texts: How to add all MonoBehaviours of Scene into the List?

texts:
I've read an article 10000 UPDATE() CALLS.
Author uses UpdateManager. It has Update method which calls Update method in all of other MonoBehaviours of objects. It works faster than calling Update method from each MonoBehaviour separately.

This Manager looks like:

private ManagedUpdateBehavior[] list;

private void Start() {
    list = GetComponents<ManagedUpdateBehavior>();
}

private void Update() {
    var count = list.Length;
    for (var i = 0; i < count; i++) {
        // UpdateMe
        list[i].UpdateMe();
    }
}

And every objects now contains component with the code:

public class ManagedUpdateBehavior : MonoBehaviour {
    // some variables

    public void UpdateMe() {
        // some logic
    }
}

It's okay if 5-6-7-8- objects will be have that component.

But what if I have 100 objects? 1000? 10000?

How to find and add all ManagedUpdateBehaviors from all objects of scene? Should I use some recursive method on On Start? Cause every object may contain other objects with the script, they may contain the other objects etc...unlimited nesting

Also some objects can be instantiating dynamically...How to add their mono to manager? What is the right way?


texts:
I was wondering, what kind of database does Minecraft use? Is it a relational database, maybe something common like MySQL? Do we even know what he's using?

And maybe even a better question, SHOULD he be doing it that way? What type of database should be used?


texts: Matrix multiplication order for multiple model transformations

texts:
I have a problem in terms of what frame of reference, I should construct, scaling (S), rotation (R) and translation (T) for a model matrix (in that order). Let us assume the use of glm (or glsl), i.e. to mean column major representation.

I believe, it should be a matrix multiplication of:

M = T * R * S // S * R * T is what we want to apply, but due to being column major, the order gets reversed, due to (AB)^T =B^T*A^T

Now, if I have a previous transformation already applied (say M_prev), and I want to apply a transformation M on top of that, then is the correct form:

M_new = M_prev * M // M_new and M_prev are both column major. I'm post multiplying due to being column major, but this is incorrect, I guess?

