texts: Drawing tile images with bigger height on floor tiles on 2.5D isometric map

texts:
Hello I am creating my first isometric game.
I have floor tiles which are 112*56 in size.
This is a simple strategy game I am making, it's an existing game, I just copied the idea for practice since I don't have anything else to do.
Each game object should be located inside the floor tile, like floor tile is the base, it can't be outside of it. All entities will be inside one floor tile, or separated.
When I try to place a rock in tiles[0][1], this happens:

(source: gyazo.com)
When I try to place it at tiles[9][9] (corner) this happens (With red borders, so you can see offsets):

(source: gyazo.com)
I am not really sure what creates this big padding when the tiles go further. The further they are, the bigger padding they will have from the tile I think.
I use this formula to locate tiles:
    int x = (this.x * width / 2) - (this.y * width / 2);
    int y = (this.x * height / 2) + (this.y * height / 2);

x = i
y = j

I've tried making offY variable, where it does imageHeight - floorTileHeight = 18, and then do int y = offY - (... formula for y ...) but no luck, the position is always randomised. Works for one position, won't work for further position.
this is the water floor tile (112x56):

this is the rock tile (112x74):

I've added red borders so you can see how big it is.
What is causing this padding between tiles when I place them?
EDIT
I am using Slick2D game library.
EDIT 2
In my program, my graphics are separated into Layers. Each layer implements Layer.
I have the layer Board, which is responsible about everything that happens on the board, the floor, it's entities, and nature objects.
That layer Board, has 2 more sub-layers in it, Nature and Entity.
Currently I am having problems with the Nature layer, which is responsible for drawing nature objects like Rocks, flowers, and more.
public class Nature implements Layer {

    private Tile[][] tiles = new Tile[15][10];

    public Nature() {
        tiles[9][9] = new Tile(9, 9, 0, 0, Tiles.ROCK);
//      tiles[0][0] = new Tile(0, -22, Tiles.ROCK);
//      tiles[0][1] = new Tile(0, -22, Tiles.ROCK);
    }

    @Override
    public void render(Graphics g) {
        for (int i = 0; i < this.tiles[0].length; i++){
            for (int j = 0; j < this.tiles[1].length; j++){
                Tile tile = this.tiles[i][j];

                if (tile == null)
                    continue;

                tile.render(g);
            }
        }
    }

    @Override
    public void update() {
        // TODO Auto-generated method stub

    }

}

The actual tile class which does the drawing:
public class Tile {

    private int offX;
    private int offY;

    private int x;
    private int y;

    public TileSprite sprite;

    public Tile(int x, int y, Tiles tile) {
        this(x, y, 0, 0, tile);
    }

    public Tile(int x, int y, int offX, int offY, Tiles tile) {
        this.x = x;
        this.y = y;
        this.offX = offX;
        this.offY = offY;
        this.sprite = new TileSprite(tile);
    }

    public int getOffX() {
        return this.offX;
    }

    public int getOffY() {
        return this.offY;
    }

    public TileSprite getSprite() {
        return this.sprite;
    }

    public int getWidth() {
        return this.sprite.getSprite().getWidth();
    }

    public int getHeight() {
        return this.sprite.getSprite().getHeight();
    }

    public void render(Graphics g) {
        int width = this.getWidth();
        int height = this.getHeight();

        int x = (this.x * width / 2) - (this.y * width / 2);
        int y = (this.x * height / 2) + (this.y * height / 2);

        x -= width / 2;
        y -= height;

        g.drawImage(this.sprite.getImage(), x, y);
    }
}


texts:
Here's a Youtube video of my problem in action ((in the video I am clicking in various directions, yet the fireball is always created facing down in some direction.))

I've been having a lot of trouble wrapping my brain around Quaternion rotations in Unity2D.

What I'm trying to do is so simple, yet it keeps beating me. I simply want to instantiate a prefab of fireball when I click the button. The problem is that I want the fireball to be facing in the direction of the mouse before firing along. I haven't gotten to the fire and velocity part because I can't get it face the right direction when it's created.