I believe this is incorrect (at least in some experiments I carried out, please correct me if I'm wrong), and it should be the reverse. What is the flaw in my calculation of M_new?


texts:
I have the following code for Food:

exports.Food = function(x, y) {
this.MOVE_X_FROM_POSITION = 10;
this.ACCELERATION = 0.05
this.image;
this.firstX = x;
this.firstY = y;
this.x = x;
this.y = y;
this.width = 10;
this.height = 10;
this.velocity = {
  x: 0,
  y: 0
}
this.acceleration = {
  x: this.ACCELERATION,
  y: 0
};
this.render = function(ctx) {
  if (typeof this.image != undefined) ctx.drawImage(this.image, this.x - this.width / 2, this.y - this.height / 2);
  return this;
}
this.update = function() {
  this.velocity.x += this.acceleration.x;
  this.velocity.y += this.acceleration.y;
  this.x += this.velocity.x;
  this.y += this.velocity.y;
  if (this.x >= this.firstX + this.MOVE_X_FROM_POSITION) {
    this.acceleration.x = -this.ACCELERATION;
  } else if (this.x <= this.firstX - this.MOVE_X_FROM_POSITION) {
    this.acceleration.x = +this.ACCELERATION;
  }
}

... and so on

I want the food to move 10 steps from it's first location one side and 10 steps the other side. The problem is that if the script is running longer it becomes to move far more than 10 steps from it's original position. PS: update function is called in the loop every 30 times per second

Where could be the problem? Thank You in advance

EDIT

Here is actually a demonstration of my problem:
https://jsfiddle.net/02jbmxnw/1/


texts: Visual Studio IntelliSense & syntax highlighting not recognizing Unity types

texts:
Frequently when I open a Unity C# script in Visual Studio, the built-in Unity Engine types aren't recognized, so I don't get syntax highlighting or code completion hints for things like MonoBehaviour.

Sometimes if I delete the script and create a new one it works, but lately nothing I do solves the problem.  Is there something I can do?


texts: Disabling, overriding or hooking a VS warning to Unity's Vector's ToString()?

texts:
I've just spent 2 hours debugging a misbehaviour because ToString() truncates to 1 digit by default.

I want to disable the parameterless version so I won't use it by accident and I will always have to define how much truncation I want.

Or if this isn't possible I want to redefine it, so it will truncate to 3 digits for example.

Or somehow hook a custom warning to it, so Visual Studio will tell me that I'm using it?

Is this possible?


texts:
I am developing following type of game Roulette Royale.

I am basically ready with wheel and number table. When user move wheel table then ball also move on that table and stop at particular number and reply to number table with that number.

Right now I only used RotationModifier and there is no position change at present only ball rotate and stop at randomly selected number. This thing work well.

But I want ball start its movement from out side the wheel and slowly move inside in to the wheel. It perform rotation as well as smoothly move towards the center of the wheel. This functionality I don't able to conceptualise how to create?

I think there is no need to put any code snippet here because I need only concept how to perform this task. Thanks in advance efforts you take for me.


texts: Which unit test framework for c++ based games?

texts:
Which combination of testing tools do you feel is best?
Given the framework / library of your choice you might consider:

suitability for TDD
ease of use / productivity
dealing with mock objects
setup with continuous integration
error reporting

Note: While this is potentially a generic question like the one on SO I would argue that game development is usually bound to a specific work flow which influences the choice for testing. For a higher-level perspective, see question Automated testing of games.


texts: Using uniform grids for collision detection - Efficient way to keep track of what a cell contains

texts:
I was looking for an efficient way to implement collision detection in a 2D game. A way that won't result in an O(n^2) level of complexity.

A lot of people recommend to use Uniform Grids for this purpose. From what I gather, this means (please confirm if this is accurate):

Dividing the screen to a grid of equally sized square areas. Each area is represented by a 'cell' inside a 2d array.
Each cell is a data structure such as a List, or
an object containing such a data structure.
The cell contains references to all of the game objects that overlap with the area the cell represents (objects 'inside' the cell).

Each update step, every object in a cell is checked for collision with every other object in the same cell.

I understand all of this. But one thing is still not clear to me:

Every update step, I need to check if any game object left the cell it was inside of and moved to another cell. I always need to know which object is in what cell.

The only idea I had of how to do this, is each update step: 1- clear all of the cells. 2- Reassign all the objects to the cells.

Meaning: If I have 40 cells and 70 game objects on screen, every object of 70 is going to have to go through 40 if statements:

if (object overlaps area 1) put it in cell 1;

if (object overlaps area 2) put it in cell 2;

... // until 40

My question:
Using 40 if statements (or a big switch) for every object isn't reasonable. Please suggest a more efficient way to keep track of what objects are in what cells.

Thank you for your help, will be appreciated.


texts: Creating non-rectangular hotspots and detecting clicks

texts:
Say for a game with irregular hotspots (say Risk, or a strategy game like Paradox's Hearts of Iron or Crusader Kings), how do you

Define a non-rectangular hotspot of irregular shape (much like a territory on a map?), in code?
What tool can you use to trace out the hotspot and import into your game?
What is the algorithm for detecting if someone has clicked within such a hotspot?


texts:
I've been searching for a way to make an svg box move to all directions using js. I have seen many tutorials on how to do it grid like, but I want it so have a square that can turn, move forward, backwards and sideways. In terms of movement, I want to be like https://www.chromeexperiments.com/experiment/arena5 except there will be a square instead of a triangle and there will be no enemies.

My problem is that I don't know how to make an svg square move fluidly and without a grid, but the movement will only use keyboard, no mouse. Please be patient I'm new to js gaming.

Here is the most reason version of what I've trying, this is svg, right now I'm trying to make it in canvas.http://codepen.io/julian-a-avar/pen/PqZvxp


texts:
I would like to know how can I go about with an approach, that lets the enemies blink after they are hit with a shot/particle?

Is it better to pre-render colored enemies into an array for a better performance or is it just okay coloring them during gameplay?

For example, you can use the colorMatrixFilter- or colorTransform- methods for accomplishing this. Pre-rendering it (mentioned before) and storing the colored enemies inside of an array is an option also.

I ask because I'm not sure how those mentioned methods influence gameplay, especially for action games.

Which method is usually faster / the accepted norm? Are there any approaches I should avoid that will impact the gameplay?


texts: How to model classes to be serialisation friendly in c#?

texts:
It is going to be just a fraction of the code but for the sake of the example let's say I have a class Stat

class Stat
{
    private string _name
    public Name { get { return _name; } }

    public Stat(string name)
    {
        _name = name;
    }
}

When I serialise object of type Stat with for example TinyJSON, it produces:

{ "Name": "some random name" }

So I figured I will create StatData with public property and not a getter so then I can use it for serialisation.

class StatData
{
    public string name
}

As far as I can tell I have now 2 choices:

Write converter method and, upon serialisation request, convert Stat to StatData and serialise StatData.
Pros: single responsibility principle preserved
Cons: more code and nested dependencies
Go with private StatData _data in Stat class and using getters as previously and adding, eg.: ToJSON() method on Stat
Pros: public interface
Cons: generics to handle inheritance eg.: StatComposite and serialiser dependency

Is/are there any other method(s) or potentially design pattern to deal with the problem?


texts: What is the best toolchain for ActionScript3 social networks game development?

texts:
I'm new to flash and web development too. But I have some background in c#/c++/Qt/python. So, I want to know, what is the best toolchain for quickest dive into.

My task is to write a game for facebook.com/vkontakte.ru. I already have the design doc, great artist and game-designer, so, the coding is the only stumbling block we met. There are no significant obstacles at server-side, but, since we have not much time, I decided to ask some help on suitable toolchain definition.

I think, that web-services (maybe WCF) are perfect for the backend, so, some of them should transfer JSON-ed data from/to client, incapsulate game-logic, and... here is the place I stuck. What next, what should I learn, what tools/toolsets will provide learing/productivity curve that meat least action principle.

Maybe I'm on the wrong way and missing some basic and obvious (for web-devs) things... I do not know, so, any advices will be highly appreciated.

Yes, this is the copy of my question on SO, but it seems, that here is the really proper place to post it.


texts: Can I create a SDL_Surface as I do with Allegro?

texts:
Using allegro I can create a Bitmap to draw just doing:

BITMAP* bmp = NULL;
bmp = create_bitmap(width,height); // I don't remember exactly the parameters

I'm using SDL now, and i want create an SDL_Surface to draw the game level (that is static). I create an SDL_Surface, draw the tiles on it, then just blit this surface to the screen instead of drawing the tiles directly on screen (I believe this will require more processing);

Is there a way to create a blank SDL_Surface as I did with Allegro to draw before I blit it?


texts:
recently I was playing The Stanley Parable, and noticed that there are several impossible spaces in the game - in this example, a pair of pillars in the middle of the room, which from each side appear to open onto a long corridor between them, which would have to cut the room in two if it were present in the same space.

I hadn't seen this in a game since the Marathon Trilogy. The marathon games used a 2.5d engine that due to a quirk in its programming allowed for non-Euclidean geometry.  I was not aware it was even possible with fully 3D engines until I played The Stanley Parable. How does it work? how would I do that in Unity 5?


texts: Toggle Button click doesn't count when the Mouse Up happens outside of the button area

texts:
I have a problem with my toggle buttons. When a user performs the Mouse Up of the toggle button outside the button area, the click is not counted.

Mouse Down and Mouse Up on the button area works. Mouse Down on the button and Mouse Up outside, does not work..

Just to avoid confusion, the Mouse Down is when you click, the Mouse Up is when you lift the finger from the mouse button.

Do you have any idea how to solve this?

I'm using Unity.
Thanks for your help!


texts: Where can I get correct pitch parameter for SDL_RenderReadPixels function in SDL2?

texts:
I have a texture created with SDL_TEXTUREACCESS_TARGET access and I want to get all its pixels with SDL_RenderReadPixels() function. One of the function parameters is pitch and I don't really know where can I can get it.

Texture is created with dimensions of a previously created surface, but function call with surface->pitch as pitch parameter generates EXC_BAD_ACCESS.

Texture and surface dimensions are 800x600, and surface->pitch returns 3200, which is strange for me, because I thought that pitch is the width of the texture in memory and expected surface->pitch to be something like 1024.


texts: How can I make my Color Mixing game more difficult?

texts:
I am making my first game and it is coming out too simple. Are there standard "techniques" to making it more difficult?

The game is pretty simple. Picture the game 2048. When you slide in a direction the blocks all slide that direction and collide or merge. But instead of merging numbers (like 2+2=4 in 2048) it merges colors, so a yellow block hitting a blue block makes a green (and red + yellow = orange, etc.) Then if you merge a primary color (blue) and a newly created secondary color (green) it makes a tertiary color (in this case "blue-green").

At that point you can tap on the tertiary color (what I have deemed a "tertiary-bomb") and it will destroy all of it's primary colors, so "blue-green" will destroy all "blue" blocks. You lose if you can no longer move, same as 2048, but it seems to be far too easy not to get stuck, by creating bombs.

How would an experienced game designer make this game less trivial?


texts: How to predict future position of an object(bullet sync)?

texts:
There is a multiplayer game and server sends to all clients a message when a shot happens, containing bullet position, bullet velocity and timestamp. By having timestamp, we can calculate the lag, let's say it's 100ms.

My game uses Box2D. How can I predict the real and current bullet position by having such data? I guess velocity might also change a little bit too.


texts: 3D game special effects, fire, lightning, water, and ice

texts: I'm working on a 3d game using OpenGL and would like to take it in a fantasy direction.  Specifically I'm thinking of having magic with effects for fire, water, ice, and lightning.  My problem is I have no idea how to create these effects.  Are there any resources for me on how to learn something like this?


texts: The mosts common topics that developer technical tests ask

texts:
Possible Duplicate:
  What are typical job interview questions related to game development?

I have a technical test on the horizon, and I'm brushing up on my 3D maths and algorithmic stuff - there are websites that have lists and lists of technical questions such as 'How would you check to see if a string was a palindrome?' and also perhaps, 'How would you check to see if there was a palindrome anywhere in this string?'

Also things like calculating complex recursion on paper and Big O notation. What are the other key things to practise for these kinds of test?


texts:
I am making a game using Cocos2d-x and want to support multiple mobile phone resolutions and sizes.

Right now I have made my game sprite sheets set on a resolution of iPad Retina's resolution of 2048X1536 and then will use Tiled Map editor to design my game levels.

My question is on what basis do I scale my sprite sheets for different resolutions suppose iPhone etc so that my Tiled Map's design does not get effected when used in the game ?


texts: How to run DOTween tweens in succession?

texts:
I have a function in my Unity game which marks a given cell GameObject as a valid cell for next move by changing the texture on it. I wanted to spice things up a bit by adding some tweens to the changing cells so I decided to use a simple tween in DOTween - I wanted to rotate the cell 360 degrees in-place while changing the texture when it's facing away from the player (so that the texture doesn't suddenly pop to a different one when it's visible). So I did something like that:

public void markAsLegal()
{
    centerPivot.DOLocalRotate(new Vector3(180, 0, 0), .5f, RotateMode.WorldAxisAdd);
    this.GetComponent<Renderer>().material.mainTexture = Resources.Load("textures/legal_hex") as Texture2D;
    centerPivot.DOLocalRotate(new Vector3(180, 0, 0), .5f, RotateMode.WorldAxisAdd);
    isLegal = true;
}

This, however, doesn't seem to wait for one rotate before starting the next one and so the cells end up in some weird middle ground, slanted. How can I make DOTween/Unity know that I want these commands to be executed in progression, ie. 180 degree rotation ends -> change texture -> finish the remaining 180 degrees?


texts: Unity: Create a custom editor for Vector2

texts:
I'm starting to dig into Unity's editor customization. What I'm looking for is a way to create custom line (or a point at least) which I could move around in SceneView and set a Vector2 value that way.

I might create a child GameObject and then calculate the relative distance, but I'd like to know, if there is any way using the Editor instead of adding other useless GameObjects.

Thanks in advance.


texts:
I'm making a first person game and when I jump and my character gets close to the top of the wall, the vertical movement stops, jitters, or suddenly snaps to the top of the wall.
Video
Here is my character controller code, based on this tutorial:
using UnityEngine;

[RequireComponent(typeof(CharacterController))]
public class PlayerController : MonoBehaviour
{
    private InputManager inputManager;
    private CharacterController controller;
    private Vector3 playerVelocity;
    private bool groundedPlayer;
    [SerializeField] private float playerSpeed = 2.0f;
    [SerializeField] private float jumpHeight = 1.0f;
    [SerializeField] private float gravityValue = -9.81f;

    private Transform cameraTransform;

    private void Start()
    {
        controller = GetComponent<CharacterController>();
        inputManager = InputManager.Instance;
        cameraTransform = Camera.main.transform;
    }

    void Update()
    {
        groundedPlayer = controller.isGrounded;
        if (groundedPlayer && playerVelocity.y < 0)
        {
            playerVelocity.y = 0f;
        }

        Vector2 movement = inputManager.GetPlayerMovement();
        Vector3 move = new Vector3(movement.x, 0f, movement.y);
        move = cameraTransform.forward * move.z + cameraTransform.right * move.x;
        move.y = 0f;
        controller.Move(move * Time.deltaTime * playerSpeed);

        // Changes the height position of the player..
        if (inputManager.PlayerJumpsThisFrame() && groundedPlayer)
        {
            playerVelocity.y += Mathf.Sqrt(jumpHeight * -3.0f * gravityValue);
        }

        playerVelocity.y += gravityValue * Time.deltaTime;
        controller.Move(playerVelocity * Time.deltaTime);
    }
}

I also tried using other solutions by changing the physics material of the level and player, neither worked.


texts:
I would like to know how to blend colors in a specific way.

Let's imagine that I have a color (A) and an other color (B).

I would like to blend them in such a way that if I choose white for the (B) then the output color is (A) but if have any other color for (B) it outputs a blending of (A) and (B).

I've tried the addition, but it doesn't give the expected result.
I've tried the multiplicative blending it's quite good for the (B) white value but it fail for a blue (B) and red (A) colors.

Any idea how to do that ?
Thanks a lot.


texts: Implementing Separating Axis Theorem to Detect and Handle Sliding Collisions

texts:
I am having a bit of difficulty detecting collisions properly with separating axis theorem. My code seems to be giving a lot of false alarms. Also, I've looked into implementing sliding collisions with the data from the theorem.

This is the resource I used for this algorithm:
https://stackoverflow.com/questions/115426/algorithm-to-detect-intersection-of-two-rectangles?rq=1

This is my code for detecting collisions:

// Note .boundingBox is a set of four vertices for each rectangle. It is:
// [Bottom Right, Bottom  Left, Top Left, Top Right]

// Also .edge is the set of four edges for each rectangle. It goes:
// [Bottom, Left, Top, Right]

// Only take two edges of each rectangle since two edges share each axis
var edges = this.edges.slice( 0, 2 ).concat( polygon.edges.slice( 0, 2 ) );

// Loop through the axes of both rectangles
for ( var i = 0; i < edges.length; i++ )
{
    var oppositeSides = true,

        // Convert the edge to an axis by finding its normal,
        // then convert the axis to a unit vector
        magnitude = i % 2 === 0 ? 50 : 25,
        normal = {
            x: -edges[ i ].y / magnitude,
            y: edges[ i ].x / magnitude
        },

        // Take one point on the current shape and find its projection onto the axis
        currentPoint = i < 2 ? this.boundingBox[ i ] : polygon.boundingBox[ i - 2 ],
        nextPoint = i < 2 ? this.boundingBox[ i + 2 ] : polygon.boundingBox[ i ],
        shape1Vector = {
            x: nextPoint.x - currentPoint.x,
            y: nextPoint.y - currentPoint.y
        },
        shape1DotProduct = shape1Vector.x * normal.x + shape1Vector.y * normal.y,
        shape1DotProductSign = shape1DotProduct >= 0;

    // Take all the points on the other shape and project their distance
    // onto the axis. If their dot product sign is opposite to the point
    // on the same shape, then there must be no collision
    for ( var j = 0; j < 4; j++ )
    {
        nextPoint = i < 2 ? polygon.boundingBox[ j ] : this.boundingBox[ j ];

        var shape2Vector = {
                x: nextPoint.x - currentPoint.x,
                y: nextPoint.y - currentPoint.y,
            },
            shape2DotProduct = shape2Vector.x * normal.x + shape2Vector.y * normal.y,
            shape2DotProductSign = shape2DotProduct >= 0;

        if ( shape2DotProductSign === shape1DotProductSign )
            oppositeSides = false;
    }

    if ( oppositeSides )
        return true;
}

return false;

Now for handling the sliding collisions, I attempted to project the rectangle's velocity vector onto the axis where there is the least overlap, then multiply that scalar dot product by the unit vector of the axis, but that seems to result in strange behaviour where the velocity goes to insane velocities.


texts:
I have no any experience in game development, I'm doing some research on machine learning tasks and for my project I need to know how to get depth buffer. I tried to google but haven't found relevant materials except the software Reshade where it says that they forbid accessing PUBG depth buffer because of cheating.

So if anyone can point me in the direction of how to access depth buffer will be much appreciated!


texts: Unwanted begincontact callbacks at high velocity

texts:
I'm having some issues with jump detection due to begincontact. I have a player entity made of 2 bodies, and it looks something like this:

Note how the circle below (a body connected via a revolute joint) is not quite as wide as the rectangle. This means that when the player is up against a wall, there is no contact between the circle and the wall.

However, if the player collides with a wall at high velocity, begincontact registers a contact between the circle and the wall. Is there any way around this?


texts: Skill vs. Luck, the ratio and its measurement

texts:
Gamer buddies, is there a term to describe the level of variance in a game, in comparison to luck. The card game war would have 0 skill and 1.0 luck because the player cannot affect the game. I can't think of something that has 1.0 skill. At first I thought Spelling Bee, but the words chosen for each contestant is randomly chosen suggesting some luck involved... What ratios do different games have, and how can those ratios be accurately measured? What metrics could be used to accurately measure such a ratio? I'd also like to hear of any 1.0 skill games if anyone can think of one.

To reiterate the question clearly:  does there exist such a measurement and if so what is it? Furthermore is there a term for the target of this measurement, so we can have a discussion using a noun.

EDIT: the term luck is used to describe the level of effect that chance, i.e. random events, have in affecting who the winner is. I appreciate everyone's responses.


texts: collision detection and normals from rigidbody

texts:
Until now I've been developing my player character using a Character Controller, but have since decided to switch to rigidbody due to the controller's limitations. In order for my movement code to run as expected I need to know when the player is colliding with anything, and the normal of the surface it's colliding with. This is easy with a Character Controller, but is there a simple way to do it with a rigidbody?

Here is a stripped down version of the script I'm using for collisions.

 // Used in other scripts (Necessary)
    public GameObject ground = null;
    public Vector3 groundNormal;
    public bool onGround;

    // Used internally
    public bool isColliding;
    public float slopeLimit;

    // Character Controller
    public CharacterController controller;

    void Start()
    {
        controller = GetComponent<CharacterController>();
    }

    void Update()
    {
        // Check if the player is colliding with anything (Character Controller)
        if (controller.collisionFlags == CollisionFlags.None)
        {
            isColliding = false;
        }
        else
        {
            isColliding = true;
        }

        // Check if the player is standing on the ground
        if (isColliding && groundNormal != Vector3.zero)
        {
            onGround = true;
        }
        else
        {
            onGround = false;
        }
    }

    void OnControllerColliderHit(ControllerColliderHit hit)
    {
        // Check for floor
        if (Vector3.Angle(transform.up, hit.normal) <= slopeLimit)
        {
            // Store floor object data
            ground = hit.gameObject;
            // Store ground surface normal
            groundNormal = Vector3.Normalize(hit.normal);
        }
        else
        {
            // reset variables
            ground = null;
            groundNormal = Vector3.zero;
        }
    }

slopeLimit is a static value. Additionally, getting the ground object isn't actually necessary atm, but I plan on using it later.

Edit:
Currently I'm using controller.collisionFlags to detect when the player is colliding with something and haven't been able to find a similar alternative. Setting the isColliding bool to true using Rigidbody.OnCollisionStay would be simple, but setting it to false without use of another void function seems difficult. is that possible at all?


texts: What happens to a D3D11 application when Windows hibernates?

texts:
In D3D9 there was the concept of a "device reset". When a device reset occurred textures created with D3DPOOL_DEFAULT had to be recreated, but textures created with D3DPOOL_MANAGED didn't, because, according to MSDN, a duplicate copy is kept in system memory.

In D3D11, the concept of a device reset has much less prominence. But since the video card loses power during hibernation, textures must be stored somewhere else beforehand.

So how does Windows 7 preserve video card resources during hibernation?

Is it like D3DPOOL_MANAGED where a duplicate copy is wastefully kept in system memory,
or does it only copy resources back from video memory immediately before hibernating, then returns them to video memory after resuming?
Or do such resources need to be manually recreated and I'm missing something in the API?

It looks like graphics drivers implement DxgkDdiSubmitCommand to allow data to be copied to and from video memory, but it's unclear whether Windows actually does this when hibernating.


texts: XNA, SpriteBatch: Slow when rendering lots of sprites?

texts:
I've just now tested rendering a lot of sprites using XNA's SpriteBatch class. What I basically do is this:

Somewhere in the code, I have a list which contains all sprites that have to be rendered. I prefilled this list with 2500 Sprites, all of which have the same rotational angle, texture, position etc.

I then draw them like this:

    spriteBatch.Begin();
    foreach (Sprite spr in sprites)
        spriteBatch.Draw(spr.Texture, spr.Position+spr.Center, spr.SourceRect, spr.Color,MathHelper.ToRadians( spr.Rotation ), spr.Center, spr.Scale, SpriteEffects.None, spr.Depth);

    spriteBatch.End();

and I'm getting really poor performance. I only average about 15FPS with my Radeon HD 6850 graphics card and i5 2500k CPU.

This is very surprising to me, since I average about 70 FPS doing exactly the same thing with my own custom OpenGL engine, which uses old OpenGL rendering (meaning one draw call for every single sprite). I actually expected XNAs rendering to be a ton faster, since it draws everything in one draw call.

Am I rendering this the wrong way? Playing around with SpriteSortMode settings has made almost no difference, some of them just make it a tiny bit slower (depth sorting etc.).


texts: What are constraints and how are they pluggable?

texts:
I have been reading this book called "Game Physics Engine Development" and Came across this image in the context of Collision Resolution.

See the contact Generator part. Can someone tell me what are constraints and how there can be different types of them? Thank you.


texts:
In my game I have created popup text for gained points when enemies are killed.
it pops up wherever the enemy was and will say something like
"+32"
float up a bit and fade away at the same time.
This transition lasts for a few seconds if that. and hundreds could appear at a time when AoE attacks destroy a lot of enemies.

That's all well and good. and it works!
but I fear that this could become quite slow on mobile devices. So I did what any good game dev does. I pooled it!

Then it occurred to me.
I'll still be changing the display value of the text elements dynamically and libraries like TextMeshPro already, in surely an optimized way, instantiate actual meshes to render text. So is pooling these text elements really a big optimization?

so here goes my question for experienced and knowledgeable devs. Is it more efficient to pool each character I need and assemble my short strings dynamically as sets of pooled gameobjects for these popups of just a few characters or should I simply pool text elements that will change their text just before appearing? Assume the memory usage difference is minimal. only worried about speed.

This is on top of the game having possibly thousands of projectiles moving at any given time, so I believe it is a valid optimization question, but I ask this more for curiosity than practicality. For now, I already have a working solution. but I believe such an issue could arise in the future. and want to satisfy my curiosity now.


texts: Goal oriented Action Planning with multiple Agents

texts:
I'm a little bit stuck:

I implemented an AI with GOAP (Goal oriented Action Planning, http://alumni.media.mit.edu/~jorkin/gdc2006_orkin_jeff_fear.pdf) for a simulation game. That works fine.

Now I want that the agents can cooperate (e.g. doing actions together). What is in this case the best AI-Design that the GoapActions keep loose couplet?

Should they plan together? (what is in this case the "worldstate"?)Or Should they share their plans? some kind of message-system?

Example
Agent1:
Worldstate Agent 1: isLonely= true
Goal Agent1: isLonely = false

Plan Agent1: AskAgent2ToTalk -> TalkToAgent2

Agent2
Worldstate Agent 2: hasWood = false
Goal hasWood = true

Plan Agent2: GetAxe -> ChopWood -> BringWoodToSupply

How I get this constellation?

Agent1 Plan: TalkToAgent2
Agent2 Plan: TalkToAgent1 -> GetAxe -> ChopWood -> BringWoodToSupply

Or if they are talking and one of the agents is interrupted (e.g. by an attacking enemy) the other agent must know that his TalktoAgent2 Action has ended.


texts:
I'd like to prototype a game with custom, very simple physics. Something similar to older games, anything from Super Mario to Quake 3 Arena.

I'd prefer to avoid realistic physics engine because they usually reduce the control you have over your objects and require you to manipulate such objects in a specific way.

I'd want to be able to update the objects' physical state using my own rules. E.g. I'd like to implement and apply gravity, movements and all the rest using my own logic.

I believe that what I need is a small engine that handles an efficient representation of objects in a space and offers an interface to query it.
I'd also need it to offer decent utilities for very common problems such as collision detection, ray casting, moving overlapping objects away from each other etc.

Do similar engines even have a name?
They're not considered physics engine, are they?

I was planning to work on a 3D prototype, and use JavaScript and Three.js as a language and scene-graph/renderer. However I might be open to 2D environments and/or different technologies.
I'd love it if I could find a set of libraries that are meant to work with each other, so that I don't need to write a lot of glue code.


texts:
I am reading Game Physics Engine Development by Ian Millington currently. In his book, he represent an orientation of rigid body by quaternion. I don't understand the formula where he apply angular velocity to the quaternion. The formula is

$$ q_{new} = q_{0} + \frac{t}{2} * w * q_{0} $$

where w is the angular velocity in quaternion representation.

$$ w = \begin{bmatrix} 0\\ w_{x}\\ w_{y}\\ w_{z} \end{bmatrix} $$

He doesn't explain where the formula come from. Currently I apply this method in my physics engine where I compute the angular rotation then convert it to quaternion and multiply it. It is slower than the above operation because of the sine, cosine and square root operation when converting the rotation to quaternion. Can someone explain to me where did the formula above come from? I understand basic quaternion operation like representing axis angle by quaternion and rotating a vector by quaternion.


texts: What resources can I use to determine if the name of my game violates any copyrights or trademarks?

texts:
I'm a indie/hobbyist game developer.  How do I check that I'm not infringing any copyrights or trademarks when I release my game?

I'm not making megabucks so it's not financially feasible to get professional legal help for each game.

I asked recently if I can reuse the name of an old arcade game (Crazy Balloon), but this got me thinking about future games where I might not even be aware of something similar that existed before.

So, are there any tools or resources that you can recommend to check myself (due diligence I think it's called).


texts: Unity2D: The name `EventSystems' does not exist in the current context

texts:
I am having a problem with errors that "The name EventSystems does not exist in the current context". I made sure that I added using UnityEngine.EventSystems, so I'm a bit dumbfounded. Anyway, this is my code:

using UnityEngine;
using System.Collections;
using UnityEngine.EventSystems;  // As you can see, its "using" correctly.

public class PlayerMovement : MonoBehaviour {

    public GameObject currentSelectedGameObject;

    void Update () {
        if (Input.GetMouseButtonDown (0)) {
            if (!EventSystems.EventSystem.currentSelectedGameObject ()) {
                Vector3 mousePosition = Input.mousePosition;
                mousePosition.z = 10; // distance from the camera
                target = Camera.main.ScreenToWorldPoint (mousePosition);
                target.z = transform.position.z;
            }
        }

    transform.position =
            Vector3.MoveTowards (transform.position, target, speed * Time.fixedDeltaTime);
}


texts: How can I use custom shaders in Monogame?

texts:
I wrote a shader in XNA and I want to use it in a Monogame Windows Phone 8 project. I converted my Effect1.fx file to Effect1.mgfxo. But the program doesn't work correctly. The screen of my emulator is always black if I run this code and I get no error message. Why is the code not working? Why is the screen always black if I try to run my shader? Am I loading the shader correctly?

How can I use a custom shader in my Monogame Windows Phone 8 project?

My shader code:

float4x4 World;
float4x4 View;
float4x4 Projection;

sampler finalImage : register(s0);
sampler displacementMap : register(s1);

float4 main(float4 color : COLOR0, float2 texCoord : TEXCOORD0) : COLOR0
{
  float displacement = tex2D(displacementMap, texCoord);
  texCoord += displacement * 0.2;
  return tex2D(finalImage, texCoord);
}

technique Refraction
{
  pass pass_0
  {
    PixelShader = compile ps_4_0_level_9_3 main();
  }
}

Code:

public class Game1 : Game
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
private Texture2D back;
public Texture2D shockwave;
private RenderTarget2D finalImage;
private RenderTarget2D distortionMap;
private Effect distortionEffect;
private Vector2 Touchpoint;

public Game1()
{
    graphics = new GraphicsDeviceManager(this);
    Content.RootDirectory = "Content";
}

protected override void Initialize()
{
    base.Initialize();
}

protected override void LoadContent()
{
    TouchPanel.EnabledGestures = GestureType.Tap;
    spriteBatch = new SpriteBatch(GraphicsDevice);
    back = Content.Load<Texture2D>("background");
    shockwave = Content.Load<Texture2D>("shockwavesprite");

    finalImage = new RenderTarget2D(GraphicsDevice, GraphicsDevice.Viewport.Width, GraphicsDevice.Viewport.Height);
    distortionMap = new RenderTarget2D(GraphicsDevice, GraphicsDevice.Viewport.Width, GraphicsDevice.Viewport.Height);
    distortionEffect = Content.Load<Effect>("Effect1.mgfxo");
}


texts: What are the practical limitations of using XNA?

texts:
Since development on XNA has long since stopped, it is unlikely that it will ever be updated to be in line with modern graphics technology, however aside from the obvious fact that it's Windows-only - what are the practical limitations of using XNA?

The obvious ones are:

It uses DirectX 9.0 - which means no compute or geometry shaders.
It's Windows-only (Excluding Monogame/FNA)
It requires the installation of .NET and XNA on a client's computer.

#2 and #3 are obvious limitations, but can be considered acceptable. #1 on the other hand, is a bit more complicated. In practical terms what does being limited to DirectX 9.0 mean in terms of game development and graphical capability? No geometry or compute shaders means having to do more heavy lifting on the CPU, but is there any other limitations that an end user would notice? Ideally beyond a generic term such as "graphical fidelity".


texts: Can I have an Area affect the audio input of a Listener rather than the audio output of a speaker

texts:
Simple 3D use case: I have a Listener attached to my 3P character and a speaker attached to the environment, providing general background ambience (no attenuation).
When the character goes underwater, I'd like the environmental noise to be muffled and when they enter a building, I'd like echo, etc.
[Edit] In reality I have numerous AudioStreamPlayer3D objects attached to the environment (general ambience, sounds of a stream laid out along its course, sound attached to a NPC) so switching them all from one bus to another on on_body_entered and on_body_exited signals from the Area seems very inefficient, though I know I can probably achieve what I want that way.


texts: Solving banding with additive blended particles

texts:
I needed to implement particles for my 2D game, written in C++ with OpenGL for graphics, so I went ahead and created a nice geometry container to batch particles together and then implemented the basic stuff on them. So far so good, my particles work fine as intended, with a decent performance.

However, even tho my particles appear, animate and die the way they are supposed to, I am experiencing banding in the particles. All particles are drawn in a single draw call with additive blending. When I render a single particle I don't seem to get any noticeable banding, but the more particles I stack on top of each other, the more clear the banding becomes, giving unacceptable results.

I am doing nothing fancy with the rendering, it should work but here 's some more info.
Blend mode: glBlendFunc(GL_SRC_ALPHA, GL_ONE); (for particle textures with varying alpha)
Context: 32 bit color depth and nothing seems to be banding anywhere else, there isn't anything using low-precision
Fragment shader output: gl_FragColor = texture2D(texture, texUV) * outColor;

Also, I developed this system inspired in HGE particle editor. I am using the same particle texture that this program uses successfully, with no visible banding at all, but it doesn't work for me for some reason. Link: http://hge.relishgames.com/

Thanks


texts:
I'm looking into doing a 2d lighting system with a result similar to this: http://forums.tigsource.com/index.php?topic=15619.0 This thread I believe disregards color, as well as doesn't really list a clear final solution, which is something we could provide here.

What I'd like to do is start with a solid black texture, and render colored lights to it. When I render a colored light onto the texture, I'd like it to subtract the alpha away from the solid black texture but also add in the color of the light. In the end, my goal would be to have a texture that I can blend normally on top of my scene, using glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA), which would let the background show through in the "lighted" areas in addition to adding some of that lights color to the area.

To start I fill the texture with black:

glColor4f( 0.0f, 0.0f, 0.0f, 1.0 )

Then I set the blend function to subtract and draw the lights:

glBlendEquation( GL_FUNC_SUBTRACT );
glBlendFunc( ??? , ??? ); // Not quite sure what to put here

// Draw a triangle fan for the circle of light.
glColor4f( 0.0f, 0.0f, 0.0f, 0.8f );
glBegin(GL_TRIANGLE_FAN);
glVertex2f(0, 0);
glColor4f( 0.0f, 0.0f, 0.0f, 0.0f );
for (float angle = 0; angle <= 6.28; angle+=0.1) {
    glVertex2f(sin(angle) * sizeOfLight, cos(angle) * sizeOfLight);
}
glVertex2f(sin(3.14159*2) * sizeOfLight, cos(3.14159*2) * sizeOfLight);
glEnd();

// Reset this back to normal
glBlendEquation(GL_FUNC_ADD);

The guts of my question is what type of blending would I need here, on the second line of this code block.


texts:
About player leveling up, most (or maybe all..?) RPG games are like this:

Kill enemies (for experience points)
Level up (for more attack power)
Repeat

It's fun in the low levels, but later, it gets dull and boring; the game becomes more like increase your numbers to see more numbers.

I'm making an RPG game. I'm thinking of giving the player mini-quest(s) for each level to level up. For example, to reach level 2, player must fulfill the following:

Gain 10 EXP points.
Find an Ancient Jar.
Kill a Blue Wolf with a single attack.

So my question is: Are there games that have done this (I haven't seen/heard of any)? Is it good or bad idea? Even if there are games that have done this technique, why most (or all) RPG games are going with the kill-levelup-repeat process?


texts:
I am trying to create multiple BoundingBoxes on a Model by following this tutorial:

https://electronicmeteor.wordpress.com/2011/10/25/bounding-boxes-for-your-model-meshes/

However, I keep getting this error: Requested range extends past the end of the array. on this line:

part.VertexBuffer.GetData(part.VertexOffset * stride, vertexData, 0, part.NumVertices, stride);

I can't figure out why it is giving me that. I load my model and try to create the boxes like this:

Model model = this.Content.Load<Model>("Cube");
MeshModel box = new MeshModel(model);

Instead of passing a String path of the model, I just pass the Model itself (I changed the constructor to accept Model model).

Any help would be appreciated!

Here's what the debugger says (the vertexStride and VertexBuffer has 24 which is the same size as the vertexData so it should be ok):


texts: What data am I allowed to collect for statistical purpose ?

texts:
Description

I would like to know where is the limit between the data I am allowed to store and the data that is private. I don't know if there is a legal limit or if it is ethical. I know what kind of statistics the games usually display but there may be others that they hide. I would like to collect data and combine them to make conclusions, I don't want the player to see the raw data.

Some examples

1) Information about the character (usual data)

  Number of type A enemy killed.
  Max gold collected.
  ...

2) Information about the player himself

  Number of hour played.
  Time when he started to play.
  Number of time playing between 11pm and 6am.
  ...

3) Information about the messages (if there is a chat in the game for example)

  Number of message sent.
  Most used word.
  Most contacted person.
  ...

I would prefer not to display a warning on the first launch of the game saying that informations are being collected or something like this.

The actual question

My question can be separated into the following questions:

Am I allowed to collect type 1, 2, 3 datas ?
Is there a difference of autorisation if the datas are stored/used localy or in an online database ?


texts: How to use camera in Google VR SDK 1.50 for Unity?

texts: I have looked at many tutorials on making an Android app for Google Cardboard in Unity, but all of them were for older versions of the GVR SDK. How do I simply add a stereo camera in version 1.50 (with Unity 5.6)?


texts:
There is a video here that shows how the camera rotates around Leon.
The camera rotates around Leon in a circle, this is not difficult, but I don't understand the timing logic.

Once given a short push, the camera keeps rotating for a few more milliseconds.

If the camera would only be rotated during the real mouse movement, the camera would not keep rotating a bit after there is no more mouse movement.

However, in this video, the camera rotates a few more milliseconds even after the last mouse movement.

How could this be accomplished?

Specifically, I would like to ask if somebody can tell me if the developers add some extra movement in the direction of the mouse movement which they then "smooth out", or if they "smooth out" the end of the user's mouse movement.

Thank you!


texts: Creating a 2D sidescroller with different behavior in each level

texts: I'm creating a game with levels built from tilemaps in LibGDX. I've created the logic for the game that adds entities based on object layers, however, many levels have different behaviors. Do I need to create a separate class for every single level, or should I build in logic to handle every possible scenario in the class that loads levels?


texts:
I couldn't find an answer to this so I'm asking here, I've made a voxel engine and it's working reasonably well, except for a small detail: I have yet to figure out how to seed my simplex noise engine, the internet gave me two suggestions:

Generate simplex of one dimension higher with the fourth axis being the seed, this worked but was painfully slow in comparison.

Shuffle the permutation table, I like this idea. It should (if my understanding of math is correct) yield 512! permutations, however I don't know how to shuffle an array reliably in a deterministic manner, I want the shuffle to be the same every time I use the same seed.
so something like shuffle(perm, 12) would return the same every time the seed is 12 but something different when the seed is 22321.

So what I really wish to know is either how to shuffle the permutation table in a fast, reliable and deterministic manner using a seed or a better method for seeding simplex noise.


texts: Converting a Flash animation to Silverlight

texts:
I recently had an animated logo done in Flash for Deen Games. I need to display in all my Silverlight games. The problem is, the logo is about ~8 seconds long (205 frames); if I export all the images as even JPEGs, the result is almost 3.5MB of content (more than the game itself).

I tried exporting as various formats (PNG, JPG, GIF, etc.) but nothing is small enough. What are my options? How can I incorporate these into my game without blowing up the file size?

There's always the option of "recreate it in-game with animation/rotation/etc. as it is now) but that's tons of work and I'd rather avoid that.

And no, just a static image is not good enough!

Edit: Exporting as a movie (AVI, MPEG) won't work since XNA doesn't support movies at this time.


texts: Help with unity cel shader not work when turning away from the main light?

texts: So i'm using this really good toon shader I found, that works with multiple directional and point lights. Only problem is, it acts weirdly when turning away from the main light seen here, ( sorry for the video in the backround). I would like it be be more realistic, like in real life where light bounces off multiple objects. As of now, if it's in shadow in acts as if no light is hitting it. Would appreciate any help, and apologize if this issue is stupid, i'm still learning shaders.


texts: C++ Generate random float values between a range

texts:
In my current situation I have a game world, in that game world I want to place loads of tree models. It is a waste of time for me to actually explicitly define the x y and z values of each tree model, so I want to do this with the help of random logic, so that it can just set the values for me. I don't want true randomness, so I do not need to seed the random logic, I want to generate the positions of all the trees randomly so that I don't need to type each one myself, but each time I run the game the trees are in the same position, so it is not truly random but that is what I want.

My current attempt is as follows:

for (int i = 0; i < numOfTrees; i++) {
        treeObjects.push_back(
        (new Entity(Vector3f(//x, y and z position value of each tree
                             rand() % 200 + (-200), //random value for x
                             0.0f,                  //y value kept as 0.0f
                             rand() % 200 + (-200)) //random value for z
//above code positions the trees, the rest of the code is irrelevant
}

The issue with this is that all the trees are very tightly packed together, so I am very skeptical that they are getting a value between -200 and 200, because if they were they would be much more spread out. Does someone know of a better solution to produce what i'm after? maybe there is an issue with the way I am doing it?


texts: How can I simplify my state machine transitions?

texts:
I currently have the following base class which I inherit from for my player states (e.g. Idle, Walking, Jumping).

struct PlayerState : std::enable_shared_from_this<PlayerState> {
    virtual ~PlayerState() {
    }

    virtual auto handle_input(const Input& input) -> std::shared_ptr<PlayerState> {
        return shared_from_this();
    }

    virtual auto update(AudioQueue& audio_queue, double dt) -> std::shared_ptr<PlayerState> {
        return shared_from_this();
    }
};

handle_input and update can both be overridden to allow transistions between states, e.g.

struct IdleState : PlayerState {
    virtual auto handle_input(const Input& input) -> std::shared_ptr<PlayerState> override {
        bool jump = input.was_button_pressed(0);

        if(jump) {
            return std::make_shared<JumpingState>();
        }

        return shared_from_this();
    }
};

This works reasonably well and lets me write new states very quickly, however as the number of states is expanding I find I'm repeating myself a lot.

Take the example above, the code for handling jumping is duplicated in both the Idle and Walking states (as you can jump from either).

I'm sure there must be a better way to model these transitions but I just can't see it right now.

My first idea was to add an additional property to each state, e.g. bool can_be_jumped_from and then pushing the logic for jumping down into the base PlayerState class and ensure all inherited classes call the base handle_input method before their own. My concern here is that the number of these flags will grow every time I have a state that can be transitioned to from multiple places.

Is there an another simpler/tidier implementation I'm missing here?


texts: Anyone know any free or non-free RTS engine that can be used for iOS game development?


texts: Why does my palette swapping code in D3D9 not have any effect?

texts:
I want to do palette swapping in my game, in a fast way and without shaders, so I couldn't replace pixels in a texture, then I tried to use the SetPaletteEntries and SetCurrentTexturePalette method, but it's not working.

static int counter = 0;

// Palette swapping experiment
PALETTEENTRY entries[256];

if (counter == 0)
{
    // Fill the palette entries with 0xFFFFFFFF
    FillMemory(&entries, sizeof(entries), 0xFF);

    // Set the palette entries in the palette index.
    if (FAILED(window.device->SetPaletteEntries(0, (PALETTEENTRY*) &entries)))
        throw std::runtime_error("SetPaletteEntries()");

    // Set the current texture palette
    if (FAILED(window.device->SetCurrentTexturePalette(0)))
        throw std::runtime_error("SetCurrentTexturePalette()");

    ++counter;
}
///////////////////////////////////////////
else if (counter == 1)
{
    // Fill the palette entries with 0x8080FFFF
    for (int i = 0; i < sizeof(entries) / sizeof(PALETTEENTRY); ++i)
        entries[i] = {0x80, 0x80, 0x80, 0xFF};

    // Set the palette entries in the palette index.
    if (FAILED(window.device->SetPaletteEntries(0, (PALETTEENTRY*) &entries)))
        throw std::runtime_error("SetPaletteEntries()");

    // Set the current texture palette
    if (FAILED(window.device->SetCurrentTexturePalette(0)))
        throw std::runtime_error("SetCurrentTexturePalette()");

    ++counter;
}

I'm loading the textures with DDSTextureLoader, and no exceptions are being thrown.
Thanks for reading.


texts: How do I properly use String literals for loading content?

texts:
I've been using verbatim string literals for some time now, and never quite thought about using a regular string literal until I started to come across them in Microsoft provided XNA samples. With that said, I'm trying to implement a new AudioManager class from the Net Rumble sample.

I have two (2) issues here:

Question 1: In my code for my GameplayScreen screen I have a folder location written as the following, and it works fine:

menuButton = content.Load<SoundEffect>(@"sfx/menuButton");
menuClose = content.Load<SoundEffect>(@"sfx/menuClose");

If you notice, you'll see that I'm using a verbatim string, with a forward slash "/".

In the AudioManager class, they use a regular string literal, but with two backslashes "\". I understand that one is used as an escape, but why are they BACK instead of FORWARD? (See below)

soundList[soundName] = game.Content.Load<SoundEffect>("audio\\wav\\"+ soundName);

Question 2:
I seem to be doing everything correctly in my AudioManager class, but I'm not sure of what this line means:

audioFileList = audioFolder.GetFiles("*.xnb");

I suppose that the *xnb means look for everything BUT files that end in *xnb? I can't figure out what I'm doing wrong with my file locations, as the sound effects are not playing. My code is not much different from what I've linked to above.

private AudioManager(Game game, DirectoryInfo audioDirectory) : base(game)
{
    try
    {
        audioFolder = audioDirectory;
        audioFileList = audioFolder.GetFiles("*.mp3");
        soundList = new Dictionary<string, SoundEffect>();

        for (int i = 0; i < audioFileList.Length; i++)
        {
            string soundName = Path.GetFileNameWithoutExtension(audioFileList[i].Name);
            soundList[soundName] = game.Content.Load<SoundEffect>(@"sfx\" + soundName);
            soundList[soundName].Name = soundName;
        }

        // Plays this track while the GameplayScreen is active
        soundtrack = game.Content.Load<Song>("boomer");
    }
    catch (NoAudioHardwareException)
    {
        // silently fall back to silence
    }
}


texts: How to balance audio levels to be loud enough yet safe

texts:
There are a few sound effects in my game that sound a bit piercing over earbuds but OK when played through the iPhone speaker. Also sound levels seem lower on older hardware. Is there some objective way to be sure my sounds are loud enough yet safe?

Notes: I made my music with GarageBand for iPad. The output was very hot but not clipped. To preview the sounds on my computer I played them in the iPad simulator and matched the volume coming out of my iPhone. To resolve my volume issues, I reduced the high end in Amadeus Pro using the EQ tool. A couple passes for each of the worst sound clips let me reduce the shrillness without muting the volume too badly. Thanks everyone for your help.


texts:
The Plan

I am up to write write an own Trigger/Event System, an event engine or how you call it. I would like to achive something similar to Blizzard's most level editors, like Starcraft 1-2, Warcraft level editors.
They are all kind of event/trigger based, you can set actions, conditions which actually control the gameplay itself. What do you think, what would be the best architecture for this event/trigger system?

The Architecture

I thought it would look something like this:

EventManager - would handle the events, checking if the conditions
meet for any event,
                  and calls the event if so.
EventHolder - would hold the list of the events.
EventEntity - would have an ID, the actions' ID and the params for
them.

Every entity, enemies, player and other stuff would have an ID in the world, which would help to get the entity itself and fire a trigger on it.
Obviously, there would be finit and pre-set BASIC actions, but that would be stored by the current project itself. The project could pass the EventSet (list of EventEntity) to the EventHolder. Thus this whole event/trigger system would be very flexible, and could compile it as a DLL for use in future projects.
Do you have any better solution for this? Or some pro tips that I could use? Would really appreciate any help! Thanks!

Edit:
This picture shows it quite well:

Edit2:
I have wrote a raw architecture of a possible "engine", but it is missing some MAIN points:

{Initializing}

//in order
[Game]--set event list--[EventManager]--requests list of EventEntity--[Game]--sends list of EventEntity--[EventManager]

{EventManager loop}

[EventManager]--checks if any of the events meet in an EventEntity
[EventManager]--if any meets--[EventManager]--checks if all of the conditions are meeting in the EventEntity
[EventManager]--if all meets--[EventManager]--fires actions of the EventEntity

{Architecture of the Models}

[EventEntity] contains
- [List of Event Models]
- [List of Condition Models]
- [List of Action Models]

[EventModel] contains
//quite similar to the ConditionModel, an event only should fire, aka check the conditions and
//fire the actions, if these special conditions, happenings, events are fired
//like a unit dies, player reaches a specific position, etc.

[ConditionModel] contains
//model must simulate AND, OR logic statements
//model must simulate IF statements

[ActionModel] contains
- [List of Targets]
- [List of Action IDs] //One action per Target, a specific Target can be listed more than once in the [List of Targets]
//something is missing

Trying to write the "system" as standalone as possible, it must not depend on any project's source. Thus I think the best would be to seperate the data from the architecture, could store the event, condition and action datas in another DLL unit, and could read from that.


texts:
I suddenly have the feeling that I have absolutely no idea how to implement invisible objects/bones.

Right now, I use hardware instancing to store the world matrix of every bone in a vertex buffer, and then send them all to the pipeline. But when dealing with frustum culling, or having them set to invisible by my simulation for other reasons, means that some of them will be randomly invisible.

Does this mean I effectively need to re-fill the buffer from scratch every frame with only the visible unit's matrices? This seems to me like it would involve a lot of wasted bandwidth.


texts:
I am building a Facebook App Game and was wondering what a safe height and width for my canvas.  I know that the current standard is 760 and there are questions about that, but I would like to know what a good height would be.  I would like it to take into account smaller screen sizes.  My game is a sidescroller.

I know there are a few Facebook App questions similar to this but I feel mine is different because I am concerned with the height in addition to the width


texts: Apparent FPS drop despite clear CPU usage drop in profile window

texts:
I have an unusual performance drop (or visual choppiness) that isn't showing in the profile window at all like I'd expect.

When using Vegetation Studio Pro and AQUAS together, I get what looks like a serious FPS drop when I look up at the sky (away from terrain) or back down at the terrain.

However, the moment always coincides with a major drop in CPU usage (seen in the following pic). I've never seen performance issues like drop cpu usage - usually they appear as major spikes, reaching higher (meaning lower FPS) on this chart.

I'm not used to the newer Unity profile window, so I may be missing some obvious clues, but what could cause such a perceived FPS drop when the cpu usage drops?

Why does the VSync category seem to disappear for a period of time?

I'm unable to reproduce the effects when I turn off VSPro or AQUAS. Whatever the real cause is, it seems related to them being used together. I don't see any indication of the same issue when I use them individually.

Edit1: The issue goes away when I disable the Caustics system in AQUAS. It's a projector system. I still don't understand what specific issue the profiler is communicating to me.


texts: Is it possible to interpolate different sprites?

texts:
I can interpolate different animations based on position, rotation, and scale.  I want to do the same for different sprites, automatically.

For example, lets say I have a soda can being crushed.  I have 2 sprites:  One is the soda can uncrushed, and one is the soda can fully crushed.  I want to only use those 2 sprites, and have Unity automatically transition from the normal can to the crushes can.

How can I do this without making a bunch of key frames in between?


texts:
In my game I have a simple click to move character. On GetMouseButtonDown(0) (when mouse is clicked) I want the character to move to the location of the click, as long as the click does not occur on a UI element.

That's simple enough, I can use if(Input.GetMouseButtonDown(0) && !UnityEngine.EventSystems.EventSystem.current.IsPointerOverGameObject())

However, in every GetMouseButton(0) case except when mouse is initially clicked (when mouse button is held down), I want to be able to move even if my mouse is positioned behind a UI element.

So let's say I have an inventory open. I do not want clicking on the inventory to move my character. But if I click somewhere else and begin to move my character, and then move my mouse cursor behind the inventory, I want the character to continue moving. That is why I can't just do if(Input.GetMouseButton(0) && !UnityEngine.EventSystems.EventSystem.current.IsPointerOverGameObject()).

I also can't do if(Input.GetMouseButtonDown(0) && !UnityEngine.EventSystems.EventSystem.current.IsPointerOverGameObject()) || !Input.GetMouseButtonDown(0) && Input.GetMouseButton(0))

Using a counter to measure elapsed time and then doing something like if(Input.GetMouseButton(0) && timer > 0.2f) doesn't seem to solve the problem either because I never want to move if the click origin is on a UI object, despite how much time has elapsed.


texts: Binding BoundingSpheres to a world matrix in XNA

texts:
I made a program that loads the locations of items on the scene from a file like this:

using (StreamReader sr = new StreamReader(OpenFileDialog1.FileName))
                    {
                        String line;
                        while ((line = sr.ReadLine()) != null)
                        {
                            red = line.Split(',');
                            model = row[0];
                            x = row[1];
                            y = row[2];
                            z = row[3];
                            elements.Add(Convert.ToInt32(model));
                            data.Add(new Vector3(Convert.ToSingle(x), Convert.ToSingle(y), Convert.ToSingle(z)));
                            sfepheres.Add(new BoundingSphere(new Vector3(Convert.ToSingle(x), Convert.ToSingle(y), Convert.ToSingle(z)), 1f));
                        }

I also have a list of BoundingSpheres (called spheres) that adds a new bounding sphere for each line from the file.
In this program I have one item (a simple box) that moves (it has its world matrix called matrixBox), and other items are static entire time (there is a world matrix that holds those elements called simply world). The problem i that when I move the box, bounding spheres move with it. So how can I bind all BoundingSpheres (except the one corresponding to the box) to the static world matrix so that they stay in their place when the box moves?


texts: How to automatically generate (creative) names for stuff?

texts:
How can I get large number (100-1000-10 000) of names, that are at most average hard to spell for things like places, weapons (and NPCs).

Have a look at TES4 Oblivion or TES% Skyrim.

http://www.uesp.net/wiki/Oblivion:Places

Yes, I understand, that they have paid army of designers for years.

My questions is how this people are creating those names?
Is there some hints for this, like should have at least/most this amount of letters or maybe let's create three sets of words - beginnings, middle and endings, and then take one random word from each?

Can it be automatized? Do they check, if created name means anything in any language?

This question is meant as extension for other questions like this, especially: Name generation

Above question was about NPC names, I am looking for something generic, especially for places and artifact names.

I am aware of Markov chains, but even after automatic generation, I would need a way to check, if this "sounds" good and if it means anything in nay language.

As much as second thing can be probably automatized, that first one not really.

Is there any full solution? Do we know, what kind of solution does Oblivion/Skyrim use? Most important part of this question is automatizing part.


texts: Build a handshake server for a multiplayer game

texts:
I'm making a multiplayer mode for a game I developed, and it works over UDP.
What I need now is a server to let a player know another player, and send each one the other's IP.
I own a VPS that I'm currently using to host a few websites, so I guess I can use it for this purpose too.

I would choose Python as a language to build it.  But I don't know where to start...
Should I make it on HTTP or TCP?
Is there any library I can use to simplify the work?
Or any example of something similar?

Any help will be appreciated.


texts: How do I prevent identity spoofing in a multiplayer game?

texts:
I'm thinking about clients spoofing IP addresses, tricking other clients that they are the server; that sort of stuff. (I don't know much about this, so if this is completely wrong, please correct me.)

What should I do to prevent this? Because it is a real-time game, if I were to use encryption, I would use something fast and secure like RC4. Should I encrypt packet data with a key, that the server gives to the client?

If it makes any difference, I'm using UDP.


texts: What's the difference with how Box2D and Farseer behave in terms of collisions?

texts:
I've ported my engine to iOS and have been using the C++ version of Box2D. Everything runs fine except on collisions, it seems Box2D and Farseer handle collisions somewhat differently.

Anyone know what these differences are exactly and if I can disable the difference and make them mimic one another?

Initial behaviours tend to be fine, for example falling speeds and the first moment of impact both cases exhibit the exact same behaviour, velocities etc.

Just after the first impact is resolved however the second impact (which occurs as a result of bodies being bumped around) is different. box2d records a higher velocity on a second collision than the first and shows less 'bounce back' from the collision.

Velocity, position iterations are the same, as are the bodies masses, densities etc. Pretty sure everything in Farseer.Settings matches up with Box2Ds settings.


texts: Using a Compute Shader in Unity to convert a texture to a float array

texts:
I have a fairly simple requirement for a compute shader (DirectCompute through Unity). I have a 128x128 texture and I'd like to turn the red channel of that texture into a 1d array of floats. I need to do this very often so just doing a cpu-side for loop over each texel won't cut it.

Initialization:

    m_outputBuffer = new ComputeBuffer(m_renderTexture.width * m_renderTexture.height, sizeof(float));
    m_kernelIndex = m_computeShader.FindKernel("CSMain");

Here is the C# method:

/// <summary>
/// This method converts the red channel of the given RenderTexture to a
/// one dimensional array of floats of size width * height.
/// </summary>
private float[] ConvertToFloatArray(RenderTexture renderTexture)
{
    m_computeShader.SetTexture(m_kernelIndex, INPUT_TEXTURE, renderTexture);

    float[] result = new float[renderTexture.width * renderTexture.height];

    m_outputBuffer.SetData(result);
    m_computeShader.SetBuffer(m_kernelIndex, OUTPUT_BUFFER, m_outputBuffer);

    m_computeShader.Dispatch(m_kernelIndex, renderTexture.width / 8, renderTexture.height / 8, 1);

    m_outputBuffer.GetData(result);

    return result;
}

and the entire compute shader:

// Each #kernel tells which function to compile; you can have many kernels
#pragma kernel CSMain

// Create a RenderTexture with enableRandomWrite flag and set it
// with cs.SetTexture
Texture2D<float4> InputTexture;
RWBuffer<float> OutputBuffer;

[numthreads(8, 8, 1)]
void CSMain(uint3 id : SV_DispatchThreadID)
{
    OutputBuffer[id.x * id.y] = InputTexture[id.xy].r;
}

the C# method returns an array of the expected size, and it usually sort-of-corresponds to what I expect. However, even if my input texture is uniformly red, there'll still be some zeroes.


texts: What are some alternative options for saving level data for a game like Hurtworld?

texts:
For a multiplayer building/crafting game like Hurtworld (where the player can build structures on the map), what are some alternative options or example data structures for saving the world data on the server?

Level data including:

Grid of squares that foundations can be built on, with a flag to indicate whether the square is empty or already has a foundation
Walls etc which have been built on the foundations, and multiple floors above
Windows/doors which can be built on window frames/door frames
Furniture/machines which can be placed on foundations/floors
Other dynamic world data such as trees, animals, chests with items, etc

I feel like it's too much data to store in a database. Am I wrong?

If it can be stored in a database, how can I get my head around the data structure I would need to set up? Is there some simplified example?

Can each square in the world grid be represented by 1 row in the database? And should there be a new row for each structure built on a square, with that row referencing the square/structure that it was built on?


texts: How can I make a character smoothly traverse a list of waypoints?

texts:
I want to set up paths for enemy characters in my game to patrol. I'd like to be able to define a list of waypoints and have the enemy follow the path from one point to another, but in a smooth curve.

How can I do this?


texts: Rotating kinematic object around a moving point Box2D

texts:
I'm new at Box2D and I am making a simple game where you control the rotation of the maze and the gravity leads the ball to the exit.

The game looks like:

The problem: I want to rotate the maze, and I'm doing it well. It is a kinematic object, so it will only move when I want. But it always rotate on a static pivot, I think that's it's center of mass. Rotating the maze, the ball hits the walls and when too further to the center, it becomes hard to control the movement of the ball by rotating the maze as the centrifugue force is too high for the ball.

What I want: I want to change the maze's rotation pivot to the ball's position, every game loop/frame, so it will rotate around the ball always and I will be able to use only gravity, not centrifuge forces, to lead the ball to the exit.

What I tried: I already tried to find a function to change the pivot center, or the center of mass, but I only found to change the mass proprieties. It changes the center of mass only if it was a dynamic body. Even the kinematic body having the same localCenter.x and localCenter.y proprieties as the dynamic body, it remains on (0.0 ,0.0) when trying to change it. And when changing the localCenter on the dynamic body, it doesn't rotate at this point anyway, so I'm not sure what to do.

Is there any possibility to change the center of the kinematic body all the time? I'm using Box2D Vestion 2.3.2, as you can see on the picture, and Visual Studio 2013 with OpenGL.

Thanks!


texts: switching from third person view to first person view

texts:
I have done a scene in opengl where I'm using a third person camera (that I can control with the mouse). Then, inside it, it has the camera of the first view (that I called thirdpersonCamera, see the code above), drawing the camera, the frustum etc..

It looks like this picture:

and I've done with this code:

void GLView::drawSubThirdpersoncamera()
{
    // set perspective viewing frustum in the 3rd person camera
    thirdpersonCamera.setFrustum(FOV_Y, (float)(W)/(H), NEAR, FAR);

    // use 3rd person camera projection matrix (the frustum, the perspective etcetera)
    // as the opengl camera
    glMatrixMode(GL_PROJECTION);
    glLoadMatrixf(thirdpersonCamera.projectionMatrix.getTranspose());
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();

    glPushMatrix();
    {
        // First, transform the camera (viewing matrix) from world space to eye space
        glLoadMatrixf(thirdpersonCamera.viewMatrix.getTranspose());

        // translate and rotate the mouse control
        // (keeping the camera fixed because
        // we want only the scene to rotate/translate)
        // for thinking about modern opengl: should be a matrix..
        glTranslatef(mousePosition[0], mousePosition[1], mousePosition[2]);
        glRotatef(mouseAngle[0], 1, 0, 0); // pitch
        glRotatef(mouseAngle[1], 0, 1, 0); // heading
        glRotatef(mouseAngle[2], 0, 0, 1); // roll

        // now the draw the scene
        drawScene();

        // draw the first person camera
        glPushMatrix();
        {
            glMultMatrixf(physicalCamera.viewMatrix.getTranspose());

            drawAxis(4);
            drawCamera();
            drawFrustum(physicalCamera.fovy, physicalCamera.aspectRatio, physicalCamera.near, physicalCamera.far);
        }
        glPopMatrix();

    }
    glPopMatrix();
}

Now I want to switch to the eye of the camera I've drawn, with this code:

void GLView::drawSubPhysicalCamera()
{
    // use physical camera projection matrix (the frustum, the perspective etcetera)
    // as the opengl camera
    glMatrixMode(GL_PROJECTION);
    glLoadMatrixf(physicalCamera.projectionMatrix.getTranspose());
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();

    glPushMatrix();
    {
        // the view matrix: how the camera is positioned in the world space
        glLoadMatrixf(physicalCamera.viewMatrix.getTranspose());

        drawScene();
    }
    glPopMatrix();

}

I think it should go because I'm using the same matrix once for translate the object in the screen, once for translate the camera but.. in the second view I don't see anything.. I don't find any error because the transformation in the space is the same but.. it doen't work..

Where am I wrong?


texts: Coarse Collision Detection in highly dynamic environment

texts:
I'm currently working a 3D space game with A LOT of dynamic objects that are all moving (there is pretty much no static environment). I have the collision detection and resolution working just fine, but I am now trying to optimize the collision detection (which is currently O(N2) -- linear search). I thought about multiple options, a bounding volume hierarchy, a Binary Spatial Partitioning tree, an Octree or a Grid. I however need some help with deciding what's best for my situation. A grid seems unfeasible simply due to the space requirements and cache coherence problems.

Since everything is so dynamic however, it seems to be that trees aren't ideal either, since they would have to be completely rebuilt every frame. I must admit I never implemented a physics engine that required spatial partitioning, do I indeed need to rebuild the tree every frame (assuming that everything is constantly moving) or can I update the trees after integrating?

Advice is much appreciated - to give some more background: You're flying a space ship in an asteroid field, and there are lots and lots of asteroids and some enemy ships, all of which shoot bullets.

EDIT:
I came across the "Sweep an Prune" algorithm, which seems like the right thing for my purposes. It appears like the right mixture of fast building of the data structures involved and detailed enough partitioning. This is the best resource I can find.

If anyone has any suggestions whether or not I'm going in the right direction, please let me know.


texts: Godot: Move_and_slide_with_snap not working on slopes

texts:
My Problem
I am currently building a platformer game. I was attempting to use move_and_slide_with_snap for the first time and can't find it working for me. My character does snap to the ground like I expected, but I find that it still slides when it's on a slope. I think that I implemented the code properly with it.
If there is a solution I would love to hear it. What am I doing wrong?
func _physics_process(delta):

var current_gravity = GRAVITY - (int(is_on_wall() and inventory.Frog) * GRAVITY/2)
var current_jump_force = JUMP_FORCE

var x_input = Input.get_action_strength("ui_right") - Input.get_action_strength("ui_left")

if x_input != 0:

    motion.x += x_input * ACCELERATION * delta
    motion.x = clamp(motion.x, -MAX_SPEED, MAX_SPEED)

else:

    playback.travel("Stand")

if !is_on_wall():
    if motion.y <= max_fall_speed:
        motion.y += current_gravity * delta
else:
    if motion.y <= max_slip_speed:
        motion.y += current_gravity * delta

if is_on_floor() or is_on_wall():
    if x_input == 0:
        motion.x = lerp(motion.x, 0, FRICTION)

    if Input.is_action_just_pressed("ui_up"):
        var can_jump = int(inventory.Spring)
        motion.y = -(current_jump_force + (JUMP_FORCE / 2.5 * can_jump))
else:

    if Input.is_action_just_released("ui_up") and motion.y < -JUMP_FORCE/2:
        motion.y = -current_jump_force/2

    if x_input == 0:
        motion.x = lerp(motion.x, 0, AIR_RESISTANCE)

if !motion.y:
    motion = move_and_slide_with_snap(motion, Vector2.DOWN * 320, Vector2.UP, true, 1)
else:
    motion = move_and_slide(motion, Vector2.UP)


texts: Where are the requirements documents for console game software?

texts:
I hear that the console game platforms have strict requirements for their games. For example I just read an answer that stated loading screens must have an animation on them so that the game doesn't appear to be frozen -- this makes sense, of course! I think a lot of the guidelines in these books would probably be great information.

Are these documents protected in some way or is there someplace on the internet where I can read them? I would love to read through all the guidelines for good design that the console manufacturers have put in place to give console players a good experience, and probably to adhere to them in my own games (at least those which are not console-specific, obviously).

So, where can I find these fabled console video game design guidebooks?


texts: Unity and Apple TV Remote control sensitivity

texts:
I'm developing a game for Apple TV and I'm responding to the swipe gesture using

if (Input.GetKeyUp(KeyCode.Joystick1Button4)){
   DoSomething();
}

But the problem is that this is too sensitive, and triggers when the player didn't intentionally swipe. Is there any way to set the sensitivity?


texts: How can I record from a second in-game camera and later export it to a video file?

texts:
I'm making a PC Horror game in Unity, and I want to have a camera recording simulation in-game - so you can leave a creepy location anytime, and you will have a tape with what you recorded on camera while exploring.
Technically, I need to attach a second camera (hand-cam) to the character's hand, and let the player look through the viewfinder by pushing a button. But in any position, the hand-cam must record everything that is in its focus at that point - floor, stairs, rubbish, etc, whether it's lowered at hand level or raised to match the player's viewpoint.
When the game ends (player leaves or dies), I'd like to have an option to save recorded tapes to a video file (if this is not possible, then to some save file).
How can I implement such a feature in my game? Are there some special Unity tricks, or add-ons and additional modules? Saving decorations and scenes with active triggers, or just grabbing video from screen?
Below is a quick MSPaint concept of what I mean:


texts:
Kinect for Windows SDK 1.6 is available for users to download. What I enquire is: Can I publish a commercial game with it? Do I have to apply for anything?

I've searched through the Microsoft's Kinect documentation about the subject but failed to find the information I'm looking for. It is impossible to publish a game for XBOX using Kinect, I know that. But what about Windows?


texts:
I want to make a game which is totally same idea as "Who pressed the button answers the question".

I have 2 joysticks and both are connected to a pc. My application will be Winforms and I will develop it on Visual studio 2012.

I've used SlimDX, Sharpx so far I've found nothing for multiple joysticks. My problem is not mesuring the time until a player presses a button, all I want to know is which joystick / gamepad have pressed a button first.

Could you give me ideas about how I can achieve this ?


texts: Is there a simpler way to create a borderless window with XNA 4.0?

texts:
When looking into making my XNA game's window border-less, I found no properties or methods under Game.Window that would provide this, but I did find a window handle to the form.

I was able to accomplish what I wanted by doing this:

IntPtr hWnd = this.Window.Handle;
var control = System.Windows.Forms.Control.FromHandle( hWnd );
var form = control.FindForm();
form.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;

I don't know why but this feels like a dirty hack.  Is there a built-in way to do this in XNA that I'm missing?


texts:
I'm working on a radiosity processor. I'm projecting scene geometry onto a hemisphere at a high order of tessellation during a visibility pass onto a 1024x1024 render target. The problem is that the edges of certain triangles are not being rendered to the item buffer( render target )...so when I test certain edges( or pixels during pixel shader ) for visibility during a reconstruction pass, visible edges are not identified and as a result the pixel for that edge is discarded.

One solution was to increase the resolution of the item buffer( up to 4096x4096 )...this helped and more edges were visible, however, this was not fullproof.

How do I increase visibility?

Here is a screenshot of a scene after radiosity is applied: the seams are edges along a triangle face that were not visible due to the resolution of the item buffer...

fixed the problem by sampling the item buffer w/8 points:

code to convert world space position into normalized device coordinates for uv lookup of item buffer:

// position lookup for item buffer
    Output.Pos3 = mul( Input.Position, mWV );
// projection is handled by normalizing the viewspace position( as i'm rendering to a hemisphere )
    Output.Pos3.xyz = normalize( Output.Pos3.xyz );

// convert to normalized device coordinates( [ -1, 1 ], [ -1, 1 ] -> [ 0, 1 ], [ 0, 1 ] )
    Output.Pos3.xy *= float2( 0.5, -0.5 );
    Output.Pos3.xy += float2( 0.5, 0.5 );


texts: Unity3D draw call optimization : static batching VS manually draw mesh with MaterialPropertyBlock

texts:
I've read Unity3D draw call batching documentation.

I understood it, and I want to use it (or something similar) in order to optimize my application.

My situation is the following:

I'm drawing hundreds of 3d buildings. Each building can be represented using a Mesh (or a SubMesh for each building, but I don't thing this will affect performances)
Each building can be textured with several combinations of texture patterns(walls, windows,..). Textures are stored into an Atlas for optimizaztion (see Texture2d.PackTextures)
Texture mapping and facade pattern generation is done in fragment shader. The shader can be the same (except for few values) for all buildings, so I'd like to use a sharedMaterial in order to optimize parameters passed to the GPU.

The main problem is that, even if I use an Atlas, share the material, and declare the objects as static to use static batching, there are few parameters(very fews, it could be just even a float I guess) that should be different for every draw call.

I don't know exactly how to manage this situation using Unity3D.
I'm trying 2 different solutions, none of them completely implemented.

Solution 1

Build a GameObject for each building building (I don't like very much the overhead of a GameObject, anyway..)
Prepare each GameObject to be static batched with StaticBatchingUtility.Combine.
Pack all texture into an atlas
Assign the parent game object of combined batched objects the Material (basically the shader and the atlas)
Change some properties in the material before drawing an Object

The problem is the point 5. Let's say I have to assign a different id to an object before drawing it, how can I do this?

If I use a different material for each object I can't benefit of
static batching.
If I use a sharedMaterial and I modify a material property, all GameObjects will reference the same modified variable

Solution 2

Build a Mesh for every building (sounds better, no GameObject overhead)
Pack all textures into an Atlas
Draw each mesh manually using Graphics.DrawMesh
Customize each DrawMesh call using a MaterialPropertyBlock

This would solve the issue related to slightly modify material properties for each draw call, but the documentation isn't clear on the following point:

Does several consecutive calls to Graphic.DrawMesh with a different MaterialPropertyBlock would cause a new material to be instanced?

Or Unity can understand that I'm modifying just few parameters while using the same material and is able to optimize that (in such a way that the big atlas is passed just once to the GPU)?


texts: Local to World coordinates in 2D and back

texts:
I'm getting back into hobby game programming after a long 4-year hiatus from college and I find that my understanding of coordinate systems is somewhat lacking.

I'm trying my skills at creating a simple skeletal animation system but I'm having a hard time wrapping my head around converting local coordinates (of say, a joint) to world coordinates, particularly when it comes to rotated sprites.

I'm trying to create a test app in XNA and accomplish this using their built-in matrix class.  Can anyone assist me in either linking a resource or helping me understand the operations I'd need to do to convert any point that is Scaled/Rotated/Translated from a local to a world coordinate and back?


texts: SlimDX Direct3D10 Sprite stretches with window size

texts:
I'd like to draw a sprite bitmap with SlimDX Direct3D10, but I'm stuck at this  problem, where I can see my image on screen, but it gets stretched depending on the window size.

The issue looks like this:

I got the same general idea of drawing sprites in Direct3D9 and Direct2D working fine, because there I simply resize the RenderTarget or reinitialize the Device with a new BackBuffer.

How do I fix this, so that the sprite remains the same dimensions independent from window size?

I'm seeing two potential issues:

I don't know if and how I need to set the different Transforms to adjust for window size (I'd rather resize the backbuffer, and only transform sprites for positioning and scaling)
I suppose I need to update the backbuffer or do something in the form's resize event.

Here is my rendering code:

using DiscSim;
using SlimDX;
using SlimDX.Direct3D10;
using SlimDX.DXGI;
using System.Windows.Forms;
using System.Drawing;
using Device = SlimDX.Direct3D10.Device;
using Vector2 = SlimDX.Vector2;
using Resource = SlimDX.Direct3D10.Resource;

namespace DiscSimSlimDX
{
    class Camera_DX10 : Camera
    {
        private RenderTargetView renderTarget;
        private Device device;
        private SwapChain swapChain;
        private Sprite sprite;
        private SpriteInstance[] spriteInstances;

        public Camera_DX10(ISimulation simulation, Form form, string spritePath)
            : base(simulation, form, spritePath)
        {
            var swapChainDescription = new SwapChainDescription()
            {
                BufferCount = 1,
                ModeDescription = new ModeDescription(0, 0, new Rational(60, 1), Format.R8G8B8A8_UNorm),
                IsWindowed = true,
                OutputHandle = form.Handle,
                SampleDescription = new SampleDescription(1, 0),
                Flags = SwapChainFlags.AllowModeSwitch,
                SwapEffect = SwapEffect.Discard,
                Usage = Usage.RenderTargetOutput
            };

            Device.CreateWithSwapChain(null,
                DriverType.Hardware,
                DeviceCreationFlags.Debug,
                swapChainDescription,
                out device,
                out swapChain);

            using (var backBuffer = Resource.FromSwapChain<Texture2D>(swapChain, 0))
            {
                renderTarget = new RenderTargetView(device, backBuffer);
                RenderTargetViewDescription r = renderTarget.Description;
            }

            device.OutputMerger.SetTargets(renderTarget);
            device.Rasterizer.SetViewports(new Viewport(0, 0, form.ClientSize.Width, form.ClientSize.Height, 0, 1));

            device.OutputMerger.BlendState = BlendState.FromDescription(device,
                new BlendStateDescription()
                {
                    IsAlphaToCoverageEnabled = true,
                });

            sprite = new Sprite(device, 512 * 512); // How big should the buffer size be?
            sprite.ProjectionTransform = Matrix.Identity; // ?
            sprite.ViewTransform = Matrix.Identity; // ?

            ShaderResourceView texView = ShaderResourceView.FromFile(device, "Resources/World.png");
            var spriteInstance = new SpriteInstance(texView, Vector2.Zero, new Vector2(1, 1));
            spriteInstance.Transform = Matrix.Identity; // ?

            spriteInstances = new SpriteInstance[1] { spriteInstance };

            form.ResizeEnd += (s, e) =>
            {
                // How do I resize the backbuffer or what do I need to do
                // to adjust for the new window size?

            };
        }

        public override void Draw()
        {
            device.ClearRenderTargetView(renderTarget, Color.Black);
            sprite.Begin(SpriteFlags.None);
            sprite.DrawBuffered(spriteInstances);
            sprite.End();
            swapChain.Present(0, PresentFlags.None);
        }
    }
}


texts:
How can i get teamscore in code?in hl2mp_gamerules.cpp i found this:

        CTeam *pCombine = g_Teams[TEAM_COMBINE];
        CTeam *pRebels = g_Teams[TEAM_REBELS];

        if ( pCombine->GetScore() >= flFragLimit || pRebels->GetScore() >= flFragLimit )
        {

And here's how i modified in my .cpp file:

CTeam *pRebels = GetGlobalTeam( TEAM_REBELS );
CTeam *pCombine = GetGlobalTeam( TEAM_COMBINE );

CBasePlayer *pPlayer = UTIL_PlayerByIndex(engine->GetLocalPlayer());

  if(pCombine->GetScore() == 1)
  {
    vgui::surface()->DrawSetColor(GetFgColor());
    vgui::surface()->DrawSetTexture( m_nTeamBlue );
    vgui::surface()->DrawTexturedRect(0, 0, GetWide(), GetTall());
  }

But it says: pRebels, pCombine, cTeam are undeclared identifiers. How can i declare them? Or what .h file i need to include?


texts: Adding Functionality to a basic Java 2D Camera

texts:
Creating a little LoZ inspired game in Java here just to get into the feeling of things (learning CS at my school but the only teacher who's willing to help is travelling for 6-months, so I'm teaching myself in the meantime). Thing is, I've run into a little snag with the functionality of the "camera".

I've so far been able to successfully limit where the camera goes in terms of the level size (stopping the camera when it gets to top, bottom, left, and right edges of the level), and keep the camera centered on the player as he moves around the level. The issue I'm having is that once my camera stops moving, I can't figure out how to wait until the player is in the center of the screen again for the camera to move again.

So if my player starts out in the center of the map and then moves all the way to the top left, if I move down or right then my sprite isn't in the center of the camera anymore.

Anyone have any suggestions? And sorry if this blatantly obvious, I'm still new to game development.

Thanks. ^^


texts: How to use Graphics.DrawProcedural to render a quad over a scene?

texts:
I want to learn this so I could do some screen space particles in Unity. This is meant as a sort of "hello world" shader.

my current script is:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Runtime.InteropServices;

public class ParticleFX : MonoBehaviour
{

public int particlecount = 4;
private Material material;

void Start()
{
        material = new Material(Shader.Find("Hidden/CustomParticle"));
}

void OnRenderImage(RenderTexture source, RenderTexture destination)
{

    material.SetPass(0);
    Graphics.DrawProcedural(MeshTopology.Quads, particlecount, 1);

}

void OnDestroy()
{

}
}

And my shader looks like this:

Shader "Hidden/CustomParticle"
{
SubShader
{
    Pass
{
    CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#include "UnityCG.cginc"
#pragma target 3.5

    struct v2f {
    fixed4 color : TEXCOORD0;
    float4 pos : SV_POSITION;
};

v2f vert(
    uint vid : SV_VertexID // vertex ID, needs to be uint
)
{
    v2f o;
    o.pos = UnityObjectToClipPos(float3(vid>>1,vid&1,1));
    o.color = float4(1,0,0,1);
    return o;
}

fixed4 frag(v2f i) : SV_Target
{
    return i.color;
}
    ENDCG
  }
 }
}

I expect to see a red quad cover my scene, but I don't. The core part is learning to use Graphics.DrawProcedural().


texts: Per fragment lighting with OpenGL 4.x tessellated model

texts:
I'm experienced with OpenGL 3+. I'm dabbling with tessellation shaders and have now got to a point where I have a nicely tessellated teapot/plane demo (quick look here)

As can be seen from the screenshots, the lighting is broken (though admittedly doesn't look too bad in the image)

I've tried to add a normal map to the equation but it still doesn't come out right, I can calculate the normals, tangents and binormals per triangle in the geometry shader but still looks wrong.

I think the question would be; How do I add per fragment lighting to a tessellated model?

The teapot is 32 16-point patches, the plane is one single 16 point patch.

The shaders are here, but they are a complete mess, so I don't blame anyone who cant make sense of them. But peruse at your leisure if you like.

Also, if this question is more suited to be somewhere else i.e. Stack Overflow or the Programming stack please let me know.