In my playercontrollerscript attached to the player Object I have this (In C#)

        if (Input.GetMouseButtonDown (0) && anim.GetBool ("canAtk")) { //Basic attack controls

        curTarget = Camera.main.ScreenToWorldPoint(Input.mousePosition);

        if(classState == "Cutter"){
            anim.SetTrigger ("attacking");
            anim.SetBool ("canAtk", false);
            StartCoroutine (AttackTiming ());
            anim.SetFloat ("animCombo", playerCombo);
        }
        else if(classState == "Flame"){
            Debug.Log (curTarget);
            var worldTarget = Input.mousePosition;
            Quaternion rot = Quaternion.LookRotation(transform.position - curTarget, Vector3.right);
            Rigidbody2D fballClone = (Rigidbody2D) Instantiate(fireBallz, transform.position, rot);

(You can safely ignore the cutter class part. The problem is when I'm in Flame class. I also have a script attached to the prefab object, but at this moment all it does is control Euler angles so it doesn't rotate along the weirdness axis.

Anyways, each time I hit the button it creates a fireball, but it's like they are 90 degrees behind where they should be. I say "like" because that's not always the case. If I click under my character, then the fireball is pointing up. If I click sort of "Down/right" it points "up/right".

This would be easier if I could visually wrap my head around how the rotations work. Any advice would be appreciated. If you need any more information or screenshots let me know as well. Thanks again.

Update: so previously I had left a line setting curTarget.z to 1 because it was returning -10 for the camera Z and I thought that was related to the problem. Oddly, when I removed that line it halfway fixed the problem. Now, if I click in the down/right or down/left or down it will create the fireball facing correct direction, but if it's "up" any, then it will pretty much face the opposite direction. Also, directly left or directly right causes the fireball to face down.

New Update: (Sort of just updating as I try to work it out.) I turned on Debug.Log(rot) just so I could see the rotation values when I create the fireball.

If I click bottom right I get (0.0, -0.6, -0.4, 0.7) the fireball is facing the correct position as it does always as long as I'm clicking in the "downish" area. When I click top right I get (-0.6, 0.0, 0.7, -0.3) and the fireball is facing Bottom-Left. So I click in the bottom-left direction and I get (0.6, 0.1, 0.7, -0.4) and it's facing bottom-left. My brain is so fried I'm not piecing it together correctly. Something I'm missing.


texts:
I'm trying to create my first C++ 2D fighting game from scratch, using SDL, and so far I got things to where I am able to move a couple sprites around using some keyboard keys. Right now, I have it so 1 unit of measurement equals 1 pixel; setting my player position to 900.0f 100.0f (my pixel units are of type float) will place him 900 pixels in the x direction and 100 pixels in the y direction.

At first, I thought that using pixels units for a sprite based 2D fighting game would make sense, but after thinking about it, I realized that I might have issues with differing screen resolutions. Someone with a higher screen resolution of 2560 x 1600 would move slower than someone with a lower screen resolution of 1920 x 1080.

Now I'm sure there would be ways to correct this specific issue, but it got me wondering if there would be better basic units of measurement I should be using for a 2D game. What should I use as units for my 2D game?


texts: What is the correct way to reset and load new data into GL_ARRAY_BUFFER?

texts:
I am using an array buffer for colors data. If I want to load different colors for the current mesh in real time what is the correct way to do it. At the moment I am doing:

glBindVertexArray(vao);
glBindBuffer(GL_ARRAY_BUFFER, colorBuffer);
glBufferData(GL_ARRAY_BUFFER, SIZE, colorsData, GL_STATIC_DRAW);
glEnableVertexAttribArray(shader->attrib("color"));
glVertexAttribPointer(shader->attrib("color"), 3, GL_FLOAT, GL_TRUE, 0, NULL);
glBindBuffer(GL_ARRAY_BUFFER, 0);

It works, but I am not sure if this is good and efficient way to do it. What happens to the previous data ? Does it write on top of it ?

Do I need to call :

glDeleteBuffers(1, colorBuffer);
glGenBuffers(1, colorBuffer);

before transfering the new data into the buffer ?


texts:
I'm having trouble rendering some of my meshes; some display just fine, some are drawn wrong or not at all.

While troubleshooting I was looking at the openGL docs (http://www.opengl.org/sdk/docs/man3/) and on the topic of glBufferSubData the following line caught my eye:

Clients must align data elements consistent with the requirements of
the client platform, with an additional base-level requirement that an offset
within a buffer to a datum comprising N bytes be a multiple of N.

I am buffering vertex + normal and index data like this:

glGenBuffers(1, &mVBO);
glGenBuffers(1, &mIndexBuffer);
glGenVertexArrays(1, &mVAO);

// buffer vertex, normals and index data
glBindVertexArray(mVAO);
glBindBuffer(GL_ARRAY_BUFFER, mVBO);
glBufferData(GL_ARRAY_BUFFER, (vertexData.size() + normalData.size()) * sizeof(float), NULL, GL_STATIC_DRAW);
glBufferSubData(GL_ARRAY_BUFFER, NULL, vertexData.size() * sizeof(float), &vertexData[0]);
glBufferSubData(GL_ARRAY_BUFFER, vertexData.size() * sizeof(float), normalData.size() * sizeof(float), &normalData[0]);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mIndexBuffer);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, indexData.size() * sizeof(uint32_t), &indexData[0], GL_STATIC_DRAW);

glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0);
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 0, (GLvoid*)(vertexData.size() * sizeof(float)));

// unbind array buffer and VAO
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindVertexArray(0);

So for the vertex and normals I first allocate the complete buffer using glBufferData and then fill it in using glBufferSubData.
My question then is, according to the docs, do I need to align the offset my normal data, and if so with what? Is this what couldve caused some meshes to draw incorrectly?


texts: Calculate XP needed for next Level using this simple algorithm?

texts:
I am currently calculating the Levels in my game using the following forumla:

player.level = mathFLOOR(mathMAX(1, 0.05 * mathSQRT(player.score)) * (1 + player.kd / 10));

So the level is based on the persons total score and their kd. However I am now trying to figure out a formula for calculating the percentage of the score/kd you need to progress to the next level. If this is not possible, how could I do it with just this formula:

 player.level = mathFLOOR(mathMAX(1, 0.05 * mathSQRT(player.score)));

Thank you for your time.


texts: In job descriptions, I often see positions called "Gameplay Programmer."  What do people in that position do?


texts: Need a better function for transportation efficiency

texts:
I'm making an economic kind of game, and one of the things I'm simulating is the transportation of resources to a central depository, e.g. moving metal from a mine to the city (so it can be turned into swords). I want it to behave so that a producer farther away from the city is considerably less efficient, but the player can bring the efficiency back up by assigning additional carters.

The function I have right now is:

efficiencyPercent = 100 - pow(9 * travelTime, 4/3)*pow(2/3, carters)

However, this doesn't have the behavior I want; carters are too powerful, either because pow(2/3, carters) converges to 0 much too fast, or because pow(9 * travelTime, 4/3) grows too slowly, or both, I'm not sure. No matter how big travelTime is, the player can overcome it by assigning a reasonable number of carters. I want it to work so that modest travelTime is defeatable by a reasonable number of carters, but once it gets too high it takes an absolutely incredible number of carters to defeat it.

What's a better sort of function that will have this behavior? I think I need the inefficiency to be exponential in travelTime but I don't know what to do about carters. Please help!

EDIT: DeadMG suggests that I have combined two effects (effect of travel time & effect of carters) that would be better off separated. I'm not sure I agree, but I'm not sure I disagree either, so I'm restating the question in support of this theory.

What I'm looking for is some kind of mechanic, involving carters and travel time, with the following behavior:

An iron mine can generate iron at a rate dependent on the number of laborers assigned to the mine; for example, 40 miners produce a maximum of 10 iron per month. This is strictly linear and I'm not changing it at this point. No matter how many carters you assign, there should never be a way to convince the mine to provide more than this amount.
In order to be used, the iron has to be transported to a city. The miners are willing to do this to some extent, but they become less willing the farther they have to carry it. If the mine is right in the middle of town, no carrying is necessary and the miners work at full power; farther away and they are forced to take time off to haul wagons. In the interest of concreteness, the miners shouldn't be willing to carry a significant amount of stuff farther than 5 days away. (I can fiddle with the exact balance later).
You can assign additional laborers (from the city's pool) as carters, allowing the miners to get on with their proper jobs. Dedicated carters are far better at moving things than miners moonlighting as teamsters. Assigning more carters should have diminishing returns. For concreteness in fiddling with constants, a mine 5-7 days away should be restored to 95% efficiency by roughly 10 carters.
The farther away the mine is, the more carters it should take to achieve a given efficiency improvement. Mines that are too far away (for concreteness, 14 days or so) should require a completely impractical amount of carters to increase the efficiency to usable levels. Ideally, in this situation the player would rather build a new city, closer to the mine, than assign such an incredible amount of workforce simply to cart things around.

The formula I have satisfies all of these except the last, which is the one I'm having trouble with. I'm particularly looking for a mechanic that provides all of these features in a "smooth" way, without arbitrary breakpoints or funny corner cases, because I want to be able to change the constants depending on the empire's technology levels. Whether this is two separate formulae as DeadMG suggests, or a single combined one like I have now, or any other kind of mechanic, I don't care. Any suggestion, up to and including the simulation of little carter automata moving around the map, is what I'm looking for.


texts:
I am performing ray triangle intersection by transforming the ray into the object space for efficiency. I am using the same technique from this question (The correct way to transform a ray with a matrix?).

My question has to do with the numeric stability of the transformed ray. This is my code

Matrix4f matModel= this->getWorldTransform();
Matrix4f matModelInverted = matModel.Inverted();
Matrix4f matInverseNormal = matModel.Transposed();

rayOrigin = matModelInverted.Transform(rayOrigin);
rayDirection = matInverseNormal.Transform(rayDirection).Normalized();

matModel is the Object-to-World transform and it is a very simple translation matrix with this value

| 1 0 0 -4 |
| 0 1 0 -15|
| 0 0 1 -13|
| 0 0 0  1 |

matInverseNormal is the transposed inverse of the matrix used to transform the ray origin and has the value

| 1  0   0  0|
| 0  1   0  0|
| 0  0   1  0|
|-4 -15 -13 1|

My code works as it should most of the time, the problem appears around certain value where the transformed ray direction behaves erratically and the ray flip flops by as much as 180 degrees for very small changes in the input.

For input ray direction {-0.59531, 0.64250, -0.48249} I get a transformed direction {-0.59531, 0.64250, -0.48249} which is visually the correct behavior. Perturbing the values of the input ray direction to {-0.59520 0.64320 -0.48169} (a change of about 10e-3 magnitude) gets me {0.59520, -0.64320, 0.48169}, which has flipped signs on all axes and is visually the incorrect behavior.

What am I doing wrong?


texts: How can I obtain a window handle in SDL 2.0.3?

texts:
I need to obtain the handle of the window for SDL 2.0.3. I got the suggestion to use info.window after initializing SDL and filling the info variable with data by calling SDL_GetWindowWMInfo(); included in the header file SDL_syswm.h. My compiler (Visual Studio 2008) gives the following error:

  226) : error C2039: 'window' : is not a member of 'SDL_SysWMinfo'
  1>     include\sdl_syswm.h(173) : see declaration of 'SDL_SysWMinfo'


texts: My sprite is not listening to any keyboard keys

texts:
First time ever creating html canvas game. Once I finally got my sprite ant tiles drawn on the canvas, now I want to make my sprite interactive. Unfortunately, for some reason it is not working. I get a message in console when the certain key is pressed but the sprite is not changing its position. I wonder why?  The code:

var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");

var mapArray = [
  [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0, 2, 2, 0],
  [0, 0, 1, 1, 1, 0, 0, 2, 0, 0],
  [0, 0, 1, 1, 1, 0, 0, 0, 0, 0],
  [0, 0, 0, 1, 1, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 1, 1, 0, 0, 0, 0],
  [0, 0, 0, 0, 1, 1, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
]

var StyleSheet = function(image, width, height) {
  this.image = image;
  this.width = width;
  this.height = height;

  this.draw = function(image, sx, sy, swidth, sheight, x, y, width, height) {
      context.drawImage(image, sx, sy, swidth, sheight,x, y, width, height);
  }
  this.drawimage = function(image, x, y, width, height) {
    context.drawImage(image, x, y, width, height);
  }
}

/* Initial Sprite Position */

var boatPosX = 230;
var boatPosY = 200;

var Loader = function(src) {
  this.image = new Image();
  this.image.src = src;
  this.image.onload = function() {
  var sprite = new StyleSheet(background, 36, 36);
  var ship = new StyleSheet(boat, 90, 100);
  for (let i = 0; i < mapArray.length; i++) {
    for (let j = 0; j < mapArray[i].length; j++) {
      if (mapArray[i][j] == 0) {
        sprite.draw(background, 190, 230, 26, 26, i * sprite.width, j * sprite.height, sprite.width, sprite.height);
      }
      if (mapArray[i][j] == 1) {
        sprite.draw(background, 30, 30, 26, 26, i * sprite.width, j * sprite.height, sprite.width, sprite.height);
      }
      if (mapArray[i][j] == 2) {
        sprite.draw(background, 200, 20, 26, 26, i * sprite.width, j * sprite.height, sprite.width, sprite.height);
      }
    }
  }
  ship.drawimage(boat, boatPosX, boatPosY, 50, 50);
}
  return this.image;
}

/* Sprite controls */

function move(e) {
  if (e.keyCode == 39) {
    boatPosX += 2;
    console.log("works");
  }
  if (e.keyCode == 37) {
    boatPosX -= 2;
  }
}

  document.onkeydown = move;

var background = new Loader("ground.png");
var boat = new Loader("ship.png");

console.log(background);


texts: Starting career with enough education but no experience?

texts:
I am a student in Game Programming at University and a lot of students like me are wondering the best way of entering the industry. With a bachelor degree in game programming, but no real experience in the game industry, how can students begin developing real projects ?

Major game companies requires you to have 2 - 3 years of experience, so how do you guys suggest us to make our way through this selective industry ? Start in smaller buisness ? Build a kick-ass demo could maybe be enough ? Massively read all game programming books we can ?

Thanks for your suggestions, the question is yours !


texts: How can I compute a velocity proportional to the difference between two hand positions?

texts:
I'm working on a project with the Kinect SDK and XNA 4. I need take the position of the hands and draw a sprite over it. I'm was doing it directly and because of that I get a "trembling hands" effect. So, I was thinking of making the sprite move from the previous position to the new one given in every frame by the new hand position.

This way, the sprite does not jump from one position to another. This is working just fine, but I'm using a constant value for the velocity, and I really would like to use a variable velocity given by the difference between the previous and the new position. That is: if the hand move more quickly in the reality, the velocity will be higher.

I really don't have a clue on how to make this work. Can somebody point me in the right direction?


texts: Tiled - Possible to create a terrain from this specific tileset?

texts:
I'm really new to Tiled and I can't get the hang of creating terrains.

I have these really nice 2D assets I would like to use but I can't get the terrains to work. I'm trying to create a dirt path terrain brush from the below tileset.

I've checked countless tutorials but nothing works. I'm starting to think these just aren't compatible with Tiled.

Could someone tell me if it's meant to be possible?

I've added a watermark to the tile image below as these are commercial assets.

Thanks!


texts: Correct me if I'm wrong, but both the Geometry Shader and the Tessellation Shader jobs are to generate vertices in the Graphic Pipeline. What I would like to know is how they are different and when should I use one over the other?


texts: Keyboard.GetState() only work first time, and Memory increase (not Disposing)

texts:
EDIT UPDATE 3
I been searching the web for a solution and found several people struggling with Memoryleak using MonoGame while trying to dispose objects.
It could be the case that MonoGame should be started and then closed as a own process, not from another program which are my case.
When I click on the button, a new thread is created and the MonoGame application is started:

 viThread = new Thread(startDemo);
 viThread.Priority = ThreadPriority.Highest;
 viThread.Start();

 private void startDemo()
 {
        using (Demo d = new Demo())
            d.Run();
 }

The "Demo" is closed by a Game.Exit command and i have also tried with Disposed(true) without any success. Next time I launch the MonoGame is Keyboard.GetsState() always empty and the memory is incresed. I made a loop where I started and closed the application 100times and it are eating my memory. I have seen lots of discussion about SharpDX not working correcly with dispsing resources. So here I am, stuck. Just want to point out that this worked fine for XNA but not now when changed to MonoGame. And again, thanks for all comments I got so far.

I have uploaded a project where you can see the issue by yourself. The second time dosn't the keyboard input work but mouseinput does and the memory is increasing for each time:

Donwload sln project

EDIT UPDATE 4

It is SharpDX which increase the memory, I perform following line before i exit:

SharpDX.Diagnostics.ObjectTracker.ReportActiveObjects().Length

And its increasing all the time. So I guess it isnt released.
Someone know how to do that?


texts: I already have a GameManager script, but need to have a 2nd one

texts:
I'm making a Unity game, and I want to use the Unity Distribution Portal.
My problem is that you have to make a script named GameManager for this, but I already have another script called GameManager, so every time I try to rename the first GameManager script, the game stops working.
I don't want to rewrite every script I've used GameManager variables in. So the way I've been trying to rename this is by right-clicking on the GameManager.cs file in the Unity project window and renaming it there, then typing a 2 in the name inside Visual Studio.
If I call the script for UDP for example something like GameManager2, UDP doesn't seem to understand that this is the script it needs for Sandbox Testing.
Can anyone help me with this?
Here is the UDP script I want to add (which is currently called GameManager2, but needs to be called GameManager):
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UDP;

public class InitListener : MonoBehaviour, IInitListener
{
    public IInitListener listener;
    public void Start()
    {
        StoreService.Initialize(listener);
    }

    public void OnInitialized(UserInfo userInfo)
    {
        Debug.Log("Initialization succeeded");
    }

    public void OnInitializeFailed(string message)
    {
        Debug.Log("Initialization failed: " + message);
    }
}


texts: Positional noise changes in Unity Editor vs compiled

texts:
I have a surface shader that adds a bit of positional noise, using the following code:

float2 uv_main = IN.uv_MainTex +
    float2(
        tex2D(_PosNoise, IN.uv_MainTex).r - 0.5,
        tex2D(_PosNoise, IN.uv_MainTex).r - 0.5
    ) / float2(_Width, _Height) * _MovementOffset;
o.Albedo = tex2D(_MainTex, uv_main);

_MovementOffset is a float, the _Width and _Height are the size of the map in world coordinates. _PosNoise is a texture that is the same for both versions.

The problem I'm seeing is that the effective noise changes between how the image looks in the Unity Editor vs when it is compiled. The effect is such that I need to multiply the MovementOffset by a factor of 2-3 to have the same effect in the compiled version.

Unity:

Compiled:

I don't understand what could be causing this, and am having some real difficulties figuring it out. Any suggestions on where to look? Thanks!


texts: How to make a horizontal scrolling menu in Game Maker Studio 1.4?

texts: I know how to place the items you see in the picture, my problem is how do I move them? How do I know if the player is swiping right or left? I made the items with a ds_list in a script file and then have an object obj_MenuCreation run that script, so if I move the obj_MenuCreation, will it move the list with it?


texts: Can .NET Core be used to make games on non-Windows platforms?

texts: If I build a game that runs on a Windows phone, does that mean it will work on Android (and future ios) with .NET core or vNext?  I do not wish to use XNA or C++.


texts:
I have the following code:

-(void)showLeaderboard {

GKLeaderboardViewController *leaderboardController = [[GKLeaderboardViewController alloc] init];
if (leaderboardController != NULL)
{
    leaderboardController.timeScope = GKLeaderboardTimeScopeAllTime;
    leaderboardController.leaderboardDelegate = self;
    [self presentModalViewController: leaderboardController animated: YES];
}

[leaderboardController release];

}

Which I am trying to use to make my leader-board pop up. The issue is cocos2d will not allow me to use the line:

        [self presentModalViewController: leaderboardController animated: YES];

How do I fix this?

Thanks

PS I am using cocos2d


texts: Game development lesson plan (9-12yr old)

texts:
I have been invited to help a couple of students make a video game. I would be working with 2-3 students aged 9-12 yrs.

The time frame is 10 x 2hr classes over 10 weeks, with plenty of preparation time on to get some assets ready.

Does any one know of an existing lesson plan for this kind of thing that I could use and contribute to; or ideas as to what the kids could achieve in this time frame? Type of game? 3d/2d? Should they make models, be given models and do programming?
Do you have any experience with what kids this age respond well to?

I have a preference towards open source frameworks, but could be convinced to use a free commercial framework if you think there is enough benefit.


texts: How can I easily implement swinging in a platformer game?

texts:
I'm developing a game in which player can use ropes to swing (just like what Spiderman or Bionic Commando did) and I'm having problem implementing this behavior. Can anyone help me how to do this, I mean physics formulas and etc. Till now I've come up with 3 ideas. One is using spring, but it consumes a lot of time and sometimes it is jumpy. The other two are trying to calculate next step (one via calculating potential energy and one via calculating torque) and both of them almost crash whenever the actor is trying to swing.

Here is the code I wrote to calculate torque:

float dx = Runner->getPosition().x - ancher.x;
float dy = Runner->getPosition().y - ancher.y;
float t0 = atan2(dy,dx); //my current angle
float k = ((dy) *vx - (dx) * vy) / (dx * dx+dy * dy); //previus angular velocity
k -= gravity * cos(t0) *dt; // new angular velocity (gravity is positive)
t0 += k * dt - acc * cos(t0) *dt * dt / 2; // rotate the rope
float dx1 = r0 * cos(t0); // new position (r0 is rope length)
float dy1 = r0 * sin(t0);
vx = (dx1 - dx) / dt; //calculate velocity
vy = (dy1 - dy) / dt;


texts: What's the right way to re-use open source game assets?

texts:
This is a hypothetical question, but one I always wanted to know about.  Suppose I wanted to create a game in the same fantasy style as Battle for Wesnoth.  Having no arts skills myself, I could write the code for the game engine and borrow (steal?) their artwork and use it myself.  IIRC, their stuff is licensed under the LGPL, so if my game were LGPL'ed I should be fine legally.

My question is: just because I can do that, should I?  What's the expected procedure for borrowing some other game's art assets?  Do I need to formally ask permission first?

Obviously I would credit their work before making anything public.


texts: Using dom elements for game interaction - slow performance

texts:
I have a need for my html5 game (using melonjs) to allow users to click tile areas on the map. The idea is it will show a css styled hover area. The browser tested is chrome.

I could do this natively in the game engine but the styling options available for canvas entities is limited. So I went with creating a dom element for each item in the canvas map. As the player moves, I update only the positions of the dom elements which are on the viewport.

Probably 70 total elements are created and only 2-3 are on the screen updating at any given time.

I'm pretty surprised how slow it's making my browser.

So my questions are:

why would updating 2-3 elements as the player moves be so slow?
is it better to remove elements when offscreen then readd when they are back on, even though they arent updating as they move off screen?
should I just scrap the dom solution altogether and rely on the api the canvas and game engines provide for styling


texts:
As the title suggests I'm developing a top down space game.

I'm not looking to use newtonian physics with the player controlled ship. I'm trying to achieve a control scheme somewhat similar to that of FlatSpace 2 (awesome game). I can't figure out how to achieve this feeling with keyboard controls as opposed to mouse controls though. Any suggestions?

I'm using Unity3d and C# or javaScript (unityScript or whatever is the correct term) works fine if you want to drop some code examples.

Edit: Of course I should describe FlatSpace 2's control scheme, sorry. You hold the mouse button down and move the mouse in the direction you want the ship to move in. But it's not the controls I don't know how to do but rather the feeling of a mix of driving a car and flying an aircraft. It's really well made. Youtube link: FlatSpace2 on iPhone

I'm not developing an iPhone game but the video shows the principle of the movement style.
Edit 2
As there seems to be a slight interest, I'll post the version of the code I've used to continue. It works good enough. Sometimes good enough is sufficient!

using UnityEngine;
using System.Collections;

public class ShipMovement : MonoBehaviour
{
    public float directionModifier;
    float shipRotationAngle;
    public float shipRotationSpeed = 0;
    public double thrustModifier;
    public double accelerationModifier;
    public double shipBaseAcceleration = 0;
    public Vector2 directionVector;
    public Vector2 accelerationVector = new Vector2(0,0);
    public Vector2 frictionVector = new Vector2(0,0);
    public int shipFriction = 0;
    public Vector2 shipSpeedVector;
    public Vector2 shipPositionVector;
    public Vector2 speedCap = new Vector2(0,0);

    void Update()
    {

   directionModifier = -Input.GetAxis("Horizontal");

   shipRotationAngle += ( shipRotationSpeed * directionModifier ) * Time.deltaTime;

   thrustModifier = Input.GetAxis("Vertical");

   accelerationModifier = ( ( shipBaseAcceleration * thrustModifier ) ) * Time.deltaTime;

   directionVector = new Vector2( Mathf.Cos(shipRotationAngle ), Mathf.Sin(shipRotationAngle) );
   //accelerationVector = Vector2(directionVector.x * System.Convert.ToDouble(accelerationModifier), directionVector.y * System.Convert.ToDouble(accelerationModifier));
   accelerationVector.x = directionVector.x * (float)accelerationModifier;
    accelerationVector.y = directionVector.y * (float)accelerationModifier;
   // Set friction based on how "floaty" controls you want

    shipSpeedVector.x *= 0.9f; //Use a variable here
    shipSpeedVector.y *= 0.9f; //<-- as well
   shipSpeedVector += accelerationVector;

   shipPositionVector += shipSpeedVector;

   gameObject.transform.position = new Vector3(shipPositionVector.x, 0, shipPositionVector.y);
    }

}


texts:
Ok, so I've already waded through a bunch of questions around this, and it's just making me even more confused.

Let's say I am trying to model a card table in a 2d game.  Behind (beneath) the table is a quad with a floor texture.  The "table" is a sprite that is just an oval (using basic shapes at this stage until I have real artwork).

I've read plenty of questions on how to scale to different device resolutions.  And, that is certainly one way to do it (bit seems like a lot of work).  I've also read posts about changing the size of the orthographic camera to match the device (this seems easier).  But i'm left not quite understanding what the frame of reference is.

Let's say I design the game to work in 16:9 at HD resolution (1920x1080).  I size the "floor" to fill the entire space (and maybe extend a little beyond).  I size the "table" to fit within a smaller portion of that space.

If you have a fixed scene (ie, not a scroller), and you want the contents to fill the entire viewport, what is the best way to go about this?  Scaling the objects, scaling the camera?

As far as units, what's the best choice?  1 PPU?  What rule of thumb do you use when choosing PPU?  What are the reasons to choose different PPU's?

I think i'm missing the forest for the trees.  I understand so many of the basic concepts from reading so many questions, I just don't know how to put them together and when to choose which method.


texts: Separate axis theorem applied to AABB misunderstood

texts:
I'm trying to implement a collision system for a 2D platformer using the SAT algorithm. For what I need, my implementation only handles AABB's, I followed the instructions given here. It works, there is only a little something I'm having trouble solving, let me explain.

In this scenario I expect the player to swing along the left side of the wall. From what I understand of the SAT algorithm, in this case, when the player reaches the bottom of one of the static entities constituting the wall, a collision on Y would happens.

To illustrate, that's what I'm trying to do in the picture, at some point, the overlap on the Y axis will become lower than the one on the X axis. Regarding the linked tutorial, the overlap on Y should then be used to create the projection vector.

It's what's happening in my implementation, I only accept collisions on X pushing away the player to the left, but it's not the case. Collision on Y happens when my player reaches the bottom of an entity resulting to an odd feeling.

Am I misunderstanding the SAT algorithm, should this case never happen? Or is there a way to avoid it?.

Here is the SAT part of my collision system implementation:

    private Vector2 testCollision(SATAABB box1, SATAABB box2, Vector2 velocity) {
        float ox = (box1.wx.len() + box2.wx.len())
                - box1.getDistanceBetweenCentersOnX(box2);
        if (ox <= 0) //no overlap on X, no collision
            return null;
        float oy = (box1.wy.len() + box2.wy.len())
                - box1.getDistanceBetweenCentersOnY(box2);
        if (oy <= 0) //no overlap on Y, no collision
            return null;

        if (ox < oy) {
            projectionVector.set((box1.center.x > box2.center.x) ? ox : -ox, 0);
            velocity.x = 0;
        } else {
            projectionVector.set(0, (box1.center.y > box2.center.y) ? oy : -oy);
            velocity.y = 0;
        }
        return projectionVector;

The SATAABB is a simple class holding half width vectors on both axis and a center position.

EDIT: After using time equations, it's way better, still a case remains I'm having trouble with. The player is moving on the ground with a positive X velocity and a positive Y velocity (gravity). Here is the equations for that particular case:

timeCollisionX = (player.topright.x - wall.topleft.x) / velocity.x;
timeCollisionY = (player.bottomright.y - wall.topleft.y) / velocity.y;

And I come in a situation where those equations are equal to:

timeCollisionX = (324,000000 - 320,000000) / 5,000000 = 0,800000
timeCollisionY = (448,200012 - 448,000000) / 0,200000 = 1,000061

Which results to a X collision where only Y collisions should occur because the difference between the player top right corner and the wall top left corner on X is lower than the actual velocity on X. Any idea on how to deal with this?


texts: How can you subscribe to Unity input events, instead of polling for them

texts:
Been trying for days to figure out if there is a way to subscribe to keyboard/mouse events in unity. Instead of having to poll for them every frame and make my own events.

Right now I poll through the inputs and fire off my own events if a button is pressed. I'd prefer to subscribe directly to Unities input events, but have yet to figure out how.

I have a Unity Answers post that may have some relevant info to my question as well: http://answers.unity3d.com/questions/878485/is-there-a-more-efficient-way-to-make-events-for-k.html


texts: How to get object position from a ray hit?

texts:
I've been coding a program to teleport an object to a player hands(which is just and empty game object). I did this using ray collision on mouse down, but I cant think of a way to find the position of the object I'm trying to teleport. I'm using GameObject.Find to find position of the hands, but I wanted to know if there was a way to find the position of an object via a ray collision. If there isn't a way to find the position of an object from a ray collision what other way could I find its position.

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

public class BasicCollisonSound : MonoBehaviour {
    public Transform hands;
    public Transform obj;

    void Start()
    {
        hand = GameObject.Find("Hand");
    }

    void Update () {
        if (Input.getkeydown("mouse1"))
        {

            Ray ray;
            RaycastHit hit;

            ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            if(Physics.Raycast(ray, out hit, 100.0f))
            {
                if (hit.collider.tag == "Grabbable")
                {

                    obj.position = hands.position;
                }
            }

        }
    }
}


texts: Combining raster textures with vector graphics. How can I do this? (See image)

texts:
I'm developing an art style that combines pixel art with simple vector graphics, but I'm feeling lost and need clarity what is technically possible within game engines.

First of all, take a look at this image:

How can I achieve this look with game engines/libraries? Is it even possible?
What can you recommend?

The game is supposed to run on PC, 60fps preferable, uses pixel sprites for smaller objects, while using simple shapes to represent very large objects. I want it to have a lighting system, all shapes must be able to rotate, move and scale at runtime and have seamlessly tiling pixel art textures drawn on top of them.


texts:
I'm almost fresh to the game development and I have one question about libraries.

If I choose one library, such as SFML, to develop the menu of my game, is it possible to merge with, for example, Direct X to handle the graphics(load maps and etc)?


texts:
following my previous post on random world map generation, I used several algorithms and obtained results similar to this: http://i.imgur.com/CKL2R.png (the height values are quantisied for viewing but they go from 1 to 500 before quantisation).
Now I am trying to improve the "lakes", as you can see, the water bodies that are inside the map are always at 0 altitude, which means that every lake would be at the ocean level.
I am willing to keep these "ocean-level lakes" (or remove them), but I would like suggestion on how to create from this heightmap real lakes that would be possibly at any height, while keeping most of the altitude structure (ie mountains positions, etc)

thanks


texts: Unity 3D rotating object around 2 axes rotates it around 3

texts:
I am developing a 3D space shooter and I've fount that when triying to rotate the ship using X and Y axes it also rotates on the Z axe.

The answer
here helped me a lot, but now when I try to rotate on 3 axes I have the same problem on the 2 axes sharing local space.

The code I have right now is this:

    float rotZ = 1;
    float rotLeftRight = Input.GetAxis("Mouse X") * mouseSensitivity;
    float rotUpDown = Input.GetAxis("Mouse Y") * mouseSensitivity;
    transform.Rotate(0, rotLeftRight, 0, Space.World);
    transform.Rotate(-rotUpDown, 0, 0, Space.Self);
    transform.Rotate(0, 0, -rotZ, Space.Self);

Anybody knows how to make all 3 rotations independent from each other? Thanks!


texts: How can I achieve area fill in the video?

texts:
I am trying to clone a game while learning Unity but I am stuck. How can I achieve area fill like shown in this Area Fill Example Video?
When I searched for it I found the "Flood Fill" algorithm but I am also not sure is it the right solution for this or not. Because in flood fill we have to select a point and check neighbors with same value and convert them, however here how can I decide which point to select and fill?
For example at 00:03 in video I close an area and game fills the area with cubes. With flood fill, if I select a starting point above that line, algorithm can travel through all outer tiles and very well can fill them with cubes also but game fills lesser area there. Why does the game pick a smaller area here? How do they decide which portion of the game field they should fill?
And in 00.11 when cube hit white wall they completely fill the remaining area because I guess they assume it is fully closed. But again my question is how can you decide that? Which methods provide area fills like this?
If someone has an idea or experience about this can points me to the right direction I'd really appreciate. Thanks in advance.


texts: What is an axis aligned integer bounding box?

texts: In this paper, in the Distance field computation section, it says that an axis aligned integer bounding box of a Prism has to be calculated. Can someone explain what an axis aligned integer bounding box is and how can it be calculated for a Prism?


texts: Silverlight player centered viewport example

texts:
I am new to game development and i want to use silverlight for it.
First of all i want to learn the logic of player centered gameplay.
Something like this;

Player character moves in large scaled map but player can see only the viewport (centered on player) like on 3000x3000 px map with 400x400 viewport

what do i need to achive this?
Is there a code example or any bookthat contains this?
Do i need to use a map generator? (so when player moves it replaces titles according to matrix text file etc)

Thanks.


texts:
the problem:

"Is Head Mounted Display Enabled" seems to always return false on samsung Gear VR.
so the camera is not locked to the HMD and it will use the default camera's not the ones for hmd.
the checkboxes under the camera settings are checked.

how to reproduce:
 (osig and nvpack is already
    installed)

create a clean Top Down blueprint
template "Mobile/Tablet", "Scalable
3D or 2D", "No Starter Content"
enable the plugins "Gear VR" and the
"Oculus Library" and disable all
other in the VR section.
in the project settings configure
for andriod, set the minimum and
target SDK version to 19, turn on
"configure the android minifest.xml
for deployment for gear vr".
package the project for "Android
ETC2".

hardware:

Samsung Galaxy S7 Edge (SM-G935F)

Gear VR (SM-R322)

software:

Android 6.0.1

UnrealEngine 4.12


texts:
I've upgraded my project to LWRP, I've changed my materials to: LWRP/lit. But in one of the gamemodes i need to change one my materials' color by script. I used to do it simply like wallMat.color = Color.red, but at LWRP that code doesn't work, how to fix it?

Edit: LWRP = Light Weight Render Pipeline


texts: Build pipleine between 2 points take rotation into account

texts:
Given a start point and start rotation and end point and end rotation, how can i find a path from start to end, that takes rotation into account and moves only on the axis. I currently have a code that can handle straight line and a L turn. I want it to be able to handle also S or U turn (like on this image), but i cant figure out how to do it. Below is my current code for handling the pipleine building.
How do different games handle that? Like satisfactory fluid pipes on vertical mode.
 Vector3 endPos = endPosition;
        Vector3 startPos = startPosition;
        Vector3 dir = startRotation * Vector3.forward;
        Vector3 diff = endPos - startPos;

        Conveior prev = startTarget;
        int dist1 = Mathf.RoundToInt(Vector3.Scale(diff, dir).magnitude);

        BuildStraight(dist1, ref startPos, dir, startRotation, ref prev);
        Vector3 endDir = endRotation * Vector3.forward;
        GameObject temp;
        if (dir != endDir)
        {
            temp = GameObject.Instantiate(turnRight, startPos, Quaternion.AngleAxis(Vector3.Angle(prev.transform.right, endDir), dir) * startRotation);
        }
        else
        {
            temp = GameObject.Instantiate(straight, startPos, startRotation);
        }
        temp.GetComponent<RaycastController>().dontIgnoreRaycast();
        temp.transform.Find("DirectionGuides").gameObject.SetActive(false);
        Conveior t = temp.GetComponent<Conveior>();
        if (prev != null)
        {
            prev.SetNext(t);
        }
        prev = t;

        diff = endPos - startPos;
        int dist2 = Mathf.RoundToInt(Vector3.Scale(diff, endDir).magnitude);
        startPos += endDir;

        BuildStraight(dist2, ref startPos, endDir, endRotation, ref prev);
        if (endTarget)
        {
            prev.SetNext(endTarget);
        }

    private void BuildStraight(int distance, ref Vector3 startPos, Vector3 dir, Quaternion rotation, ref Conveior prev)
{
    for (int i = 0; i < distance; i++, startPos += dir)
    {
        GameObject go = GameObject.Instantiate(straight, startPos, rotation);
        go.GetComponent<RaycastController>().dontIgnoreRaycast();
        go.transform.Find("DirectionGuides").gameObject.SetActive(false);
        Conveior c = go.GetComponent<Conveior>();
        if (prev != null)
        {
            prev.SetNext(c);
        }
        prev = c;
    }
}


texts: How do you detect which side of a cube is facing up/down/left/right?

texts:
Please imagine a scene that shows a cube. Both the camera and the cube can be randomly positioned and rotated. How can you tell which side of the cube is facing up/down or left/right?
Or in other words: What's the math to find a cube's orientation in relation of the camera?
Your advise is very much appreciated. Thank you.
Edit:
Here's a screenshot:

The camera is "locked" onto the cube. I.e. one of it's sides is facing directly into the camera. Both cube and camera are rotated in 90 degree steps, so that each face of the cube is always in parallel to the camera's axis's. How can you tell which face (or color in the screenshot above) is pointing left/right/up/down?
Thank you!


texts: Is it worth having AI opponents step in for disconnected players in an online multiplayer card game

texts:
I have an online multiplayer card game resembling spades/bridge and I want to implement a system that autoplays when a client disconnects. Right now, there is a client and server. In the new system, there will be an autoplay server sitting between the client and the actual game server.

The client connects to the autoplay server which in turn connects to the game server. If the client disconnects during a match, the autoplay server is activated.

Both servers will reside on the same machine so communication cost should be minimal. Processing cost should be minimal as well as the autoplay will be programmed with limited skills only to keep the match going till the end. The idea is not to break the game flow once a player disconnects. But, I don't see autoplay systems in popular commercial games such as Zynga poker (maybe in this case because a disconnection can be easily be considered as a Check or Fold.) Well, is it really worth it to have an extra layer for autoplay?

Edit: Are there other drawbacks for having an extra layer for autoplay?


texts: How to avoid recursive and or infinity loop monogame return function

texts:
This piece of code is returning on a infinite base how to fix?

public GuiElement MoveElement(int x, int y)
{
    GUIRect = new Rectangle(GUIRect.X += x,GUIRect.Y += y,GUIRect.Width,GUIRect.Height);
    return MoveElement(x,y);
}

this is where i set the values i have in my Other class

        gm.Add(new GuiElement("BackGround"));

        gm.Add(new GuiElement("Play_Button").MoveElement(150, 50));

        gm.Add(new GuiElement("HighScore_Button"));

        gm.Add(new GuiElement("Quit_Button"));

basicly i want a to be able to move some elements using that MoveElement

it creates a infinite loop

An unhandled exception of type 'System.StackOverflowException' occurred in giftman.exe


texts: In unity game appears dark exporting to ios what happened?

texts:
Everything appeared darker when I exported my game to iOS.  I only updated my Unity to 4.6.3 .
Any idea why?


texts:
I am creating a 2D game for mobile phones. It's in pixel style. Now I want the player to be able to create his own character based on givin items like: Hair, Eyes, Skin, Clothes, etc. (like in Starbound for example)

What is the best way to achive that. Should I create everything as a single texture with all frames of the animation of it (like a moving hair and clothes) and after the creation of the character, put those together to a single sprite with the giving items and frames? Or do you guys have any better ideas?

I am thankfull for every piece of help!

EDIT

Actually I did not started programming the character generation yet.
I am creating a RPG and want the players to be able to create individual characters (also with armor contents). Just kind a like in Starbound.

What I want from you guys are the best ways to realize such a system. With best I mean fast, simple and safe.


texts: How to implement a mechanism to select language specific expression (python)?

texts:
On a game server, programmed in python, I want to be able to select language specific expression, according to the user's preference. Provided a 'name tag' and a 'language identifier' I want a function to return the appropriate text for the specified tag in the given language, for example

> print(foo("turn left","de"))
Bitte nach links abbiegen
> print(foo("turn left","en"))
Turn left please

I hope you get the point.

Is there something available for python which can provide a solution? I am not looking for gettext or something which uses the computer's locale setting for the language! I am looking for a solution which might work similar, but works as given in the example.

Or is it better to code something like this by oneself? How then to store the language phrases in a best way? Just in a big text file? A data base? ...?


texts: How to design a multi-step game menu system?

texts:
I am getting started with game programming. I am designing a game that starts by taking you through a series of menu screens. I am interested in learning how this is typically structured in professional game development.

Currently I handle the controller inputs from the main file and have individual classes for each menu screen. When the user makes a selection, I need to transition to the next menu screen. It seems like I either need some sort of "menu screen manager" for keeping track of the previous selection and transitioning between menu screens, and/or I need to pass the controller input handling down to the menu objects, since I want to use up/down on one menu and left/right on the other menu.

How would a professional game programmer architect/design this?

require "components/first_menu"
require "components/second_menu"

first_menu = FirstMenu.new
second_menu = SecondMenu.new
menu = first_menu
menu.render

on(controller: "up")   { menu.prev_option }
on(controller: "left") { menu.prev_option }

on(controller: "down")  { menu.next_option }
on(controller: "right") { menu.next_option }

on(controller: "buttonA") do
  if menu.is_a? FirstMenu
    menu.hide
    selected_option = menu.select_option
    menu = second_menu
    menu.show(selected_option)
  else
    selected_option = menu.select_option
    launch_game(selected_option)
  end
end


texts: Line Rendere Default Pink Color still Visible

texts: I am using the line Renderer for shooting in my game. Everything works well except for the fact that the default pink color is still visible. I have a Material set, so I do not think it is a problem of materials lacking. Someone Help please.


texts: I am finding it very difficult to learn DirectX 11. The MSDN website is just full of unorganized information that doesn't seem to help at all. I am particularly looking for something that explains many if not all aspects of developing with DirectX 11. I have been searching for weeks and still come up empty. I have found some books but they don't really explain the fundamentals of the language at all. Thanks in advanced.


texts: Progressively loading the racing arena in a 3D driving sim

texts:
I need advice and resources on a 3D car simulator.
I want to progressively load the track for the player as I'm thinking of porting the game to mobile devices.
This seems too difficult to me as I'm trying to separate the racing arena model design and the code as much as possible. Is there a structured method for achieving that for any model (arena/map). I think this is something that comes up a lot in games in general not just this instance.


texts:
I'm currently trying a develop a small game similar to http://www.estiah.com/.

Basically, there are 2 teams of 1 or more actors each, everyone with their same deck. Turn order is fixed and each card is automatically played when drawn, so games play out automatically. I already got the basic game loop, game state and history and turn order and currently try to create a fluent API, that makes it easier to add cards later on.

Each card consists of multiple effects, that can either target the current user, a random ally/enemy, a specific ally/enemy based on some criteria (like, enemy with lowest hp) or all allies/enemies/everyone. On top of this, effects may also have some kind of setup/cleanup, that should only be executed once before/after all targets have been processed.

Below are the use cases i can currently think of:

apply 1 effect to self
apply 1 effect to a random ally/enemy
apply 1 effect to a ally/enemy matching criteria
apply 1 effect to all allies/enemies
apply 1 effect to everyone
apply multiple effects to either of the above (targets should not change between effects, even if, for example, the "enemy with lowest hp" is different after the first effect)
execute effects based on a condition on the user
execute effects based on a condition for each target

Conditions/targets should be resolved during effect execution, since previous effects might influence them (unless multiple effects are joined and assigned to the same target, in which case it should not change between effects, as stated above).

Since the theory probably isn't very expressive, i already developed a basic system, which can be found over here: https://codereview.stackexchange.com/questions/189732/designing-a-system-to-apply-multiple-effects-to-one-or-multiple-targets.

The current system allows me to do things like:

public class MyCard implements Card {
    public Effect getEffect() {
        dealPhysicalDamage(10).to(randomEnemy());
    }
}

Where dealPhysicalDamage(...) returns an instance of TargetedEffect, randomEnemy() returns an instance of TargetSingle and the to(...) method binds the target to the effect, converting it into a plan Effect, which in turn can get executed by the game engine. This modifies the current game state, which gets deep cloned into a history for later usage as a battle log.

I've been trying for days to come up with a better system that gives me the freedom to apply 1-n effects to 1-n targets (single target effects will be the majority), while keeping the API as compact as possible. I'm probably too deep in the code to get a clear view, so maybe someone else can come up with an idea.


texts: How do I convert an image into a tile map?

texts:
I am working on a game in Pygame/Python, and I'd like to turn an image into a map.

The idea is simple: Pixels in the image are colored by tile type. When the program loads the image, I want the color (e.g. #ff13ae) to be matched to a certain grass tile, and the color (e.g. #ff13bd) to a different tile.

I know that I may have to convert from hexcodes to RGB, but that is trivial. I just want to know the way I to go about loading an image file, mainly because all my other games don't do anything of this sort.


texts: About floating point precision and why do we still use it

texts:
Floating point has always been troublesome for precision on large worlds.

This article explains behind-the-scenes and offers the obvious alternative - fixed point numbers. Some facts are really impressive, like:

"Well 64 bits of precision gets you to the furthest distance of Pluto from the Sun (7.4 billion km) with sub-micrometer precision. "

Well sub-micrometer precision is more than any fps needs (for positions and even velocities), and it would enable you to build really big worlds.

My question is, why do we still use floating point if fixed point has such advantages? Most rendering APIs and physics libraries use floating point (and suffer it's disadvantages, so developers need to get around them).

Are they so much slower?

Additionally, how do you think scalable planetary engines like outerra or infinity handle the large scale? Do they use fixed point for positions or do they have some space dividing algorithm?


texts: Why would it be faster to render using multiple canvas elements?

texts:
This video suggests that rendering using multiple canvas elements helps performance.

How does this work?

The idea was to use one for the player, one for the enemies, another for the background, though I really don't understand how could it be faster if you use more of the same thing.

Could someone clarify?


texts: XNA Framework doesn't recognise controller

texts:
So just a little bit of XNA code:

if (this.IsActive && (Keyboard.GetState().GetPressedKeys().Length > 0 || Mouse.GetState().LeftButton == ButtonState.Pressed || Mouse.GetState().RightButton == ButtonState.Pressed || Mouse.GetState().MiddleButton == ButtonState.Pressed) || GP_state.GetButton(8) == ButtonState.Pressed)
                    {
                        Current_GameState = GameStates.Game;
                            bg_music.Play();
                    }

If something is done --> Switch to a different game state.
Works with: Keyboard and Mouse, but not with the gamepad (which is new and it works with other games) So why does XNA not recognise it correctly??

EDIT: I do have a working solution and mark my own answer as soon as possible as right...


texts: Resizing canvas to match screen size in Unity WebGL

texts:
I'm learning how to make a browser game with Unity. I have set up the screen display dimensions to 960 x 640 (I read that it's a safe resolution to use. Feel free to correct me). I created a Canvas and set it to match with width or height, and I set Reference Resolution to 960 x 640.
The problem is that the canvas doesn't match the screen properly and empty leaves bars at the top and bottom. I get the same result using both Render Modes for Camera and Overlay. I understand that the matching options choose either width or height, depending on the slider setting.
Can I somehow match the canvas to the display properly?
Screenshot of the Canvas
Screenshot of the Canvas setting
Screen as displayed in the browser


texts: Which is better for a beginner, UDK or Unity?

texts:
I am just getting into game development and I would like to know which engine would be best to learn first.

In terms of my current skills, I know a good deal of javascript, but not much beyond that. This is all a learning experience for me (I am an extremely fast learner).

I am using HTML5 canvas right now as that's mostly what I was hinting at when i said javascript. I probably should have made it a bit more clear.


texts:
I'd like to introduce seamless level loading which means I need multiple threads. The main thread is for rendering the current scene (or for non-seamless level loading a progress bar) while the other thread is loading the resource files and sending data to the graphics card.

Now I have the following single threaded architecture: when the graphics device is initialized, a dummy window and a "shared context" is created. This is the only rendering context (HGLRC in Windows terms) I'm creating. Every time a new window is created and the graphics device is asked to create a "renderable surface" into that window, the same "shared rendering context" is used. I can do this because I set the same pixel format for each window, so there is no point to make multiple rendering contexts (that would just make my life harder than it should). Here is a small image representing the current design:

I've read some topics about this but now I'm confused since I read really different point of views, so I have some questions:

As far as I know an OpenGL context can be active in a single thread only (at a time). This means that I need another "loading rc" which shares resources (through context creation or *glShareList) with the "shared rc". Every time I create a new thread to load something, I have to set the "loading rc" active in that thread. Am I right?
Can I use the same dummy device context (HDC) in the loading thread?
Because I have a single GPU the commands sent to the graphics card are queued up. Right? Will this behaviour introduce switches between shared and loading contexts?
Is there anything else I should take care of?


texts: Why does SDL render the background from the operating system to the window?

texts:
My code displays a fully transparent window that copies the background from the operating system.

This is the code I use for rendering:

void render()
{
    SDL_RenderClear(renderer);
    SDL_SetRenderDrawColor(renderer, 255, 0, 0, 255);
    SDL_RenderDrawRect(renderer, &background);
    SDL_RenderPresent(renderer);
}

And this is the code I use to create my window:

window = SDL_CreateWindow("title", posX, posY, windowWidth, windowHeight, SDL_WINDOW_OPENGL);


texts: How to make a shattering effect similar to Housemarque's Nex Machina?

texts:
After playing Nex Machina for a while, the shattering effect which turns monsters and scenes into cubes really fascinated me and I can't hold my curiosity to explore how they made it. I have tried to google some relevant material but I only found a video which introduces the game engine theory of Nex Machina and a blog post which briefly shows and introduces how they made the effect.

According to the information I have gathered, this shattering effect is achieved via ray tracing and morphing technique, but I don't know how exactly they implemented this. I have found a "Ray-tracing morph" solution here but obviously, it can not achieve the "Cube" effect in Nex Machina.

Since no GDC talk or technical blog is found from Housemarque, we can only guess how they implemented this. Any discussion is welcomed!


texts:
I want to make a simulation of water drops producing waves, in OpenGL with C++. I calculated the height for each point of my plane grid in the 'Vertex Shader' with this formula:

The problem is that I don't know how to generate the waves so they gradually advance.

This is what my waves look like:

I want to have one circle at the beginning instead of all of them. The first circle should get bigger, like in the photo.

How do I do this?


texts: What is the correct multiplication order for a 2D matrix?

texts:
I'm currently trying to create a camera and entity/model matrix for my 2D game similar to that of Unity3D.
I've already tried to find answers to this question on stackoverflow/gamedev but i couldn't find an answer that explains how to center the camera and image.

Goal:

Have a camera matrix wich is centered at the position of the camera.
Have a entity matrix wich draws everything centered

Current implementation:

camera: matrix = Matrix.translation(Screen.width * 0.5, Screen.height * 0.5) *
                 Matrix.rotation(camera.rotation_radians) *
                 Matrix.scale(camera.scale.x, camera.scale.y) *
                 Matrix.translation(camera.x, camera.y);

entity: matrix = Matrix.rotation(entity.rotation_radians) *
                 Matrix.scale(entity.scale.x, entity.scale.y) *
                 Matrix.translation(entity.x, entity.y);

image component draw function:
                 setMatrix(camera.matrix * entity.matrix);
                 drawImage(x=0, y=0, image) // position is already included in the entity matrix

Results:

Image rotates around the upper-left corner of the screen not around it's center
Image is not centered. The image's origin is at its upper-left corner.
The camera matrix seems to be correct.

Questions:

What is the correct multiplication order for the entity/model matrix?
Can i use a single matrix for all components of a entity or do i need to calculate in the width/height of the image/text/animation component.


texts:
I'm creating a game where hundreds of rockets with colliders attached are shooting at a player.  Should I write my script where:

1: The player script reads the collision from hundreds of rocket colliders
or
2: Each rocket collider updates information when colliding with the player

Thanks!


texts:
I have this struct array in GLSL.

struct Test {
    vec2 value1;
    vec3 value2;
    float value3;
}
uniform Test u_test[5];

How can I modify the elements of this array one at a time?

I know that the location of individual objects in an element in the array can be accessed using glGetUniformLocation(program, "u_test[0].value1") but I'd like to upload an entire instance of Test at once.


texts: What is the difference between ambient lighting and skylight?

texts: What is the difference between ambient and skylight lighting? Please give me a detailed description of the differences.


texts: XNA soundEffectInstance set to loop, does not loop

texts:
Using the code below I can play background music, this works. Eventhough I've set 'IsLooped' to 'true', the sound won't loop.

What Am I doing wrong?

protected override void LoadContent()
    {
        // background music
        SoundEffect bgEffect;
        bgEffect = Content.Load<SoundEffect>("background_music");
        SoundEffectInstance soundEffectInstance = bgEffect.CreateInstance();
        soundEffectInstance.IsLooped = true;
        soundEffectInstance.Play();


texts: Texture gets blurry when moving Box2D body

texts:
I'm having this issue that is very annoying. Somehow the texture of the player body is getting blurry and leaving a slight trail with its colors when moving it. The interesting fact is, this only happens when the player is moving in the air. I set linear velocity to move the player on the ground and I'm applying force to center to move the player when he's jumping.

I also tried using just a simple sprite. I played with Texture Filters and it didn't change anything. I even tried different textures. I'm calling Gdx.gl.glClear, which should have solved this issue.

Here's the render method of my Screen class:

@Override
public void render(float delta) {
    Gdx.gl.glClearColor( 1, 0, 0, 1 );
    Gdx.gl.glClear( GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT );
    camera.update();
    game.batch.setProjectionMatrix(camera.combined);
    world.step(Gdx.graphics.getDeltaTime(), 6, 2);
    debugMatrix = game.batch.getProjectionMatrix().cpy().scale(pixelsToMeters, pixelsToMeters, 0);
    game.batch.setProjectionMatrix(camera.combined);
    tiledMapRenderer.setView(camera);
    tiledMapRenderer.render();
    game.batch.begin();
    player.update();
    player.render(game.batch);
    game.batch.end();
    debugRenderer.render(world, debugMatrix);
}

Here's the part in the player's update method where I move him if he's jumping. This is the only movement in the game that causes the texture to get blurry. Same thing for the left side except the "-" sign when applying force to center:

if (Gdx.input.isKeyPressed(Input.Keys.RIGHT) && !rightCollision) {
        playerDir = Direction.right;
        if (playerState == State.jumping) {
            playerBody.applyForceToCenter(250f, 0f, true);
        } else {
            playerState = State.walking;
            playerBody.setLinearVelocity(1.2f, 0f);
        }
    }

And here's the part that makes the player jump:

if (Gdx.input.isKeyJustPressed(Input.Keys.UP) && playerState != State.jumping) {
        playerBody.applyLinearImpulse(new Vector2(0, 500f), playerBody.getWorldCenter(), true);
        playerState = State.jumping;
    }


texts: I'm trying to create a football game where the user will make a flick gesture in order to kick the ball. I'm quite new to developing games in unity3d, I have successfully made a moving ball, added some rotation, gravity and some basic input (the ball follows the touch coordinates). How can I achieve the flick gesture?


texts: XNA: draw a sprite in 3d, is that possible?

texts:
since now I always used sprited to draw in 2D:

spriteBatch.Draw(myTexture, rectangle, color);

(I suppose the texture is binded internally to 2 triangles and then scaled.)

Now, I'm porting my game in 3D and I have to draw several planes (walls, floor, roof,..). Do I need to manually binding a texture to a geometry (for example using VertexPositionColorTexture with VertexBuffer and IndexBuffer), or is there any simpler way to do that?

I'm looking for something like spriteBatch.Draw with the rectangle clip specified in 3d space:

spriteBatch.Draw(myTexture, rectangleIn3D, color);


texts: SceneGraph in Entity Component System, Transformations

texts:
I'm recently learning entity component systems, and started implementing it into my test engine, however I'm having an issue integrating this with scene-graph, which I'm trying for the first time.

All my entities have a TransformComponent which transforms the entity in the scene, with it's position, rotation and scale. This is how I'm doing this:

transform.reset();

Entity entity = this.entity;

while (entity != null)
{
    if (!lockScale) transform.scale(entity.scale);
    if (!lockRotation) transform.rotate(Vector3.AXIS_Z, entity.rotation);
    if (!lockPosition) transform.translate(entity.position);

    entity = entity.parent;
}

The TransformComponent is present for all the entities, and hence it cannot be removed from the entity, I restrict it.

Now I have another component, called as CollisionComponent which contains the polygon, and a callback when a collision occurs, along with a collision tag. It updates the polygon position upon update:

polygon.setPosition(entity.position);
polygon.setRotation(entity.rotation);
polygon.setScale(entity.scale);

This is working for all the entities that are in the scene root, they are displayed at their correct positions, and also the collisions are working. The issue starts with the entity's children if they are present.

I have attached a child entity with position set to (0, 50) whose coordinate system is local to the parent entity system. But here, the graphics work correctly, on rotating the parent, the children rotate too due to the transform matrix, but the polygon stays at the local position.

The solution that I'm thinking now is to make the entity positions in global coordinate system, even if they are in the children of an entity, and have the transform change correctly even when the parent moves.

How can I do that?


texts: How move sprite in Java 2d (swing) with keyboard?

texts:
I'm practicing some simple techniques with Java swing games, to learn the basics. Right now I'm practicing how to move a sprite... but it's not working! whhyyyy

Here is what I've come up with so far (Main class):

public class GraphicsPracticeDrawing extends JPanel implements Runnable{

private CoinSprite coin2;
private Thread animate;

private final int DELAY = 25;

public GraphicsPracticeDrawing(){
    setBackground(Color.BLACK);
    this.addKeyListener(new InputHandler());

    Initialize();
    animate = new Thread(this);
    animate.start();
}

public void Initialize(){
    coin2 = new CoinSprite("images/coin.gif", 25, 25);
}

public void paintComponent(Graphics g){
    super.paintComponent(g);

    Graphics2D g2d = (Graphics2D)g;
    g2d.drawImage(coin2.getImage(), coin2.getX(), coin2.getY(), null);
}

@Override
public void run() {
    long beforeTime, timeDiff, sleep;

    beforeTime = System.currentTimeMillis();

    while(true){
        coin2.move2(); //move the 2nd coin based on the inputHandler
        repaint();

        timeDiff = System.currentTimeMillis() - beforeTime;
        sleep = DELAY - timeDiff;

        if(sleep < 0)
            sleep = 2;

        try{
            Thread.sleep(sleep);
        } catch(InterruptedException e){
            System.out.println("Animation interrupted!");
        }

        beforeTime = System.currentTimeMillis();
    }
}

/*
 * create a inner class to handle key inputs via the CoinSprite class
 */
private class InputHandler extends KeyAdapter{
    public void keyPressed(KeyEvent e) {
        coin2.keyPressed(e);
    }
    public void keyReleased(KeyEvent e) {
        coin2.keyReleased(e);
    }
}

}

and for my CoinSprite class:

public class CoinSprite {

private BufferedImage img;
private int speedKeyX, speedKeyY;

public CoinSprite(){ }

public CoinSprite(String fileLoc, int x, int y){
    try{
        this.img = ImageIO.read(new File(fileLoc));
    } catch (IOException e){
        System.out.println("Can't load file!");
    }

    this.x = x;
    this.y = y;
}

/*
 * move the sprite based on key inputs
 */
public void move2() {
    this.x += this.speedKeyX;
    this.y += this.speedKeyY;
}

public void keyPressed(KeyEvent e) {
    if(e.getKeyCode() == KeyEvent.VK_LEFT) {
        speedKeyX = -1; //when move is, called change the speed
    }
    if(e.getKeyCode() == KeyEvent.VK_RIGHT) {
        speedKeyX = 1;
    }
}

public void keyReleased(KeyEvent e) {
    if(e.getKeyCode() == KeyEvent.VK_LEFT){
        speedKeyX = 0;
    }
    if(e.getKeyCode() == KeyEvent.VK_RIGHT){
        speedKeyX = 0;
    }
}

//GETTERS
public BufferedImage getImage(){ return this.img; }
public int getX(){ return this.x; }
public int getY(){ return this.y; }

//SETTERS
public void setX(int x){ this.x = x; }
public void setY(int y){ this.y = y; }

}

When I run the game and press left and right the sprite wont move! I don't know why...


texts: How does a game like Doodlejump generate its "level"?

texts:
How does the game Doodlejump for iphone generate its stage? Are the platforms randomized in some way? If so, how do they make sure it doesn't generate impossible combinations?

If it's not randomized, how do they make sure it's different (or varied enough) every time?


texts: Create dynamic cities of perspective angle x with least amount of tiles

texts:
I found you can create unique building sizes with perspective with six tiles using parallel projection, whose angles are always 45 degrees... this allows you to connect to the next tile without issue:

The issue with that is you're stuck to a 45 degree angle... I feel like a 75 degree angle better matches my game's overall perspective...

But doing anything other than 45 degrees limits how deep my building is (how far back the building top goes)... so this seems to force me to create additional buildings if I want to make the top reach back further... Which adds complexity

Question:

Is there a way to achieve what I'm doing for any angle I choose such that I can create one building tileset (of 6 tiles) and create dynamic cities?

Or, do I have to sacrifice the angle of my choosing and go with the simple 45 degrees?

Thanks


texts: Crash on creating pipeline state - "the parameter is incorrect" - HRESULT 0x80070057

texts:
All input appears valid, although the DirectX12.ShaderByteCode() pointer is null - I don't know if that's indicative of anything; the buffer does contain data.

Edit: Diagnostic hub output:

Profiling of 'Graphics Frame Capture' started.
Graphics Frame Capture has exited.
Profiling of 'Graphics Frame Capture' stopped.

Edit2: Debug output:

Exception thrown: 'System.Runtime.InteropServices.SEHException' in SharpDX.Direct3D12
An unhandled exception of type 'System.Runtime.InteropServices.SEHException' occurred in SharpDX.Direct3D12
External component has thrown an exception.

Code:

var pipelineStateDesc =
    new GraphicsPipelineStateDescription
    {
        BlendState =
            BlendStateDescription.Default(),
        DepthStencilFormat = SharpDX.DXGI.Format.D32_Float,
        DepthStencilState =
            new DepthStencilStateDescription
            {
                IsDepthEnabled = false,
                IsStencilEnabled = false
            },
        Flags = PipelineStateFlags.None,
        InputLayout = inputLayout,
        PixelShader =
            new ShaderBytecode(pShader),
        PrimitiveTopologyType =
            PrimitiveTopologyType.Triangle,
        RasterizerState =
            RasterizerStateDescription
            .Default(),
        RenderTargetCount = 1,
        RootSignature = rootSignature,
        SampleDescription =
            new SharpDX.DXGI.SampleDescription(1, 0),
        StreamOutput =
            new StreamOutputDescription(),
        SampleMask = int.MaxValue,
        VertexShader =
            new ShaderBytecode(vShader)
    };

pipelineStateDesc.RenderTargetFormats[0] =
    SharpDX.DXGI.Format.R8G8B8A8_UNorm;

// Crash happens here.
// Pointer-to-implementation.
// .GetDevice returns the SharpDX.Direct3D12.Device.
pipelineState =
    graphicsDevice
        .ImplAs<GraphicsDeviceInternal.GraphicsDeviceImpl>()
        .GetDevice.CreateGraphicsPipelineState(
            pipelineStateDesc
            );


texts: Drawing with SpriteBatch and GraphicsDevice.DrawPrimitives

texts:
I've faced with a problem when i tried to draw 2d game with SpriteBatch and GraphicsDevice.DrawUserPrimitives. I suppose that what is drawing with SpriteBatch has higher priority, because i can not see a result of its rendering. GraphiscDevice.DrawUserPrimitives renders only if i comment a line of rendering background. Here is my method Draw. Could you check the order of rendering. What is the reason?

protected override void Draw(GameTime gameTime)
{
    GraphicsDevice.Clear(Color.BlanchedAlmond);

    basicEffect.CurrentTechnique.Passes[0].Apply();

    spriteBatch.Begin();
    spriteBatch.Draw(background, new Rectangle { X = 0, Y = 0, Height = Bounds.Height, Width = Bounds.Width }, Color.White);

    DrawCell();
    spriteBatch.DrawString(defaultFont, "fps: " + FPS, new Vector2(10, 75), Color.DarkBlue);

    spriteBatch.End();

    base.Draw(gameTime);
}

private void DrawCell()
{
    basicEffect.Texture = cellBody;
    graphics.GraphicsDevice.DrawUserPrimitives<VertexPositionTexture>(PrimitiveType.TriangleList, cell.Triangles, 0, cell.Triangles.Length / 3);
}

protected override void Initialize()
{
    basicEffect = new BasicEffect(graphics.GraphicsDevice);
    basicEffect.TextureEnabled = true;
    basicEffect.Texture = bg_menu;
    basicEffect.World = Matrix.Identity;
    basicEffect.Projection = Matrix.CreateOrthographicOffCenter
  (0, graphics.GraphicsDevice.Viewport.Width,
  graphics.GraphicsDevice.Viewport.Height, 0,
  0, 1);
...
}


texts: Setting a displacement or offset between Snake segements

texts:
I have a problem in maths or I do not know. I have drawn few circles that simulates the body of a snake, the head of the snake moves and others should follow.  but the is no offset or displacement between the circles, because the current code sets the previous position of the nodes to the current, when I add few numbers to both x, y axis, the body segments get distorted. How do I set the offsets between the segments?

for ( int i = 0 ; i < nodes.size(); i++ )
{
    if( i == 0 )
    {
        // Do calculations for new position

        //Set position and previous position
        nodes[i].m_PrevPos.x = nodes[i].m_Pos.x;
        nodes[i].m_PrevPos.y = nodes[i].m_Pos.y;

    }
    else
    {
        nodes[i].m_PrevPos.x = nodes[i-1].m_Pos.x;
        nodes[i].m_PrevPos.y = nodes[i-1].m_Pos.y;
        nodes[i].m_Pos.x = nodes[i-1].m_PrevPos.x;
        nodes[i].m_Pos.y = nodes[i-1].m_PrevPos.y;
    }
}

I would like also to check the head's node velocity for example:

 if ( nodes[0].m_Pos.x < 5 )
    {

        nodes[0].m_Vel.y = -2;
        nodes[0].m_Vel.x = 0;

        if(nodes[0].counter--<1)
        {
            nodes[0].m_Vel.y = 0;
            nodes[0].m_Vel.x = -2;
            nodes[0].counter = 5;
        }

    }


texts: How to make model's arms + weapon follow cursor?

texts:
0
Just like the title says. I currently have my controlling movement working just how I want it to. Now in order to proceed with shooting I first should focus on how the model should look like to determine how my script should act when firing. Currently I am using Unity's Constructor model, but now I need to create my own model just to get the arm movements to follow how I want it to. I have an idea how to make the arms follow the cursor, by adjusting the X and Y axis rotation to follow the position of the cursor, taking on screen coordinates then using Atan to find the right angle. First I have no idea how to make a model, so I guess I need to figure that out first, but how can I make it move like the constructor model from Unity. I have heard of rigging, but still not sure what that is. I have played with C4D when in high school which I noticed while modeling it help provide a human like effect when controlling joints. I am planning on using Blender so if anyone had 3D modeling humanoids video with rigging or skeletal joint or something. Not an artist at all, but I need a model I suppose.

This is a 2.5D platform game, 3D environment with 2D physics.


texts:
How can I subdivide a triangle more than once. I can not use recursion as directx 11 hlsl will not allow it. Are there any links to a HLSL code. This has to be done in the geometry shader as my book says.

my code that will subdivide once is:

  void Subdivide(VertexOut inVerts[3], out VertexOut outVerts[6])
{
    //          1
    //          *
    //         / \
    //        /   \
    //     m0*-----*m1
    //      / \   / \
    //     /   \ /   \
    //    *-----*-----*
    //   0     m2     2

    VertexOut m[3];

inVerts[0].PosL = normalize(inVerts[0].PosL);
inVerts[1].PosL = normalize(inVerts[1].PosL);
inVerts[2].PosL = normalize(inVerts[2].PosL);
// compute edge midpoints
m[0].PosL = 0.5f * (inVerts[0].PosL + inVerts[1].PosL);
m[1].PosL = 0.5f * (inVerts[1].PosL + inVerts[2].PosL);
m[2].PosL = 0.5f * (inVerts[2].PosL + inVerts[0].PosL);
m[0].PosL = normalize(m[0].PosL);
m[1].PosL = normalize(m[1].PosL);
m[2].PosL = normalize(m[2].PosL);

    // derive normals
    m[0].NormalL = m[0].PosL;
    m[1].NormalL = m[1].PosL;
    m[2].NormalL = m[2].PosL;

    // interpolate texture coordinates
    m[0].Tex = 0.5f * (inVerts[0].Tex + inVerts[1].Tex);
    m[1].Tex = 0.5f * (inVerts[1].Tex + inVerts[2].Tex);
    m[2].Tex = 0.5f * (inVerts[2].Tex + inVerts[0].Tex);

    outVerts[0] = inVerts[0];
    outVerts[1] = m[0];
    outVerts[2] = m[2];
    outVerts[3] = m[1];
    outVerts[4] = inVerts[2];
    outVerts[5] = inVerts[1];
}

void OutputSubdivision(VertexOut v[6], inout TriangleStream<GeoOut> stream)
{
    GeoOut gout[6];

    [unroll]
    for(int i = 0; i < 6; ++i)
    {
        // Transform to World Space
        gout[i].PosW = mul(float4(v[i].PosL, 1.0f), gWorld).xyz;
        gout[i].NormalW = mul(v[i].NormalL, (float3x3)gWorldInvTranspose);

        // Transform to homogeneous clip space
        gout[i].PosH = mul(float4(v[i].PosL, 1.0f), gWorldViewProj);

        gout[i].Tex = v[i].Tex;
    }

    //          1
    //          *
    //         / \
    //        /   \
    //     m0*-----*m1
    //      / \   / \
    //     /   \ /   \
    //    *-----*-----*
    //   0     m2     2

    // We can draw the subdivision in two strips:
    // strip 1: bottom three triangles
    // strip 2: top triangle

    [unroll]
    for(int j = 0; j < 5; ++j)
    {
        stream.Append(gout[j]);
    }
    stream.RestartStrip();

    stream.Append(gout[1]);
    stream.Append(gout[5]);
    stream.Append(gout[3]);

    }

[maxvertexcount(8)]
void GS(triangle VertexOut gin[3], inout TriangleStream<GeoOut> stream)
{
    VertexOut v[6];

    Subdivide(gin, v);

    OutputSubdivision(v, stream);
}

How can I subdivide twice or even three or four times.
thx


texts: How do I convert distance covered from meters to kilometers, in Unity?

texts:
I am developing a game in Unity where I have to find a distance in kilometers, to find a passenger's fare based on  the covered distance.

This is what I have tried:

private Vector3 previousPosition;
public float cumulatedDistance;

void Awake()
{
    // initialize to the current position
    previousPosition = transform.position;
}

// Update is called once per frame
void Update () {
    cumulatedDistance += (transform.position - previousPosition).magnitude;
    previousPosition = transform.position;
}

How can I determine the distance covered, and convert it to kilometers?


texts: Should I use retained mode or immediate mode

texts:
I'm trying to make a opengl wrapper for winforms(.net). Basically you code in gdi+ syntax but it gets rendered for opengl(using glcontrol of opentk).

Which mode should I use for rendering ui? It has to be fast enough to support lagless animations and image-drawing. Direct mode (glBegin, glEnd) is easy but I've read there are performance issues. On the other hand, retained mode will be relatively much complex to implement.

My preference is first make for immediate mode then move to retained as I progress. Are there any issues with immediate mode(like missing functionality


texts:
I am studying how to make a 2D game with JavaScript by reading open source JavaScript games and I came across this gibberish...

aSpriteData = [
    "}\"¹-º\"À+º\"À+º\"À+º\"¿¤À ~C_ +º\"À+º\"À+º\"À*P7²OK%¾+½u_\"À<¡a¡a¡bM@±@ª",    //  0 ground
    "a ' ![± 7°³b£[mt<Nµ7z]~¨OR»[f_7l},tl},+}%XN²Sb[bl£[±%Y_¹ !@ $",        //  1 qbox
    "!A % @,[] ±}°@;µn¦&X£ <$ §¤ 8}}@Prc'U#Z'H'@· ¶\"is ¤&08@£(",           //  2 mario
    "  ´!A.@H#q8¸»e-½n®@±oW:&X¢a<&bbX~# }LWP41}k¬#3¨q#1f RQ@@:4@$",         //  3 mario jump
    "   40 q$!hWa-½n¦#_Y}a©,0#aaPw@=cmY<mq©GBagaq&@q#0§0t0¤ $",         //  4 mario run
    "+hP_@",                                    //  5 pipe left
    "¢,6< R¤",                                  //  6 pipe right
    "@ &  ,'+hP?>³®'©}[!»¹.¢_^¥y/pX¸#µ°=a¾½hP?>³®'©}[!»¹.¢_^  Ba a",        //  7 pipe top left
    "@ , !] \"º £] , 8O #7a&+¢ §²!cº 9] P &O ,4    e",              //  8 pipe top right
    " £ #! ,! P!!vawd/XO¤8¼'¤P½»¹²'9¨  \"P²Pa²(!¢5!N*(4´b!Gk(a",            //  9 goomba
    "   Xu X5 =ou!¯¬a[Z¼q.°u#|xv ¸··@=~^H'WOJ!¯¬a=Nu ²J <J   a",          // 10 coin  // yui
    "@ & !MX ~L \"y %P *¢ 5a K  w !L \"y %P *a%¬¢ 4  a",               // 11 ebox // yui
    "¢ ,\"²+aN!@ &7 }\"²+aN!XH # }\"²+aN!X%  8}\"²+aN!X%£@ (",          // 12 bricks
    "} %¿¢!N° I¨²*<P%.8\"h,!Cg r¥ H³a4X¢*<P%.H#I¬ :a!u !q",         // 13 block
    makeSpace(20) + "4a }@ }0 N( w$ }\" N! +aa",                    // 14 bush left
    " r \"²y!L%aN zPN NyN#²L}[/cy¾ N" + makeSpace(18) + "@",            // 15 bush mid
    makeSpace(18) + "++ !R·a!x6 &+6 87L ¢6 P+ 8+ (",                // 16 bush right
    " %©¦ +pq 7> \"³  s" + makeSpace(25) + "@",                 // 17 cloud bottom left
    "a/a_#².Q¥'¥b}8.£¨7!X\"K+5cqs%(" + makeSpace(18) + "0",             // 18 cloud bottom mid
    "bP ¢L P+ 8%a,*a%§@ J" + makeSpace(22) + "(",                   // 19 cloud bottom right
    "",         // 20 mushroom
    "", // koopa 16x24
    "",             // 22 star
    "",                         // 23 flagpole
    "",         // 24 flag
    "",                 // 25 flagpole top
    "  6  ~  }a }@ }0 }( }$ }\" }! } a} @} 0} (} $} \"² $",             // 26 hill slope
    "a } \"m %8 *P!MF 5la\"y %P" + makeSpace(18) + "(",             // 27 hill mid
    makeSpace(30) + "%\" t!DK \"q",                         // 28 hill top
    "",         // 29 castle bricks
    "",                         // 30 castle doorway bottom
    "",                 // 31 castle doorway top
    "",         // 32 castle top
    "",         // 33 castle top 2
    "",             // 34 castle window right
    "",             // 35 castle window left
    "",         // 36 castle flag
    makeSpace(19) + "8@# (9F*RSf.8  A¢$!¢040HD",                    // 37 goomba flat
    "     *(!¬#q³¡[_´Yp~¡=<¥g=&'PaS²¿ Sbq*<I#*£Ld%Ryd%¼½e8H8bf#0a",         // 38 mario dead
    "   =  ³ #b 'N¶ Z½Z Z½Z Z½Z Z½Z Z½Z Z½Z =[q ²@ ³  ¶   0",           // 39 coin step 1
    "   ?@ /q /e '¤ #³ !ºa }@ N0 ?( /e '¤ #³  ¿  _a  \"",               // 40 coin step 2
    "   /  >  ]  º !² #¢ %a +  >  ]  º !² #¢ 'a  \"",               // 41 coin step 3
    "   7¢ +² *] %> \"p !Ga t¢ I² 4º *] %> \"p  ¡  Oa  \""              // 42 coin step 4
],

What does it do? If you want to look at the source file, here it is. Beware, there is more gibberish inside. I can't seem to make sense of any of it.


texts: What continuous integration technology is used for games?

texts:
Which continuous integration technology & software would you recommend for use with games?

Also are there any build technology libraries or specific languages you would recommend to use when a custom part of the game asset pipeline needs to be coded in-house?

Are there any good resources for demonstrating the business case for using continuous and automated build systems for games?


texts: In XNA, how do I access a model's dimensions with code?

texts:
I'm trying to rotate a model around some axes, but this rotates it around the world origin. I understand that I need to translate the object relative to its own size before rotating it, but I don't know by how much.

I've done it by trial and error until now. How can I automatically read a model's width, height and position?


texts:
Hey everyone, could someone help me out on this question?
When I am trying to texture objects in maya (for example a barrel) I want to texture it with a brush. When I try to use the 3D painting tool it al gets black even when I have a image file selected. Also the resolution is very very low of the models and textures in maya, though the texture image is very high quality. Can someone please help me? Thanks so much for helping.


texts: Circular trajectory for sprite in LibGdx

texts:
I want four sprites to orbit a single origin point. But if I use like this

    sprite_p1_avatar = new Sprite(dummyText);
    sprite_p1_avatar.setPosition(200, 200);
    sprite_p1_avatar.setOrigin(100, 100);

    sprite_p2_avatar = new Sprite(dummyText);
    sprite_p2_avatar.setPosition(300, 300);
    sprite_p2_avatar.setOrigin(100, 100);

    sprite_p3_avatar = new Sprite(dummyText);
    sprite_p3_avatar.setPosition(400, 400);
    sprite_p3_avatar.setOrigin(100, 100);

    sprite_p4_avatar = new Sprite(dummyText);
    sprite_p4_avatar.setPosition(500, 500);
    sprite_p4_avatar.setOrigin(100, 100);

    sprite_p1_avatar.rotate(40 * delta);

    sprite_p1_avatar.draw(batch);

    sprite_p2_avatar.rotate(40 * delta);
    sprite_p2_avatar.draw(batch);

    sprite_p3_avatar.rotate(40 * delta);
    sprite_p3_avatar.draw(batch);

    sprite_p4_avatar.rotate(40 * delta);
    sprite_p4_avatar.draw(batch);

the sprite get inverted while revolving, as these sprites are profile pictures of users I want them to stay straight while orbiting at every point. Is there any way to move the sprites along a circular path without rotating.


texts:
I'd like to explain this problem with a screenshot from a released game, DROD: Gunthro's Epic Blunder, by Caravel Games.

The game is turn-based and tile-based.

I'm trying to create something very similar (a clone of the game), and I've got most of the fundamentals done, but I'm having trouble implementing pathfinding.

Look at the screenshot. The guys in yellow are friendly, and want to kill the roaches.
Every turn, every guy in yellow pathfinds to the closest roach, and every roach pathfinds to the closest guy in yellow.

By closest I mean the target with the shortest path, not a simple distance calculation.

All of this without any kind of slowdown when loading the level or when passing turns.
And all of the entities change position every turn. Also (not shown in screenshot), there can be doors that open and close and change the level's layout.

Impressive.

I've tried implementing pathfinding in my clone.

First attempt was making every roach find a path to a yellow guy every turn, using a breadth-first search algorithm. Obviously incredibly slow with more than a single roach, and would get exponentially slower with more than a single yellow guy.

Second attempt was mas making every yellow guy generate a pathmap (still breadth-first search) every time he moved. Worked perfectly with multiple roaches and a single yellow guy, but adding more yellow guys made the game slow and unplayable.

Last attempt was implementing JPS (jump point search). Every entity would individually calculate a path to its target. Fast, but with a limited number of entities. Having less than half the entities in the screenshot would make the game slow. And also, I had to get the "closest" enemy by calculating distance, not shortest path.

I've asked on the DROD forums how they did it, and a user replied that it was breadth-first search. The game is open source, and I took a look at the source code, but it's C++ (I'm using C#) and I found it confusing.

I don't know how to do it. Every approach I tried isn't good enough. And I believe that DROD generates global pathmaps, somehow, but I can't understand how every entity find the best individual path to other entities that move every turn.

What's the trick?

This is a reply I just got on the DROD forums:

  Without having looked at the code I'd wager it's two (or so) pathmaps
  for the whole room:

  One to the nearest enemy, and one to the nearest friendly for every
  tile.

  There's no need to make a separate pathmap for every entity when the
  overall goal is "move towards nearest enemy/friendly"... just mark
  every tile with the number of moves it takes to the nearest target and
  have the entity chose the move that takes it to the tile with the
  lowest number.

To be honest, I don't understand it that well.


texts: Correctly bitmasking path tiles based on existing paths

texts:
Currently, I have a bitmasking implementation that sometimes incorrectly bitmasks the tiles. Conventionally, it is done correctly, and the math/etc is sound, but it achieves results such as the following:

This is similar to what you might expect, and looks fine when doing simple x-shaped crossings. However, I would like for the images to remain unchanged in some of these cases. For instance, the parallel paths in the third image would remain parallel paths instead of being bitmasked into many crossings. In the first and second images, only the parts of the path highlighted in the following images would be bitmasked (Different parts of path labelled for clarity.)

If I purely update only the tiles that make up the newest path, I again get good results in simple x-shaped crossings, however I get results such as those demonstrated in the following image:

What could I do to achieve results where this would not occur? I have though about adding some sort of flag to the tile to indicate that it is a crossing, but how could I detect that?


texts: How does Unity pick which sprite atlas to load?

texts:
I plan to use sprite atlases for my 2D game. All my animation is sprite animation so I'm going to use sprite atlases for my characters' sprites.
My question is, if I put the same sprite in two different atlases, how does Unity decide which atlas to load?
EX:
I have a sprite atlas per level that contains the background for that level.  Sometimes, there's space left over in the atlas.  So, if I want to put a sprite, which already exists in another atlas, in the empty space for that level's atlas, how does Unity know not to load both atlases?