texts: How to dynamically create an UI text Object in Unity 5?

texts:
I have been searching for something that should be simple, but Unity 5's documentation on that is fairly outdated. What I want to achieve is to be able to create UI Text totally from script, i.e. fully dynamically - in my real case application, I will do that in a loop of not pre defined number of iterations.

A search using Google will find quite many examples on how to do that, but all I saw either use methods that are already deprecated (are from before Unity version 5) or are simply wrong (no surprise here...). I already know that I should first add a Canvas to my project, then I should include using UnityEngine.UI in my C# code, and also that I could declare a UI Text like Text _guitext.

However, the code below does not work. I mean, it's not that it crashes, but rather that nothing is shown:

using UnityEngine;
using System.Collections;
using UnityEngine.UI;

public class MyClass: MonoBehaviour {

Text _guitext;

// Use this for initialization
void Start () {
    _guitext.text = "testing";
}

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

Worse than that, it seems that while game is played, no new object appears in the object hierarchy list.

Could you please point me out in the right direction here? Thanks.


texts: Import Quaternions from a different coordinate system to perform an animation (DirectX to 3ds/Maya)

texts:
I'm working on a tool to import a biped from a DirectX engine that uses Left-handed coordinate system to 3ds Max that uses a right-handed one.

I managed to achieve the initial positions of the biped by multiplying all the transformations matrices by this initial matrix (the initial positions are written in a 4x4 matrix):

[1,    0,           0          ]
[0,   -1.62921e-07, 1          ]
[0,    1,           1.62921e-07]
[0,    0,           0          ]

3ds uses the classic 4x4 matrix with the difference that it removes the last column, so this is pretty much the DirectX 4x4 matrix with the rotations and scale on the first 3 lows and the translation is in the last one.

I achieved this matrix by doing the following on maxscript:

rotation = (0, 0.707107, -0.707107, 0) //rotate 90 on x and 180 on z
scale = (1, 1, -1)

Everything is fine here until i try to apply quaternions on each keyframe, which half of the time imports the rotation fine, but backwards. I'm not sure how to express this properly so i will show an image of what happens:

In this example, the first frames are fine on the legs ( the arm is messed up in the same way but it's not as obvious)

And then the rotation of the leg is totally backwards in the next frames.

What i do to implement the animation is to apply to the TCB Rotation controller the quaternion locally. Sometimes the result is right, and sometimes the result isn't, and i'm not certainly sure why or how to fix it. I tried inversing them, and some operations that the max api gives me, but not of them seem to work. Conjugating the quaternion seems to give me some kind of better result (which is the current one), but still gives me flaws. The line of code is:

 in coordsys local anode.rotation.controller[node_layer_index].controller.value = conjugate arot

This applies the rotation using the conjugated version of the quaternion.

I attempted to do the exact same thing in Maya, which gave me a better result than the current one, but the problem is, that since i'm using euler and i don't seem to actually know how to process it properly, the interpolation is totally off, but the animation seems to be processde fine. I issued this problem in another question that ended up unanswered, if you think you can help me out in fixing it in maya, the question is here:
https://stackoverflow.com/questions/40581600/interpolation-between-two-keys-makes-are-off-after-python-importantion

I tried also to import the animation straight from the original axis, even if everything is flipped, but the problem remains, so it seems to be an issue of the way Max does the thing.

I would greatly appreciate any kinds of suggestions, or any way to fix this manually in the editor, even if it is in the curve editor, it does not have to be directly fixed on the script.


texts: How can I move and rotate an object in an “infinity” or “figure 8” trajectory?

texts:
I know that the easiest way to move an object with the figure 8 trajectory is:

x = cos(t);
y = sin(2*t) / 2;

but I just don't know how to rotate it, lets says with a new variable r as rotation, how do I merge it into the above formula ?
can anyone please advise me on what is the simplest and cheapest way/formula to move and rotate the figure 8 trajectory ?

ref:How can I move an object in an "infinity" or "figure 8" trajectory?


texts: How can I give the illusion of height to a ball in 2D?

texts:
In 2D top down soccer games, sometimes a ball is given the illusion of being in the air, like below:

How can I achieve this?


texts:
I want a way to make a lot of different units without having to program stuff like moveTo and Attack actions more than once

The way I see it, there are 2 ways I can do this.

A single generic Unit class with flags that specifies what it can/can't do (then create instances in a static array and grab them when needed)
Abstract unit class with abstract methods for Unit-specific actions like (Attack, Harvest, Patrol), which then all need to be implemented in the subclasses, even if the unit can't actually harvest anything.

the first way of doing this seems the simplest, but i would end up having a lot of code being unused for the majority of the units.

the second way could also work. But if i decide to have two different units that can harvest resources, i'm gonna have the exact same code in two different classes, which doesn't seem like the right way to do it.

Is this even the right approach to this problem?
In a game like AoE, every unit has, what i presume is, some kind of List of Actions/Orders, I would really like to know how to achieve something similar to that, where i can just code each Action/Order once, and then give it to all the units that need said Action.

If i'm unclear (highly plausible) or you need more information on what exactly i'm looking for, just ask me in a comment.


texts: How can I prevent seams from showing up on objects using lower mipmap levels?

texts:
Disclaimer: kindly right click on the images and open them separately so that they're at full size, as there are fine details which don't show up otherwise. Thank you.

I made a simple Blender model, it's a cylinder with the top cap removed:

I've exported the UVs:

Then imported them into Photoshop, and painted the inner area in yellow and the outer area in red. I made sure I cover well the UV lines:

I then save the image and load it as texture on the model in Blender. Actually, I just reload it as the image where the UVs are exported, and change the viewport view mode to textured. When I look at the mesh up-close, there's yellow everywhere, everything seems fine:

However, if I start zooming out, I start seeing red (literally and metaphorically) where the texture edges are:

And the more I zoom, the more I see it:

Same thing happends in Unity, though the effect seems less pronounced. Up close is fine and yellow:

Zoom out and you see red at the seams:

Now, obviously, for this simple example a workaround is to spread the yellow well outside the UV margins, and its fine from all distances. However this is an issue when you try making a complex texture that should tile seamlessly at the edges. In this situation I either make a few lines of pixels overlap (in which case it looks bad from upclose and ok from far away), or I leave them seamless and then I have those seams when seeing it from far away.

So my question is, is there something I'm missing, or some extra thing I must do to have my texture look seamless from all distances?


texts: How to modify the Unity sprite renderer (or create a custom one) that can display the sprites on the X-Z plane?

texts:
Prefix: I am NOT trying to rotate a sprite 90 degrees by it's transform, this changes what is up/down and forward/backwards for the object. I need the sprite displayed on the X-Z plane in comparison to the default X-Y plane in it's natural state in the game world with rotation transforms of 0.

I'm trying to use 2D sprites on the X-Z plane, how do I go about either modifying the built in sprite renderer to do this, or creating my own custom sprite renderer component?


texts: How to draw image in memory manually in pyglet?

texts:
In pyglet, I want to create an image buffer in memory, then set the bytes manually, then draw it. I tried making a 3x3 red square like this in my draw() function:

imageData = pyglet.image.ImageData(3, 3, 'RGB', [1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0 ])
imageData.blit(10, 10)

...but at runtime, Python complains:

ctypes.ArgumentError: argument 9: <type 'exceptions.TypeError'>: wrong type

Is this the right approach? Am I missing a step? How can I fix this?


texts: Making the player walk on walls in box2d

texts:
I'm making a game in stencil where players walk form left to right along randomly generated walls. I cant use waypoints, since the walls' shapes and positions are unpredictable.

Here's a descriptive sketch:

The red line is the player's path. The red circles are what I thought might make good waypoints until  I scrapped the idea.


texts: SpriteKit SKTileMapNode with Tileset Integration

texts:
SpriteKit supports tile maps as of iOS 10 and has a pretty powerful engine. Only, I am having trouble discovering if it is possible, and how to natively create, tile sets directly from a tileset image.

For example, it seems that many other tile map programs (such as Tiled) support uploading a single tileset image with a few inputs (16x16 tiles at 64px for each tile, for example) to create an array of tile textures. The only way that I've found to integrate this with Xcode's new SKTileSet feature is to manually crop each tile into it's own image, upload that image into a separate texture, and access them via name.

Is there a better way to upload a tile map image and access its tiles using Apple's SKTileMapNode engine?


texts: Can the unity networkmanager actually load scenes from streaming assets like loading a build-in scene?

texts: Can the build in networkmanager load a scene from the streaming assets folder and force all clients to do the same or do i have to load it manually on each client using some remote procedure? I cant find anything about that in the docs or on youtube.


texts: Unity3d - setting gameobject position by percentage of view

texts: I am having trouble finding a way to set a gameobject's position with regards to the screen size. I am building a 2d game that I will be putting on iPhone, iPad, and Android. I need to be able to set the object's position to a percent of the view.


texts: DRY 0-bandwidth-overhead-serialization in C#: virtual, delegates or reflection?

texts:
I'm (de)serializing some datastructures for a network-multiplayer game, and for each datastructure that's to be (de)serialized, I want to define the order of (de)serialization only once for maintainability without any additional bandwidth overhead, and as little performance cost and extra typing as possible.

I can use C#'s abstract class methods to achieve my goal, but there's several problems with doing so:

performance: adding an additional abstract method call to each (de)serialization operation isn't ideal
extra typing: I have to needlessly initialize all variables I'm deserializing because C# won't allow me to pass "ref" and "out" parameters interchangeably

How can I avoid duplicating the definition of a datastructure's (de)serialization while also avoiding some or all of the above issues, and continuing to avoid any additional bandwidth cost?

(ProtoBufs and BinaryFormatter both seem to use some additional bandwidth for metadata to describe the "payload" data, and XmlSerializer, DataContractSerializer and NetDataContractSerializer are all xml based and therefore more bandwidth intensive than a straight binary serialization. I also toyed with delegates and reflection, but this solution came to me most readily):

public struct ControllerSnapshot
{
    public Vector2 m_lStick;

    static private void Op(ref float lStickX, ref float lStickY, Op<float> op)
    {
        //define (de)serialization order here once and only once
        lStickX = op.Invoke(lStickX);
        lStickY = op.Invoke(lStickY);
    }
    public ControllerSnapshot(uLink.BitStream bitStream)
    {
        OpRead<float> opRead = new OpRead<float>(bitStream);
        float lStickX,lStickY;
        lStickX = lStickY = 0.0f;//2.can't use "out"; have to match Op's "ref" params
        Op(ref lStickX,ref lStickY,opRead);

        m_lStick = new Vector2(lStickX,lStickY);
    }
    public void Serialize(uLink.BitStream bitStream)
    {
        OpWrite<float> opWrite = new OpWrite<float>(bitStream);
        Op(ref m_lStick.x, ref m_lStick.y, opWrite);
    }
};

//in order to make the above work this needs to be defined:
abstract class Op<T>
{
    public Op(uLink.BitStream bitStream)
    {
        m_bitStream = bitStream;
    }
    abstract public T Invoke(T arg);

    protected uLink.BitStream m_bitStream;
}
class OpRead<T>:Op<T>
{
    public OpRead(uLink.BitStream bitStream) : base(bitStream) { }
    override public T Invoke(T arg)
    {
        return m_bitStream.Read<T>();
    }
}
class OpWrite<T>:Op<T>
{
    public OpWrite(uLink.BitStream bitStream) : base(bitStream) { }
    override public T Invoke(T arg)
    {
        m_bitStream.Write<T>(arg);
        return arg;
    }
}

//by contrast, the "obvious" code duplicates the order of (de)serialization, which I
//want to avoid, especially as (de)serialization becomes increasingly complex:
public ControllerSnapshot(uLink.BitStream bitStream)
{
    float lStickX,lStickY;
    lStickX = bitStream.Read<float>();
    lStickY = bitStream.Read<float>();

    m_lStick = new Vector2(lStickX,lStickY);
}
public void Serialize(uLink.BitStream bitStream)
{
    bitStream.Write<float>(m_lStick.x);
    bitStream.Write<float>(m_lStick.y);
}


texts: Box2d - Allow object to pass but still report collision

texts: I am creating a laser which is a dynamic body with its own collision filtering. I want it to not collide, as it does not currently but I want it to still report the collision or when the two overlap. Is such a thing possible?


texts:
I'm trying to learn DirectX via SharpDX, very new to this. What I want to do is be able to draw 2D shapes for a game I'm trying to make. So I started with the demo "MiniRect" that came with SharpDX. Since I want my game to be full-screen, I changed the RenderForm to be maximized (using WindowState) and set the FromBorderStyle to None.

I noticed that even if the form is set to maximized, it's size is always 800 by 600. In my renderloop, if I specify the location for the rectangle has 400 by 300, it is drawn in the middle of the screen. If I try to set the location via mouse-click (using the RenderForm's MouseClick event, there is always an offset present between where the mouse was clicked and where the drawing shows up.
My system DPI is set to the standard (96) so there shouldn't be any scaling. But it looks like there is a scaling factor of about 2.4

If it's not the DPI settings, does anyone have any idea what this be related to? The problem doesnt happen if the RenderForm is not maximized.
Is there another way to be drawing full-screen using SharpDX?

Thanks


texts: Make perfect constant game animation using javascript

texts:
I tried different ways to make constant animations using JavaScript and HTML. The problem is that they are never perfect.

If I want to move a square exactly 5 pixels every 50 miliseconds I would use that code:

var leftPosition = 0;

function move() {
    leftPosition += 5;
    document.getElementById("square").style.left = leftPosition + "px";
}

window.onload = function() {
    setInterval(move, 50);
};

What I mean by not perfect is that the square will sometimes move slightly faster or slower during it's course. To notice that you have to really pay attention to the moving animation.

I already tried to using requestAnimationFrame but happened the same thing. Is there a way to improve it?


texts: How do online games deal with lerp overshooting?

texts:
From what I understand, when you lerp in an online game, you travel from point a to b based on the elapsed time since the last update. The problem is when you have a higher latency, and you start receiving updates at inconsistent rates. So lets say I have variable t, variable t tracks the time since the last update and is only reset when a new update is received. The variable t is also responsible for moving the lerp like so:

lerp(a, b, t)

But when we receive updates at an inconsistent rate, t is reset inconsistently, so if there is any lag between the updates, t will keep incrementing, thus, the lerp will overshoot. How do online games deal with this?


texts: How to outline a 3D object with a cartoon style stroke?

texts:
How could I draw (stroke) the outline of a 3D object in a cartoon style with GLKit?

I'm referring to something like this:

However we can start with a simple line around the object and then try to improve the stroke with a shader.

I'm drawing the object with this code:

glBindVertexArrayOES(_vertexArray);
glDrawElements(GL_TRIANGLES, sizeof(Indices)/sizeof(Indices[0]), GL_UNSIGNED_BYTE, 0)

As I'm not very familial with GLKit: all the solutions I've found make use of OpenGL APIs not supported by OpenGL ES.


texts:
Is there any possibility to limit quaternions to move only in x & y axis (like in Eulers- yaw and pitch, without rolling)? I's there any equation or something similar to do this?
Some example:
Movement should behave like this: http://360.art.pl/experimental/1/
But when I build my player on quaternions it have no limits and I don't know how to fix it http://360.art.pl/experimental/2/


texts: I am new to Unity. I have a basic setup following Brackeys tutorial. When in game mode, I see the red cube having jagged edges. I tried increasing the antialiasing in Unity to 8x but it did not work. I also tried turning on antialiasing in my Nvidia control panel. But the issue still persists.


texts: Scaling textures with nearest neighbour without having to use seperate sprite batches

texts:
I'm interested in being to scale textures up via nearest neighbour. I can do this via a SpriteBatch.Draw() overload however this means that any other sprites drawn within that batch will also have the scaling.

What happens if I have 50 objects I want to to scale, and another 50 objects I don't want to be drawn using nearest neighbour. Assuming they alternate depths, that's 100 calls to to spriteBatch.End() in order to get depth drawn correctly. Now also let's say each object has it's own texture.

One way is to you use Texture2D.SetData() to manually scale up the textures but this could get messy, very quickly.

Any tips?


texts: Objects fall off screen, because stay one behind another[unity]

texts:
I m learning unity, I placed objects on a scene, camera is looking at them and displays them fine.

but in 3d, I can see they are one behind another, so when i hit play button, they just fall!

Pic:

is there any specific button like "align on one level" in unity?


texts: How to unpause a particular gameobject in unity?

texts: Say, I have a GUI Menu attached in a game scene. The game will be in pause state by default. I did it by setting "Time.timescale=0.0f"; I want my game to unpause only when Play button clicked. My question is how to access game scene from the script? And, what I to write on "OnClick" event? Your any suggestion will be highly appreciated. Regards


texts: MMO Client-Server Spoofing Vulnerabilities

texts:
Ive created a working authoritative client-server system using LiteNetLib for my game however im wondering if packet sniffing+modification is a real worry i should be developing for.

I read some information that other Client sniffing the packets of another client is pretty much impossible since the packets are routed through their ISP. Therefore: should i only worry about the client causing problems for the server, instead of also worrying about clients causing problems for other clients?

Currently im encrypting every packet sent by the client including movement commands such as 'move left'. My idea is that this will make packet-sniffing fail, packet-modification fail, and packet-spoofing fail.

If i remove my encryption doesn't that mean someone can spoof a packet by changing the packet source in the header? (thus sending game commands for another client - moving another player!). Usually when its encrypted i know that only the client with the secret key could have sent it, thus validating the packet source.

I see everyone saying that people shouldn't encrypt general traffic like this, but whats the truth here! Whats the best way?


texts: Chances of landing a job as a (AAA or medium sized studio) game programmer?

texts: How competitive are these jobs? If I am a fresh college graduate with a degree in CS and I have a portfolio that consists of one self-published and self-developed game with a little over 1k units sold, would that put me way ahead of the curve or no (let's assume for the sake of completeness that the game in question is quality enough to showcase and be proud of on an interview)?


texts: Why does rendering a gradiented shape leave gaps?

texts:
Sometimes when I am drawing objects that aren't 'linear' (e.g. rounded edges, circles, ellipses, diagonal lines, etc) I this weird effect of some pixels at certain points not getting drawn.

It's easier to show than explain: This image is created by the code below it. It's a block fading from blue to black. The same effect appears when only using one color. (Though it's otherwise obviously equivalent to just drawing a filled rectangle.)

float b = 100;
int steps = 100;
int thickness = 1;
int basex = 10;
int basey = 10;
int lenx = 200;
int leny = 200;
for(int idx = 0; idx < steps; idx++) {
    al_draw_rounded_rectangle(
            basex + thickness * (steps - idx), basey + thickness * (steps - idx),
            basex + lenx - thickness * (steps - idx), basey + leny - thickness * (steps - idx),
            RII, RII,
            al_map_rgba(0, 0, b - idx * (b / steps), alpha(0.0)),
            thickness);
}

Is there a term for this phenomenon? How do I prevent it from happening?


texts:
I recently came across the game turbo tunnel. I want to make a similar game.

only thing that stands in my way is the collision detection. I first thought of learning plane line collision detection. But I didn't understand that stuff as I am too small(11th grade). I know gluunproject that uses coordinates  on screen to world coordinates.

Things I thought about collision detection: -

getting a physics library. (But I am not sure how do I use bullet).
using box collision. (This solution may not work for irregular shaped doors) .
third method is given below:-

1) render the whole scene by plane's view.(no lightning, no textures)

2) get the depth buffer at pixel at centre of screen.

3) use gluUnproject for getting realworld coordinates of centre pixel. Let's say this point M.

4) if the distance between plane and M is less than certain value then aeroplane blasts off.

5) clear buffer bits and re render the scene with textures and lightning.

The third method is my idea. I am not sure if it is good to render the scene 2 times. But since only one object requires collision detection it may be a choice for me.

I am asking is using 3rd method to check for collision is good idea? if not So I should think something other.


texts: Which is the best format or best technique to compress images without loss of quality for iPhone/iPad games?


texts:
Hello i'm doing a game in WPF, 2D version (top view)

I have the map and i'm trying to check for color collision in pixel each time the timer is activated

Well...with 1 object it works fine but with more objects at same time it just slow down the process

This is my code every time the dispatchertimer activates and i loop to check for collision on every object

CroppedBitmap cb = new CroppedBitmap(source, new Int32Rect(x, y, 1, 1));
int px = 1 * (source.Format.BitsPerPixel / 8);
byte[] pixels = new byte[px * 1];
cb.CopyPixels(pixels, px, 0);
Color c = Color.FromArgb(pixels[3], pixels[2], pixels[1], pixels[0]);
if (c.R == 255 && c.B == 255 && c.G == 255) {
   pixels = null;
   return true;
}

Any help to simplify the process? I really want to do it in WPF

PS: The map is 1018x731


texts: Unity animation won't play on trigger. What do I do to fix it?

texts:
Ok so I added a play animation line to my trigger script. I made an animation, added it to the trigger object, attached the animation to the trigger, and tested. The target goes to the trigger as it should, deletes the trigger, but the animation never plays. So I check the console, and it's telling me "The AnimationClip 'MazeDoorClose' used by the Animation component 'SuckInTarget' must be marked as Legacy." so I do that, but now the trigger activates before the target gets there, and there is still no animation playing!

I know this sounds confusing so in an attempt to make it easier to understand I made a short video . Sorry for the crappy quality, but hey it's free.
Here is the code:

using UnityEngine;
using System.Collections;

public class SuckIn : MonoBehaviour
{

    public Transform target;
    public float speed;
    public string ObjectWithTagToBeDestroyed;
    public string ThingToAnimate;

    void Update()
    {
        float step = speed * Time.deltaTime;
        target.position = Vector3.MoveTowards(target.position, transform.position, step);
    }

    void OnTriggerEnter(Collider coll)
    {
        if (coll.gameObject.tag == "Ball")
        {
            Destroy(GameObject.FindWithTag(ObjectWithTagToBeDestroyed));
            GetComponent<Animation>().Play(ThingToAnimate);
        }
    }

}

Before you ask yes the animation is on the object as it should be, and as Unity told me to do I marked it as a legacy animation. Any ideas what  am doing wrong?


texts: UV mapping. Texture blurry and overlapping. Unity3d

texts:
In my voxel game, this is how I'm calculating UV coordinates for my cubes' faces:

public static Vector2[] faceUVs(Direction dir)
{

    Vector2[] sideUV = new Vector2[4]{
        new Vector2(0, 1),
        new Vector2(1f/3, 1),
        new Vector2(1f/3, 0),
        new Vector2(0, 0)
    };
    Vector2[] topUV = new Vector2[4]{
        new Vector2(1f/3, 0),
        new Vector2(1f/3, 1),
        new Vector2(2f/3, 1),
        new Vector2(2f/3, 0)
    };
    Vector2[] bottomUV = new Vector2[4]{
        new Vector2(2f/3, 0),
        new Vector2(2f/3, 1),
        new Vector2(1, 1),
        new Vector2(1, 0)
    };
    if ((int)dir == 4)
    {
        return topUV;
    }
    if ((int)dir == 5)
    {
        return bottomUV;
    }

    return sideUV;
}

Then depending on which face is being generated, I return appropriate UV coordinates for it.

This is the texture itself(pretty clean, each block is exactly 16 pixels wide and 16 pixels tall. Total length of picture is 48 pixels):

But the result is terrible(Faces are almost correctly aligned with appropriate texture part, but the annoying keyword here is "almost"):

As you can see, edges of side faces contain few pixels of what should have been the texture of top face.

I've set filter mode to point too.

If I instead use 16x16 pixel texture, for example only side, then I get good result:

I suspect the problem here could be floating point precision. In that case, how do i resolve this error?


texts:
This is mostly a general design theory question, but for reference the bulk of my game is in JavaScript.
I can draw images to the screen that layer on top of each other in the order that I please. One of the layers, I call it the light layer, is simply a series of black squares that change opacity based on the light levels in the game. During night, these black squares are almost opaque (unless a light source is affecting them) and during the day they are nearly invisible.
Glowing things, like bulbs or radar console screens, are drawn above the light layer to make it look as if they're exempt from the light effect. (Glowing)
However, the turret head is a non-glowing object that needs to appear above the glowing objects. For example, it might partially cover the radar console screen or light bulbs. However, it isn't meant to glow.
This is where the paradox occurs. The turret head needs to be below the light layer, but also above the glowing elements.
Any ideas of how I could solve such a paradox?


texts: I have created a terrain mesh in World Machine. When editing the mesh in Blender is it possible to select a vertex and adjust its coordinates using text entry? I need the height of each vertex to be an integer multiple of 24, and the horizontal distance between adjacent vertices to be integer multiples of 32. Using the mouse to drag things around is much too imprecise. Thanks.


texts: How can I avoid having many singletons in my game architecture?

texts:
I use cocos2d-x game engine for creating games. The engine already uses many singletons. If someone used it, then they should be familiar with some of them:

Director
SimpleAudioEngine
SpriteFrameCache
TextureCache
EventDispatcher (was)
ArmatureDataManager
FileUtils
UserDefault

and many more with overall about 16 classes. You can find a similar list on this page: Singleton objects in Cocos2d-html5 v3.0 But when I want to write I game I need much more singletons:

PlayerData (score, lives, ...)
PlayerProgress (passed levels, stars)
LevelData (parameters per levels and level packs)
SocialConnection (Facebook and Twitter login, share, friend list, ...)
GameData (you may obtain some data from server to configure the game)
IAP (for in purchases)
Ads (for showing ads)
Analytics (for collecting some analytics)
EntityComponentSystemManager (mananges entity creation and manipulation)
Box2dManager (manages the physics world)
.....

Why I think they should be singletons? Because I will need them in very different places in my game, and shared access would be very handy. In other words, I don't what to create them somewhere and pass pointers down to my all architecture as it will be very difficult. Also these are kind of things I need only one. In any case I will need several, I can use a Multiton pattern too. But the worst thing is that Singleton is the most heavily criticized pattern because of:

 - bad testability
 - no inheritance available
 - no lifetime control
 - no explicit dependency chain
 - global access (the same as global variables, actually)
 - ....

You can find some thoughts here: https://stackoverflow.com/questions/137975/what-is-so-bad-about-singletons and https://stackoverflow.com/questions/4074154/when-should-the-singleton-pattern-not-be-used-besides-the-obvious

So, I think, I am doing something wrong. I think my code smells. :) I wounder how more experienced game developers solve this architectural problem? I want to check, maybe it is still normal in game development to have more than 30 singletons, considered the ones that are already in game engine.

I have thought to use a Singleton-Facade which will have instances of all these classes I need, but each of them would not be singletons already. This will eliminate a lots of problems, and I would have only one singleton which would be the Facade itself. But in this case I will have another design problem. The Facade will become a GOD OBJECT. I think this smells too. So I can't find a good design solution for this situation. Please advice.


texts: Where can I find info on grid based algorithms for stateless AI?

texts:
There seems to be an overwhelming amount of info out there on AI of all kinds, and it's kind hard to digest at once.

For my testing purposes, I'm creating a "typical stateless AI", as described in this article, and now I need to implement the following functions for a 2D square based game board:

-(void)runAway;
-(void)attackPlayer;
-(void)moveTowardsPlayer;
-(void)tacticalMoveAwayFromPlayer;
-(void)waitOrStationaryAction;

For example, I can run my own run away function like this:

-(void)runAway
{
    DLog(@"runAway");
    [self debugMessage];

    int bestTileIndex = 0;
    int largestDistance = 0;
    int distance = 0;
    if(validMoves.count>0)
    {

        for(NSNumber* tileNumber in validMoves)
        {
            distance = [self distanceToTargetFromTile:tileNumber.intValue];
            if(distance >largestDistance)
            {
                largestDistance = distance;
                bestTileIndex = tileNumber.intValue;
            }
        }
    }
    //move to best tile

}

but this method only checks the distance from 1 target, which may not be the best if there are multiple enemies on the game board.

Where can I find good/efficient implementations of algorithms for searching a 2D grid for these functions? For example finding a point that is furthest away from multiple opponents and is accessible within a certain number of moves.

Other functions that come to mind is picking the best/weakest target, moving towards a specific target while accounting for variable terrain cost, etc

I'm certain someone has already done this before.


texts: How to tell if a fixture is being squeezed by two other fixtures in Box2D?

texts: Let's say I had a ground fixture, a player box, and a kinematic block moving up and down. If the player stands under the block, weird things happen. I want to simply play an event where the player dies. How can I detect when the player box is crushed by the block moving down on it?


texts: How to avoid material copying error message in Edit-mode?

texts:
I created a component called "AphaGroup" (an analog of the existing CanvasGroup for UI) which should be able to change alpha of the whole game object tree. My component finds all the MeshRenderer components, takes their material.color and changes its alpha. It should work both in play- & edit- modes. When it's run in edit-mode there is an error in the console when the material is copied for the first time:

  Instantiating material due to calling renderer.material during edit
  mode. This will leak materials into the scene. You most likely want to
  use renderer.sharedMaterial instead.

I've read most of the similar questions on the Internet but still haven't found the answer on how to manage this situation properly. How to avoid both: this error message and memory leaks?

I tried Renderer.material, Renderer.materials and Renderer.GetMaterials, but all they cause the same error.


texts: Remove sprite reference before build in Unity

texts:
All the the characters in my 2D game have SpriteRenderers to animate the characters.  Some of the characters are only active in their scenes sometimes, so I load their sprites asynchronously based on game state.
During edit mode, I have at least one sprite from an animation assigned to each sprite renderer so I can tell where the game object is.  The problem is that including even a single sprite will load up the entire sprite atlas at runtime if I allow the SpriteRenderer.sprite to be set.
Is there an efficient way to unset the SpriteRenderer.sprite for a build, but not during edit time?  Is there a better way to handle this?


texts:
Hi!

Would someone answer my question, please?
Does the title's method create the same components always or verify possible duplicates?

For exaple:
I have one D3D12_INPUT_LAYOUT_DESC struct and two shaders need the same IL.
How many ILs will it create? (In the D3D11 one was enough).
Is it possible to avoid duplicates?

I highly appreciate the answer.


texts:
I've been trying to get this working for ages now, I can detect if there's a solid block at any place on the map and I can check how far something is inside of it, but I don't understand how to fix the collision.  I've tried loads of ways and all of them end up by the player getting stuck, glitching around, incorrect responses and I really have no idea how to go about this :/.

       int Chnk = Utility.GetChunkFromPosition(origin);
        if (Chnk == -1)
            return;

        Vector3 Pos = Utility.GetCubeVectorFromPosition(origin);

        if (GlobalWorld.LoadedChunks[Chnk].Blocks[(byte)Pos.X, (byte)Pos.Y, (byte)Pos.Z] != 0)
        {
            isInIllegalState = true;
            if (velocity.Y < 0f)
                velocity.Y = 0f;
        }

        while (isInIllegalState)
        {
            if (GlobalWorld.LoadedChunks[Chnk].Blocks[(byte)Pos.X, (byte)origin.Y, (byte)Pos.Z] != 0)
                origin.Y = (int)(origin.Y + 1);
            else isInIllegalState = false;
        }

        if (origin.Y < Chunk.YSize - 2 && GlobalWorld.LoadedChunks[Chnk].Blocks[(byte)Pos.X, (byte)(origin.Y + playerHeight.Y), (byte)Pos.Z] != 0)
        {
            velocity.Y = 0f;

            //Acceleration.Y = 0f;

            origin.Y = (int)origin.Y;// -0.5f;
        }

        for (int x = -1; x <= 1; x+=2)
        {
            for (int z = -1; z <= 1; z += 2)
            {
                Vector3 CornerPosition = new Vector3(boundingSize * x, 0, boundingSize * z);
                bool CorrectX = false;
                bool CorrectZ = false;

                Vector3 RoundedOrigin = Utility.RoundVector(origin);
                Vector3 RoundedCorner = Utility.RoundVector(origin + CornerPosition);

                byte BlockAdjacent = Utility.GetCubeFromPosition(origin + CornerPosition);

                if (BlockAdjacent == 0)
                    continue;

                if (RoundedCorner.X != RoundedOrigin.X && RoundedCorner.Z != RoundedOrigin.Z)
                {
                    CorrectX = true;
                    CorrectZ = true;
                }

                if (RoundedCorner.Z != RoundedOrigin.Z && RoundedCorner.X == RoundedOrigin.X)
                    CorrectZ = true;
                if (RoundedCorner.X != RoundedOrigin.X && RoundedCorner.Z == RoundedOrigin.Z)
                    CorrectX = true;

                if (CorrectX && CornerPosition.X > 0)
                {
                    if (origin.X > 0f)
                        origin.X = (int)(origin.X + 1) - boundingSize;
                    else origin.X = (int)origin.X - boundingSize;
                }
                else if (CorrectX && CornerPosition.X < 0)
                {
                    if (origin.X > 0f)
                        origin.X = (int)(origin.X) + boundingSize;
                    else origin.X = (int)(origin.X - 1) + boundingSize;
                }

                if (CorrectZ && CornerPosition.Z > 0)
                {
                    if (origin.Z > 0f)
                        origin.Z = (int)(origin.Z + 1) - boundingSize;
                    else origin.Z = (int)origin.Z - boundingSize;
                }
                else if (CorrectZ && CornerPosition.Z < 0)
                {
                    if (origin.Z > 0f)
                        origin.Z = (int)(origin.Z) + boundingSize;
                    else origin.Z = (int)(origin.Z - 1) + boundingSize;
                }
            }
        }


texts: How can I apply Perlin noise to generating an asteroid from cubic voxels?

texts:
I know I can use Perlin noise to generate randomised terrains, but for my current project i want to generate random asteroids of non-uniform length, width depth etc.

My first thought was to apply Perlin noise to a sphere, but i do not know how i would apply this with cubes space in a grid nor did i know whether it would make the asteroids appear random enough, my current assumption was they would all be relatively spherical still.

Is Perlin noise still the best method to be using for terrain not on a single plane?


texts: SDL_RenderPresent is writing over the previous frame

texts:
Whenever I call SDL_RenderPresent, the previous frame is replaced with black before the new frame is displayed. It's almost like when I call SDL_RenderPresent(renderer), it automatically calls SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255) and thenSDL_RenderClear(renderer).

I want to keep the previous frame because only 100 pixels are changed per frame. How do I prevent it from writing over the previous frame?

Here's an example:

// Error checking removed for clarity
SDL_Init(SDL_INIT_VIDEO);
SDL_Window* window = SDL_CreateWindow("title", 0, 0, width, height, SDL_WINDOW_SHOWN);
SDL_Renderer* renderer = SDL_CreateRenderer(window, -1, 0);

// after some other, non-SDL related stuff, I run this code:
SDL_Rect a = {
    .x = 0,
    .y = 0,
    .w = 100,
    .h = 100
};
SDL_Rect b = {
    .x = 200,
    .y = 0,
    .w = 100,
    .h = 100
};

SDL_SetRenderDrawColor(renderer, 0xFF, 0xFF, 0xFF, 0x00);
SDL_RenderClear(renderer);

SDL_SetRenderDrawColor(renderer, 0xFF, 0x00, 0x00, 0xFF);
SDL_RenderDrawRect(renderer, &a);
SDL_RenderPresent(renderer);
// A red outline of a square is displayed on a white background
SDL_Delay(2500);

SDL_SetRenderDrawColor(renderer, 0x00, 0xFF, 0x00, 0xFF);
SDL_RenderDrawRect(renderer, &b);
SDL_RenderPresent(renderer);
// A green outline of a square is displayed on a black background.
// The red outline is gone.
SDL_Delay(2500);

How do I prevent SDL_RenderPresent from painting over the previous frame with black? Why is it doing that even though I'm not telling it to clear between the presents?


texts:
I need an advice on creating a slot machine phaser game.
So it looks like this

I need to plan an approach to do the animation of the reels of the slot machine. I have idea of using tileSprite, are there any other ideas of implementing this game?


texts:
I am trying to use my PS3 Controller with Unity but it has been unsuccessful.

I followed this video to do so:
https://www.youtube.com/watch?v=LcettC1QHu4

I have done the same thing as the video but for some reason unity is not getting ANY input from the controller.

I have tested the controller with another commercial game on my Mac and it works perfectly, so my controller is well connect to my computer.

here is a screenshot of the input manager:

joystick button 0 is the X button


texts: How can I simulate light using mask images on the iPad?

texts:
Possible Duplicate:
  Can I achieve a torchlight effect (lighter area around a light source) in a 2D game?

I want to have a picture as a background, say this:

Then I would like to apply a mask, just a circle with blurred edges, so it looks like this:

The idea is to simulate something emitting. Is this a good way of simulating light or should I use another method? And if so how? And I'm not really sure how to apply this method.


texts: How can I use a data grid to make an isometric turn based game in GameMaker?

texts:
I am making a Hero Quest clone. It is a turn based adventure game with an isometric view point. So far I have been able to turn a 2D map into an isometric view but I believe I need to use a data grid to achieve turn based movement, combat etc.

There are plenty of tutorials on data grids but none that I can find on how to translate a 2D grid to a psedo-3D isometric game.

How could I do it?


texts: Why flip sprites instead of creating extra assets?

texts: Why is the preferred method for changing the direction a character is looking in a 2D game a sprite flip? Why not just create the extra asset and show that one on screen?


texts: C# Unity - Multiplying Colors in loop results in wrong results

texts:
Good day, I'm trying to generate a tilemap, my current setup is a base tileset, and a few overlays for the different biomes / terrain heights. In my code, I generate each biome's tileset, based off of the base tileset, multiplied by the biome's overlay. However, as you can see in he image, it's reusing the first biome's overlay for all biomes.

Preview of result

Base Tileset

Overlays

Here's my code:

        for (int i = 0; i < biomes.Length; i++)
        {
            StatusText.text = "Generating Biome["+i+"] Tileset...";
            biomes[i].TileSet = new Sprite[_tileSet.Length]; // Creates the sprite array for the tileset of biome [i].
            Color[] b = biomes[i].Overlay.texture.GetPixels(); // Gets biome[i] overlay in a color array.
            for (int x = 0; x < _tileSet.Length; x++)
            {
                Debug.Log(biomes[i].Name);
                Debug.Log(biomes[i].Overlay);
                Color[] a = _tileSet[x].GetPixels(); // Get's base tile [x] in tileset pixels.
                for (int j = 0; j < a.Length; j++)
                {
                    a[j] *= b[j]; // Multiplies each pixel of the copy of base tile in the new color array with the overlay of biome[i].
                }
                Texture2D tex = new Texture2D(8, 8);
                tex.SetPixels(a);
                tex.filterMode = FilterMode.Point;
                tex.Apply();

                biomes[i].TileSet[x] = Sprite.Create(tex, new Rect(0, 0, 8, 8), new Vector2(4, 4), 8); // Creates sprite from generated texture.
            }
        }


texts:
I'm trying to convert a AS3 game to C# / XNA and I'm looking for a way to animate a sprite.

More precisely, I want the sprite to rotate and scale a bit, then return to its starting position.

In AS3 I just use a tweening library and add a touch listener to the sprite, but I haven't been able to find something like this for XNA. How would you do something like that in C#?
Thanks in advance!


texts: I am using unity and I would like to create characters that have interchangeable spells. As an example it would be something like Pokemon that can attain different skills as they level up and the user can change out skills for new ones. Would this be a good place for inheritance? Should I make a parent class that inherited by all of the other characters? Would this be the best approach?


texts: Time based movement Vs Frame rate based movement?

texts:
I'm new to Game programmming and SDL, and I have been following Lazyfoo's SDL tutorials. My question is related to time based motion and frame rate based motion, basically which is better or appropriate depending on situations?. Could you give me an example where each of these methods are used?.

Another question I have is that, in lazyfoo's two Motion tutorials (FPS based and time based) The time based method showed a much smoother animation while the Frame rate based one was a little hiccupy, meaning you could clearly see the gap between the previous location of the dot and its current position when you compare the two programs.

As beginner which method should I stick to?(all I want is smooth animations).


texts: For voxel rendering, what is more efficient: pre-made VBO or a geometry shader?

texts:
Given a fairly static voxel array, what is more efficient: using the CPU to pre-generate a VBO to render the voxel faces (ignoring more advanced forms of rendering like marching cubes for now) or using a geometry shader on the GPU to generate the faces on the fly?

I'm not that worried about updating changing voxels but of course that is a benefit of the GPU-version since you don't have to rebuild the VBOs. Also, the GS approach feels a bit more modern :)

On the other hand, I haven't looked at the details on how a GS actually works with the rasterization pipeline in modern GPUs. Does it output the vertices into a sort of stream-cache or is the vertices written to the normal GPU memory in between? If it's the latter, then on-the-fly generating could reduce the available bandwidth and processing power from the rest of the GPU tasks I guess and then it would be more beneficial to do it on the CPU..


texts: How to begin serious game development (in C++)

texts:
I would like to start developing games. I have tried before Game Maker 8, which was a very easy way to start creating games, if you were new in game development. Then, I tried Unity 3D, which was a much more serious and complete tool to create computer-games, and required some experience. And now, I would like to start creating games, and don't use any special environment or developer, but just code (in C++ preferably). So, here is my question: from where should I begin, if I would like to start programming games? Thanks in advance.

Note: I work in ubuntu 10.04, I can also use windows 7, but I prefer ubuntu.


texts: In Physijs, how do I detect that an object is still?

texts: I have a cylinder that simulates a flipping coin. I am using Physijs. The coin might bounce off the surface multiple times before stopping. How can I know when the coin has completely stopped moving?


texts: How should I organize my matrices in a 3D game engine?

texts:
I'm working with a group of people from around the world to create a game engine (and hopefully a game with it) within the next upcoming years. My first task is to write a camera class for the engine to use in order to add cameras to the scene, with position and follow points.

The problem I have is with using matrices for transformations in the class, should I keep matrices separate to each class? Such as have the model matrix in the model class, camera matrix in the camera class, or have all matrices placed in one class/chuck?  I could see pros and cons for each method, but I wanted to hear some input form a more professional standpoint.


texts: How do I write a simple 2-player server?

texts:
I've recently started learning JavaScript and HTML and developed simple 2-player game such as tick-tack-toe, battleship, and dots & boxes. However, these 2P games can only be played on one computer (i.e. the 2 players must sit together).

I want them to be able to play with a friend on a different computer.

Would anyone have a general, simple working example of a web-game server?


texts:
I am a 4th-year student in the apply math department. It's my final year, so I am working on my bachelor's thesis. The topic is "Real-time weather effects simulation for grassland". The huge work was done by my tutor, so the grassland simulation itself had been already implemented. Now we decided to limit the work to adding 3d wind modal and snowfall for result presentation. The snow particle system has been implemented recently, however, I've coped with problems while seeking information on how to implement real-time 3d wind field simulation.
There are plenty of quite complex articles on how to simplify real turbulence simulation, but it's too excessive for my work. On the other hand, there are quite simple 2D approaches using Perlin Noise, but I can't find something like that for the 3-dimensional scene.
Summing up, Could someone share some typical solution for my issue, or just post a good link?
Thank's a lot in advance and sorry for my poor English.
UPD Screenshot of the scene for whatever it may be worth


texts: Techniques for building out a game idea and mechanics

texts:
I've been finding that many of my projects fall into the abyss of my "game mechanic tests". That is, they aren't really "games", but rather sandboxes where I try out various things and find some mechanics that would be fun.

Now, I'd like to actually create a game out of some these ideas. Since so many of my "games" end up turning into additional sandboxes when I get distracted by a new idea("whoa, that's cool", and suddenly the whole game completely changes.. twenty times.. sometimes back and forth between several competing ideas), I'd like to actually plan out the mechanics, how they will fit together, and altogether how the game will work as a whole, even though I know I still need to be semi-flexible for when things play-test differently than expected.

This is compared to my usual strategy of, "Let's just get started and then I will build a game out of whatever I create" mindset.

What techniques are used for planning out a game idea (even if just roughly), before actually just jumping in? Is there specific software which helps? How do I go about managing the planning phase in general and keeping things up-to-date if things start to change?

See this great answer on a separate question for the type of actual design I would like to work on for my game, opposed to the programming focus I generally approach things with.


texts: Are we supposed to be creating player prefab?

texts:
This may seem like a dumb question, but I want a single player object for the entirety of my game. However when I load multiple levels obviously I need to reload the player so I would create a player prefab and instantiate him. However, it seems counterintuitive as prefabs are for objects you want to create multiple instances of easily, correct?
Also, I need values to be carried over accross levels for my player object therefore I guess I would need a static global singleton to store the player objects.

Hence the dilemna and confusion! Can anyone help me out here?


texts:
I am trying to create doodle jump like game with object pool for platforms. I have created an empty object with box 2D collider attached to it. This object moves with player and should be gathering platforms which exit its collider, but it isn't.

public class PoolGrabber : MonoBehaviour {

[Tooltip("Field for game manager.")]
[SerializeField]
private GameObject gameManager;

private void Awake()
{
    gameManager = GameObject.FindGameObjectWithTag("GameManager");
}

private void OnTriggerExit2D(Collider2D collision)
{
    if(collision.tag == "PooledObject")
    {
        collision.gameObject.SetActive(false);
        gameManager.GetComponent<LevelGenerator>().objectPool.Add(collision.gameObject);
    }
}

It also doesn't work with OnTriggerEnter2D.

I have also tried

private void OnBecameInvisible()
{
    gameObject.SetActive(false);
}

on a platform. Doesnt work either.

I have discovered that for all those methods above object required to has Rigidbody2D component. But what if I don't want any phisycs calculations to be handled. I don't need physics on those platforms at all. Also, an object doesn't become invisible if you see it in the editor window. Isn't very convenient.


texts: Board game: Move entity direction based on position and angle

texts:
I have a board game where you have entities on a tiled map and you can only move forward, left, and right. Each tile represents a position of the entity, and based on the entity's angle and position, I need to make a method that processes the move. For example if the entity has decided to move left, my function needs to perform a left movement.

An example:

My ship is currently on the tile where the arrow starts and the entity selected to move left, the arrow represents how the entity should move, with a motion.

So it slowly goes up and then slowly starts to go left and changing its rotation.

My question is, how can I make such a function which will know the entity's position, current angle (rotation), and where it should move to, and then with these parameters, it will process the movement animation motion to the target tile?

I am trying to solve this for a long time now, but no luck.
Thank you a lot!


texts: Derive direction in which a spot light emites its light from a projection matrix

texts:
First of all, sorry if my question sounds too basic or even makes no sense. I'm new with game development

I'm working with HPL1Engine, specifically, the lights parts. I need to know the direction in which a spot light emits its light. But the class that represents a spot light, doesn't have any direction vector.

So, I've been reading about lights in 3D engines, and I've detected in the class some other properties that I consider important. Like a projection matrix and angles (FOV and aspect). I'm trying to focus on the projection matrix (here, how the engine calculates it), but I'm not sure if I'm wasting my time.

Again, my goal is to know the direction in which a spot light emits its light (a vector), but I just have this matrix, and many other properties I don't relate with the spot direction calculation.

How could I know this direction from which I have (what the class provides me)?

Many thanks in advance.


texts: How to create rotating mode selection knob on multimeter

texts:
I want to create something looks similar to this for electrical and electronic troubleshooting simulationw.
I need to know how to program the drag interaction that and rotates the knob to select the mode of operation.
I checked several videos including this one, but this is not what I'm looking for. I am hoping to drag and rotate the knob in a circle.
I also need to know how to set the operating mode based on rotation. For instance, if the knob is pointing at 0-5 degrees (after drag and release), the knob position is set to 0, and the device is in off mode; if it is at 85-95 degrees then angle=90 degrees, and the device is set to resistance measurement mode.


texts: Correctly get size from Canvas UI element on Unity

texts:
Normally when anchors are on the same position, we can use .sizeDelta or .rect.width/height from RectTransform, but if the anchor are stretched, both of them returns negative values:

Which in reality is not 5 in size at all:

There are already SetSizeWithCurrentAnchor but how to get other's RectTransform's absolute size?


texts: With an iPhone game, can I allow music from other apps to play while my game is being played?

texts: My game doesn't have any music but it does have sound effects. Right now if I power up Pandora and then start a song and then switch to my game it will stop the Pandora song. Is there a special way I need to play my sound fx so that the music from Pandora will keep playing while my game is running?


texts: How to optimize a cubes made world game?

texts:
I'm making a cube-world-game like Minecraft. And to render it I've splitted it in 16x16x16 blocks regions (also known as chunks in mc) and then, on rendering, I take all the chunks in the rendering distance area and foreach of them I iterate all blocks and draw them.

It's so slow.

Then I tryed to remove hidden blocks and draw only visible faces of blocks. I made a VBO that store a face and then using model matrix I rotate it to make the other sides of the block. Finally I added a camera frustum test that checks if the block is visible from the camera.

I didn't code yet all these things, that's just a reasoning.

Are these optimization good or could I add something else?

P.S: I've seen that minecraft use a "display list" foreach chunk and not use a VBO for a face (I've didn't understand the code well since part of it is obfuscated) and each loop get just the rendering distance chunks and draw them using the display list stored. How's possible making a display list with all the shape of the chunk? There's another thing that does the same thing of the display list but it's not deprecated (I though VBO but I'm not sure)?


texts: 'Edit Collider' exits after every adjustment

texts:
When I click the Edit Collider button I can see the collider's region and the handles to adjust it.

After every adjustment (with the mouse) the collider outline disappears as Edit Collider finishes.  It's frustrating to use, having to reclick Edit Collider after every drag/click.

How do I stop Edit Collider mode from exiting after every change and only exit if I click the button, or press some commit key?


texts:
I am new to DirectX development and I am wondering if I am taking the wrong route to achieve the following:

I would like to mix three textures which contain transparent areas and some solid areas (Red, Blue, Green). The three textures should blend like shown in this example:

How can I achieve that in DirectX (preferably in directx9)?

A link or example code would be nice.

Update:

My rendering method looks like this and I still think I am doing it wrong, because the sprite only shows the last texture (nothing is rendered transparent or blended):

void D3DTester::render()
{
d3ddevice->Clear(0, NULL, D3DCLEAR_TARGET, D3DCOLOR_XRGB(0,0,0), 1.0f, 0);
d3ddevice->BeginScene();

d3ddevice->SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE);
d3ddevice->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_ONE);
d3ddevice->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_ONE);

LPD3DXSPRITE sprite=NULL;
HRESULT hres = D3DXCreateSprite(d3ddevice, &sprite);
if(hres != S_OK)
{
    throw std::exception();
}

sprite->Begin(D3DXSPRITE_ALPHABLEND);

std::vector<LPDIRECT3DTEXTURE9>::iterator it;
for ( it=textures.begin() ; it < textures.end(); it++ )
{
    sprite->Draw(*it, NULL, NULL, NULL, 0xFFFFFFFF);
}

sprite->End();

d3ddevice->EndScene();
d3ddevice->Present(NULL, NULL, NULL, NULL);
}

The resulting image looks like this:

But I need it to look like this instead:

Update2:
I figured out that I have to SetRenderState after I use sprite->Begin(D3DXSPRITE_ALPHABLEND); thanks to the hint by Josh Petrie. However, by using this:

    sprite->Begin(D3DXSPRITE_ALPHABLEND);

d3ddevice->SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE);
d3ddevice->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_ONE);
d3ddevice->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_ONE);

std::vector<LPDIRECT3DTEXTURE9>::iterator it;
for ( it=textures.begin() ; it < textures.end(); it++ )
{
    sprite->Draw(*it, NULL, NULL, NULL, 0xFFFFFFFF);
}
sprite->End();

The sprites colors are becoming transparent towards the background scene e.g.:
if I use d3ddevice->Clear(0, NULL, D3DCLEAR_TARGET, D3DCOLOR_XRGB(0,100,21), 1.0f, 0); the result looks like:

Is there any way to avoid that?
I would like the sprites be transparent to each other but to be still solid to the background.

Update3:
After having sombody explained to me, how to do what @LaurentCouvidou and @JoshPetrie suggested, I have a working solution and therfore accept the answer:

d3ddevice->BeginScene();

D3DCOLOR white = D3DCOLOR_RGBA((UINT)255, (UINT)255, (UINT)255, 255);
D3DCOLOR black = D3DCOLOR_RGBA((UINT)0, (UINT)0, (UINT)0, 255);

sprite->Begin(D3DXSPRITE_ALPHABLEND);
sprite->Draw(pTextureRed, NULL, NULL, NULL, black);
sprite->Draw(pTextureGreen, NULL, NULL, NULL, black);
sprite->Draw(pTextureBlue, NULL, NULL, NULL, black);
sprite->End();

sprite->Begin(D3DXSPRITE_ALPHABLEND);
d3ddevice->SetRenderState(D3DRS_ALPHATESTENABLE, TRUE);
d3ddevice->SetRenderState(D3DRS_BLENDOP, D3DBLENDOP_ADD);
d3ddevice->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_ONE);
d3ddevice->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_ONE);
sprite->Draw(pTextureRed, NULL, NULL, NULL, white);
sprite->Draw(pTextureGreen, NULL, NULL, NULL, white);
sprite->Draw(pTextureBlue, NULL, NULL, NULL, white);
sprite->End();

d3ddevice->EndScene();
d3ddevice->Present(NULL, NULL, NULL, NULL);

Update:
since this question is rather popular, I'd like to point out a website where you can experiment with opengl blendmodes:


texts: Objects don't instantiate at mouse position

texts:
I'm trying to get the player to shoot a projectile at the mouse position, however the projectile is shot in weird directions (http://gfycat.com/BothFluidHoneyeater).

Here is relevant part of my code:

var shotSpeed = 1000;
var projectile : Rigidbody;

function Update () {
    var clone : Rigidbody;
    if(Input.GetKeyDown(KeyCode.Mouse0)){
        clone = Instantiate(projectile, transform.position, transform.rotation);
    }
    clone.rigidbody.AddForce(Vector3.forward * shotSpeed);
}

What am I doing wrong?


texts: SharpDX / DirectX: How to render text to a transparent BitmapRenderTarget?

texts:
I'm trying to render text to a BitmapRenderTarget, cleared with transparent color.

My TextBox is drawn on its own SharpDX.Direct2D1.BitmapRenderTarget, which I create in this way:

var bitmapRenderTarget = new SharpDX.Direct2D1.BitmapRenderTarget(renderTarget,
    SharpDX.Direct2D1.CompatibleRenderTargetOptions.None, null, null, null);

As you can see, I don't change the pixel format of BitmapRenderTarget. The pixel format of underlying SharpDX.Direct2D1.RenderTarget, on which I draw my TextBox through DrawBitmap method, is defined in the following code:

renderTargetProperties = new SharpDX.Direct2D1.RenderTargetProperties()
{
    PixelFormat = new SharpDX.Direct2D1.PixelFormat(SharpDX.DXGI.Format.Unknown,
    SharpDX.Direct2D1.AlphaMode.Premultiplied)
};

Here is the code, that produces visual results:

// In the case 1: opaque white background
bitmapRenderTarget.Clear(SharpDX.Color.White);
...

// In the case 2: white background with 50% transparency
bitmapRenderTarget.Clear(new SharpDX.Color4(1f, 1f, 1f, 0.5f));
...

// In the case 3: fully transparent background
bitmapRenderTarget.Clear(SharpDX.Color.Transparent);
...

// The color of textBrush in all these cases is the same solid Black.
bitmapRenderTarget.DrawTextLayout(vector, textLayout, textBrush, ...);

The results:

As you can see, alpha value of the text color is somehow bound to the one in the clear color. The black line around the text is cursor, and it is drawn as it should.

How to fix this issue?


texts:
Right now im working on my c++ game, and im having alot of trouble using GLM and Bullet Physics to create my world correctly.

The main problem is that when i export my physics with Blenderv2.57, and export my models for GLM, the models never line up with the physics correctly...

Im wondering if there are any model loaders that would be good to use with Bullet Physics, and I can export the vertices,texture coords, etc. from Blender to be loaded and used as btTriangleMeshes..

I managed to make a btBvhTriangleMesh with my GLM model, but I think its falling, or my character is not picking it up correctly..

heres the code:

void BulletifyContinent(GLMmodel* mesh,float x,float y,float z,float scale)
{
    btTriangleMesh* trimesh = new btTriangleMesh();
    for(int t=0;t<mesh->numtriangles;++t)
    {
        GLuint index0 =3*mesh->triangles[t].vindices[0];
        GLuint index1 =3*mesh->triangles[t].vindices[1];
        GLuint index2 =3*mesh->triangles[t].vindices[2];

        GLfloat* p0 = &mesh->vertices[index0];
        GLfloat* p1 = &mesh->vertices[index1];
        GLfloat* p2 = &mesh->vertices[index2];

        btVector3* v0 = new btVector3( p0[0], p0[1], p0[2] );
        btVector3* v1 = new btVector3( p1[0], p1[1], p1[2] );
        btVector3* v2 = new btVector3( p2[0], p2[1], p2[2] );
        *v0 *= scale;
        *v1 *= scale;
        *v2 *= scale;
        trimesh->addTriangle( *v0, *v1, *v2 );
        ///trimesh->addTriangle(mesh->triangles[t].vindices[0]*100,mesh->triangles[t].vindices[1]*100,mesh->triangles[t].vindices[2]*100);
    }
    btCollisionShape* shape = 0;
    bool useQuantization = true;
    shape = new btBvhTriangleMeshShape(trimesh,useQuantization);
    btDefaultMotionState *StillStateMOT = new btDefaultMotionState(btTransform(btQuaternion(0,0,0,0),btVector3(x,y,z)));
    btScalar Mass = 1;
    btVector3 FallInertia(0,0,0);
    btRigidBody::btRigidBodyConstructionInfo StillRigidCI(Mass,StillStateMOT,shape,FallInertia);
    btRigidBody *ContiRigid = new btRigidBody(StillRigidCI);
    PhysicsWorld->addRigidBody(ContiRigid);

Edit 1:

btScalar Mass = 1;
btVector3 FallInertia(0,0,0);
// This line is missing in your code
shape->calculateLocalInertia(Mass, FallInertia);
btRigidBody::btRigidBodyConstructionInfo StillRigidCI(Mass,StillStateMOT,shape,FallInertia);
btRigidBody *ContiRigid = new btRigidBody(StillRigidCI);
PhysicsWorld->addRigidBody(ContiRigid);

Edit 2:

There is no need to create the bullet vertices on the heap with new:

btVector3 v0( p0[0], p0[1], p0[2] );
btVector3 v1( p1[0], p1[1], p1[2] );
btVector3 v2( p2[0], p2[1], p2[2] );
v0 *= scale;
v1 *= scale;
v2 *= scale;
trimesh->addTriangle( v0, v1, v2 );

Edit 3:

This is not a proper identity quaternion:

btDefaultMotionState(btTransform(btQuaternion(0,0,0,0),btVector3(x,y,z)));

either do it this way:

btTransform trans;
trans.setIdentity();
trans.setOrigin(btVector3(x,y,z));
btDefaultMotionState *StillStateMOT = new btDefaultMotionState(trans);

or by passing a proper identity quaternion either yourself:

btDefaultMotionState *StillStateMOT =
    new btDefaultMotionState(btTransform(btQuaternion(0,0,0,1),btVector3(x,y,z)));

or using quaternion's identity member function:

btDefaultMotionState *StillStateMOT =
    new btDefaultMotionState(btTransform(btQuaternion::getIdentity(),btVector3(x,y,z)));


texts: Minecraft Bukkit Rename world and use in Java Plugin

texts:
I run a Minecraft server (Bukkit 1.7.9) and would like to have a second overworld-like world, into which I can teleport players from my plugin.
I did some testing with the "world" folder:

tried to simply rename the folder, but then a new world is generated on server start (into folder "world")
moved another world with different folder name into the server directory (in addition the original world folder)
tried to change the "level-name" value in server.properties but that does just generate new nether and end folders containing the new name

But in all cases the additional world is not listed when

Bukkit.getWorlds()

is called from the plugin (of course I restarted the server after adding the world).
So now the question is how do I properly rename a world?
I was not able to find something via a search engine nor could I find a file in the world folder that contains the world's name to change it there.

I know that I could use Multiverse or a similar plugin to do what I want but I hope that there is an easier way (like the one i tried).

I hope you can understand everything, sorry that it's not the best English but I'm not a native speaker ^^ .
If I missed to tell you something you need to know please ask :)
If anything else is wrong with this post please tell me as this is my first question posted here.
Any idea or help is appreciated!


texts:
I'm working on collision for walls in my game and the way I currently have it I get stuck walking into a wall. I'm trying to make my character slide on the walls but still collide.

My character moves off of a vector I create using the angle he is facing.

this is my collision function:

    private static bool CheckForCollisions(ref Crate c1, ref Player c2,bool direction)
    {
        for (int i = 0; i < c1.model.Meshes.Count; i++)
        {
            // Check whether the bounding boxes of the two cubes intersect.
            BoundingSphere c1BoundingSphere = c1.model.Meshes[i].BoundingSphere;
            c1BoundingSphere.Center += c1.position + new Vector3(2, 0, 2);
            c1BoundingSphere.Radius = c1BoundingSphere.Radius / 1.5f;

            for (int j = 0; j < c2.model.Meshes.Count; j++)
            {
                BoundingSphere c2BoundingSphere = c2.model.Meshes[j].BoundingSphere;
                if (direction)
                    c2BoundingSphere.Center += c2.position + new Vector3(c2.getPlannedDirection().X, 0, 0);
                else if (!direction)
                    c2BoundingSphere.Center += c2.position + new Vector3(0, 0, c2.getPlannedDirection().Y);
                //c2BoundingSphere.Center += c2.position;

                if (c1BoundingSphere.Intersects(c2BoundingSphere))
                {
                    return true;
                }
            }
        }
        return false;
    }

This is my update:

for (int x = 0; x <= 29; x++)
        {
            for (int y = 0; y <= 29; y++)
            {
                if (crate[x, y].getType() == 11 && collisionEnabled)
                {
                    if (CheckForCollisions(ref crate[x, y], ref player,true))
                    {
                        player.clearPlannedDirectionX();
                        //Console.Write(player.getPosition().X + "," + player.getPosition().Y + "," + player.getPosition().Z);
                        //movePlayer = false;
                    }
                    if (CheckForCollisions(ref crate[x, y], ref player,false))
                    {
                        player.clearPlannedDirectionZ();
                        //Console.Write(player.getPosition().X + "," + player.getPosition().Y + "," + player.getPosition().Z);
                        //movePlayer = false;
                    }
                }
            }
        }


texts: How are UDP packets verified as authentic?

texts:
Hey I'm writing a game and have the backend written using a sometimes-reliable UDP scheme. I want to verify that inbound packets are actually originating from the player specified in the packets.

My idea (not original by any means) was to have the player register an account once and then, once per "session", login over HTTPS/SSL by sending username+password to a simple web service. The game client would check validity of my site's SSL certificate to disallow impersonation. The username and password are submitted and the response is a generated random "secret session key".

Matchmaking happens blah blah...

Then, when playing a match/game, the game client sends packets using UDP and attaches a HMAC-SHA1 of the packet payload using the secret session key as secret. I don't care if people can see the contents of the packet -- there's nothing secret there -- so symmetric encryption isn't needed.

I don't see how the packets can be spoofed since the secret session key was transmitted to the game client over a secure channel but I don't know what I don't know, you know?

Thanks for any insights.


texts: What is a lobe, in reference to lighting and graphics

texts:
I sometimes see references to lobes when talking about lighting, especially with specular lighting, but also with spherical harmonics which doesn't do specular.

Can anyone explain what exactly a lobe is?


texts:
I have a melee enemy tagged as enemy. enemy has two coliders: a capsule(physics) and a sphere(for attacking player in radius and istrigger) and a particlesystem, enemy has enemyhealth script attached.

Similarly, bullet has capsule collider and set istrigger, I've attached enemyhealth script to bullet as enemy sphere and bullet capsule are triggers (bullet doesn't have any particle system need fix for this too without raycast), bullets are destroyed on colliding with enemy but doesn't damage the enemy.

script used for enemy health

using UnityEngine;
using System.Collections;

public class enemyhealth : MonoBehaviour {
  public int health = 40;
  public int current;
  //public int score = 10;
  public AudioSource deathclip;
  public ParticleSystem death;
  CapsuleCollider Collider;
  bool dead;
  // Use this for initialization
  void Start ()
  {
    deathclip = GetComponent<AudioSource> ();
    Collider = GetComponent<CapsuleCollider> ();
    death = GetComponentInChildren <ParticleSystem> ();
    current = health;
    dead = false;
  }

  void Update()
  {}

  public void Takedamage (int amount )
  {
    if (dead)
      return;
    current -= amount;

    if (current <=0)
      die ();
  }

  void die ()
  {
    //GetComponent<NavMeshAgent> ().enabled = false;
    dead = true;
    Collider.isTrigger = true;
    deathclip.Play ();
    death.transform.parent = null;
    death.Play ();
    Destroy(death.gameObject);
    Destroy(gameObject);
  }
}

script used for bullet

using UnityEngine;
using System.Collections;

public class mover : MonoBehaviour {
  public float speed;
  public int damage = 10;
  enemyhealth Enemyhealth;
  GameObject ENEMY;
  bool enemyinrange;

  // Use this for initialization
  void Awake () {
    GetComponent<Rigidbody>().velocity = transform.forward*speed;
    Enemyhealth = GetComponent<enemyhealth> ();
    ENEMY = GameObject.FindGameObjectWithTag ("enemy");
  }
  void OnTriggerEnter(Collider other)
  {
    if(other.gameObject == ENEMY && Enemyhealth.currenthealth >=0)
      enemyinrange=true;

    //Destroy(gameObject);
  }
  void OnTriggerExit(Collider other)
  {
    if (other.gameObject == ENEMY)
      enemyinrange = false;
  }
  void Damage()
  {
    Enemyhealth.Takedamage (damage);
  }

  // Update is called once per frame
  void Update ()
  {
    if (enemyinrange)
        Damage ();
  }
}


texts:
I need an algorithm to split a grid into randomly generated paths where:

A path is a list of cells connected at most to two adjacent cells.
Paths have a minimum and maximum length.
All cells in the grid belong to a path.
Grid might have gaps.

The algorithm must be random, with no artificial bias. With this I mean:

There should be no bias for path positions/trajectories (e.g. wrong if a path always starts at (0, 0), paths always starting adjacent to other path path ends, etc.)
There should be no bias for path lengths. E.g. algorithm must not favor a short length if a longer path would fit.
Natural bias due to grid state (even intermediate states) is fine (unavoidable?).

Input is width, height, number of gaps.

Example of finished grid:

1--1  0  4--4
|     |  |
1--1  0  4--4
   |  |     |
2  1  0  4--4
|     |
2  0--0  3--3
|           |
2--2  3--3--3

Example of grid with gaps:

0--0--0  2--2
      |     |
.  1  0  .  2
   |  |     |
1--1  0  2--2
|
1  .  3  3--3
|     |     |
1--1  3--3--3


texts:
I have created a new project using the third person template. I set the number of players to two in the play settings as well as using a dedicated server.

How do I package the project so that I can run the server and connect to it with clients? So far when I package it all I get is an exe that starts the game like a normal single-player game.

I've looked for any information on how to do this but I just can't seem to find anything.


texts: "RENDER WARNING: there is no texture bound to the unit 0" When not Rendering Texture

texts:
I have a webgl program that sometimes renders textures, but mostly renders triangles or lines. When I am not rendering a texture, webgl gives the warning, "RENDER WARNING: there is no texture bound to the unit 0". Here is some code from my rendering loop:

if (thing.hasOwnProperty('texCoords')) {
    gl.uniform1i(shaderProgram.useTexture, true);
    gl.bindBuffer(gl.ARRAY_BUFFER, thing.texCoords);
    gl.activeTexture(gl.TEXTURE0);
    gl.bindTexture(gl.TEXTURE_2D, thing.texture);
    gl.uniform1i(shaderProgram.tex_uniform, 0);
    gl.enableVertexAttribArray(shaderProgram.vertexPositionTex);
    gl.vertexAttribPointer(shaderProgram.vertexPositionTex, 2, gl.FLOAT, false, 0, 0);
} else {
    gl.uniform1i(shaderProgram.useTexture, false);
    gl.disableVertexAttribArray(shaderProgram.vertexPositionTex);
}

If a thing doesn't render a texture, there is code to set a flag in my shaders not to consult the sampler2d for texture values and instead just draw polygons.

I suppose "there is no texture bound to the unit 0" is correct: there isn't a texture bound since the last call to drawArrays, but why would that issue a warning when I don't try to access TEXTURE0?


texts:
I found a good description of the engine in the Sonic games. It describes roughly how the engine works for people writing their own clones. In my case, I am simply interested in getting a general view of how the many 8-bit and 16-bit game engines worked on their respective consoles.

What other online descriptions exist for specific game engines 8-bit and 16-bit game engines?


texts: What's the standard location of a 3D clipping box?

texts:
The way I understand 3D rendering, polygons are transformed using several matrices, and they are then clipped if they are not inside a certain box, before projecting the box onto the screen. Before transformation, the visible area is typically a frustum, and after transformation, I am guessing it's a cube. This cube makes the clipping math easier than a frustum would.

My question is, what's the 'standard' location/size for this clipping box? I can think of 3 possibilities: (0,0,0)-(1,1,1), (-0.5,-0.5,-0.5)-(0.5,0.5,0.5), (-1,-1,-1)-(1,1,1)

Or is there no standard?


texts:
I'm a programmer, so I am perfectly aware of how to implement a behaviour tree. I don't want to rely on third party tools, but still have convenient tools for creating the AI for my game.

I was looking at tools like this one but I could not find out how to create editor extensions like that in Unity.

I also noticed that there is a new experimental feature (Playables) in the current versions of Unity.Does this use the state machine editor from the Animator? Should/Could I use that to implement a behaviour tree?


texts: Player positions in a race game through arrays or...?

texts:
First time posting on these forums so go easy on me!

I've been programming a race game which has been going quite well. I've just discovered now how hard it is to set up player positions!(As in 1st, 2nd, 3rd, etc). From research I've discovered that the easiest way of doing this is through checkpoints which I've successfully managed to set up. Each player races through the checkpoints in the game and this progress is stored as an int. There's 2 int, one for laps and one for checkpoints. When the checkpoint integer reaches a certain number it resets back to zero and the lap integer is incremented.

I was planning to compare these to work out player positions. Hopefully by putting them into arrays and then sorting them so it could tell me the player's positions in the race as the person with the high lap and checkpoint count would surely be the highest ranked.

Also to make the measuring of player positions more accurate I've measure the distance between checkpoints. At each checkpoint it works out how far the player is from the next point and using the distance from the previous to the next I'm able to generate a percentage which tells me how far the player is from the lap.

What I was hoping to do is create an integer worked out from the players race progress. So for example going through a checkpoint would increment the player's race progress integer by 100. If there were 12 checkpoint a complete lap would obviously be 1200. 2 laps would be 2400 and so on. By inverting the percentage I generated earlier it gives me the distance to the next checkpoint. so for example a player 75% towards the 4th checkpoint in their first lap would have an integer of 375, whereas a player 50% towards the first checkpoint in their second lap would have an integer of 1250.

I hope that logic made sense.

So what I'm essentially looking to create is a sort of table, using the player's object or even a unique player id as an index. And then to sort this table by the player position int.

I think this maybe possible through multidimensional arrays but I'm quite unsure. I've looked into associative arrays, dictionaries and hashtables but I'm still pretty unclear on what to do.

Would really appreciate being pointed in the right direction.
Thanks!


texts: Finding x and z value in the direction of another object

texts:
In my game you can drive a car and it has an arrow point to an object you need to drive towards. The arrow pops up above the car using the same x and z value as the car but adding 2 to the y value. What I am trying to do is push the arrow out a little bit toward the object it is pointing to. This way it looks like it is rotating in a circle around the car instead of rotating about it's own center point.

This is what I am doing right now:

if (!(Vector3.Angle(car.transform.forward, obj.transform.position - car.transform.position) < 40f))
{
    arrow.SetActive(true);
    temp = car.transform.position;
    temp.y = car.transform.position.y + 2f;
    arrow.transform.position = temp;
    temp = obj.transform.position;
    temp.y = arrow.transform.position.y;
    arrow.transform.LookAt(temp);
}


texts: How should I efficiently store faction relationships?

texts:
I'm working on a game that follows the life of a powerful magician as she lives, dies, and reincarnates dozens of times across hundreds of years. Meanwhile, empires rise and fall around her--she can influence them by killing their kings or even becoming their leader, but even without her they will go about their business, fighting wars with other factions and appointing new leaders.

The problem is this: how do I store all those faction relationships? Currently, I have a class Faction, which has an enemy list, a ally list, and a controlled list (the Government of Rezla controls the Army of Rezla, etc). However, simply using lists like these limit me to a binary ally/not-ally, enemy/not-enemy deal.

I suppose I could get around that to some degree by using a list of lists, so RezlaGovt.allies contains [[AzosGovt, 2],[JupaGovt, 4]], where the first value in the sublist stores the name of the ally and the second value stores the current reputation, but that seems inelegant (and I don't really understand how to manage it properly in code). It also makes it much more difficult to later add tags to the relationships, like hasTradeAgreement or hasMutualDefencePact.

What data structure do other complex strategy games use to handle faction relationships?

Other Details:

I will have around 10 main factions for the world governments, each with subfactions and subsubfactions (and maybe even subsubsubfactions!), so a system that deals well with large datasets is a plus.

Not all factions need to be simulated all the time: the Fighter's Guild in a distant city might be completely ignored until the player does something in the area, at which point I can randomly generate some "history" for it, to make it seem like it's been doing stuff.


texts: I want to show total time spent by all players around the world in my game

texts:
I am developing a Unity3D game. I want to show in my game:

Total time spent playing all time by all players around the world
Total time spent playing in last 24 hours by all players around the world

I heard that it can be achieved by analytics services like Flurry / Google Analytics. I did some research but I am not getting anywhere by myself. Can anybody guide me to the right path?


texts: How to accurately count 1 second within my logic update?

texts:
I have the following method:

long time = system.nanoTime();

public void count(){

    if (System.nanoTime() > (time+1000000000)){

        //Output something or perform action here
        Log.v("timer","One second passed");

        //Reset for next second-count
        time = system.nanoTime();
    }

}

This should output to the console every 1 second.  It's close, but it seems not quite perfect.

If I time this with an actual stop watch (or with the same code running on another device), over time, it becomes slightly 'off'.  Not by much, but it's off.  After a minute, it's about 1/4 of a second off, the longer it is left, the larger the discrepancy.

The above method is called from within my updateLogic() method which is called aprox 60 times per second from my main game loop.

Can anyone tell me why this doesn't count extactly 1 second or why it's becoming out of snyc over time?  How can I get a perfectly accurate timer that will run exactly the same on all devices?


texts: How to accurately capture the direction in which the mouse moves?

texts:
I used to play this game on Kongregate called Death vs Monstars.

A tl;dp (too long; didn't play) explanation of the mechanics is that the character you control follows your mouse cursor. Your charcter fires projectiles endlessly in the direction opposite of that in which you just moved (basically out of your back). This game offers a fairly smooth experience in that you can be fairly sure that the projectiles will fire in the opposite direction that you move your mouse in.

I recently tried to recreate this idea in Godot 3.0.6 Mono.
It's not the same game, but the idea is that the character controlled by your mouse has an object that is always pointing in the opposite direction of the character. The problem I faced is that the capturing the direction in which the player moves every frame is limited to the very discrete grid of pixels which Godot (and presumably most other engines) uses to interpret the cursor position. Essentially I just get the angle of rotation from the old position vector to the new position vector, and rotate the character accordingly before updating the position. The result is that the direction in which the character is facing, and thus the object behind it, is very unpredictable. For example, you may move your mouse at a 60 degree angle, but the character ends up pointing in a 45 degree angle depending on what pixel your cursor ends up in.

Is there a less discrete way to approach this problem? Instead of reading the integer-vector position of the mouse cursor, could one somehow get the velocity of the mouse movement?

Any other methods of doing this are also appreciated. I am not asking this question for Godot specifically, but generally, in case there is a common "right" way to do this.


texts: Basic equation for pure metallic reflectance

texts:
I'm working on a live wallpaper that shows a pure metallic object. Since it's a live wallpaper, I can make a ton of approximations...this isn't a full blown scene in a game world. My shader only has to support this one material. People won't expect extreme detail, etc. So, for example, I don't even bother with diffuse since a pure conductive material barely has any.

So I'm trying to implement a reflective conductive surface that pulls the reflection from a cubemap representing the lighting environment. On a very basic level it looks like this:

vec3 fresnelSchlick (vec3 f0, float cosTheta)
{
    return mix(f0, vec3(1.0), pow(1.0 - cosTheta, 5.0));
}

//...
float NdV = dot(normal, viewDir);
vec2 brdf = texture2D(u_brdf, vec2(u_roughness, NdV)).rg; // from a LUT

vec3 reflection = textureCube(u_cubemap, reflect(viewDir, normal));
gl_FragColor = reflection * (fresnelSchlick(materialColor, NdV) * brdf.x + brdf.y);

The problem with my simple math here is that the range of possible final pixel colors does not produce a proper-looking range of hues. Suppose my material color is #0050ff and the environment is monochrome white. Then all of the possible colors that could be seen are:

This doesn't allow for bright looking reflections at the light sources in the envmap. I found this example material render for comparison. The cubemap in the example here is close to monochrome white. But at the bright areas of the reflection, there is a lot of red component in the color.

With my limited range of colors, my object looks dull and lifeless. Can anyone point out what I'm missing in my equation?


texts: How do you create 2D skeletal animations without extra software?

texts: I'm working on a Cocos2d-x game and I'm developing on Windows. What I want is to make some skeletal animations, without using a tool or extra software to do so?


texts: Detect collision that happen between frames, between slices of moving, rotating circles?

texts:
To detect a collision between two circles, we check if the distance between their centers is smaller than the sum of their radii.

To detect a collision between a slice (in this case half) of a circle and a circle:

Check if the circles are in collision.
Find the two points of the imaginary segment that splits the circle (in the middle).
Check if either of these two points is contained inside the other circle (if so, it is colliding with both slices, red & blue).
If not, compute the angle between the two circles and use that to decide if the circles are touching from one side or the other.

Is there any reasonable way to compute this on moving objects? i.e, so collisions will not be missed because of the discrete nature of frames?


texts: How to setup Authentication Database and Game Database?

texts:
I'm playing around with creating a game in C# using the XNA Framework. I've decided to use technologies that I'm pretty much familiar with and create things from scratch. There are probably frameworks out there that would take away all of the difficulties that I'm encountering but I find it fun to dive into these challenges and over come them manually if you will.

My current issue is that when I play MMO type games I know the general setup. I must login (authenticate) and then select a server to begin playing on. Once I log into the server I'm generally met with a Character Select screen of some sort before I actually "log in to the game".

With that said, my initial attempt at developing a database system was this:

Authentication Database - table for user information, table for server information
Game Database - table for characters, table for inventories, items, etc...

After I created these I noticed a key missing problem. Users are linked to characters and characters are linked to a server. I currently have these pieces of information spread over 2 databases. I thought to myself, maybe this isn't a good idea?

I guess I could: Game Client can store the reference to the account identifier in the code once login was successful, but doesn't that sound like a security issue?

Anyone have thoughts or suggestions? Or a good book recommendation for development in this area?

Note I'm not trying to develop an absolute perfect system that I can release and make money off of. I'm more doing this for experience, fun and enjoyment so my solution doesn't have to be perfect, but I don't want it to be the worst possible solution either :)


texts:
I want to find a formula to get the probabilities of dice roles in the game Infinity. In this game people are rolling a set number of 20 sided die against another number of 20 sided die, hoping to roll the higher number. In addition each person has a set target number that limits how high a die value he can use. So if my target number is 13 any number I roll above a 13 does not count.

For example if I am rolling 3 dice (20 sided) and need to roll a 11 or below, and my opponent is rolling 1 die (20 sided) and needs a 14 or below. What are my chances of getting a higher number than him without going over 11?


texts: Intuitive way to handle dragging outside the Arc Ball?

texts:
So I'm writing a game (or toy, rather), which involves manipulating a 3d object with the mouse. I'm trying to get the most intuitive control that I can.

I've implemented the "Arc Ball" mouse control. I'm happy with how it "feels", except for when I drag the mouse outside the range of the virtual ball.

Currently when the ray from camera to mouse-pointer in world-space does not intersect the virtual sphere, I simply find the closest point to it.

This results in something that acts like this example (not my code, just an example I found with the same implementation as me).

Notice the behaviour change when you click and drag away from the cube.

I'm not sure if it makes sense, but I am hoping for some way of allowing the cube to continue to rotate no matter how far away the mouse pointer gets, while still maintaining the useful property of standard Arc Ball that returning the pointer to the starting point will undo all rotation.

Any suggestions?


texts: Calling and functions/methods from different Classes in Unity

texts:
I am learning some of the basics with Unity and am running into calling/sending code to a different script.

For example, the code below is a basic menu of options. I have a different Scene set up in Unity for each one of the menu options. As you can see from the if/else if statements, depending on which option a user checks, will take them to a different portion of the program.

At this point it will obviously not compile because the 4 methods for each menu option are not referenced anywhere.

Lets say the user selects option 1 which is the StudyScreen() method. Now in the StudyScreen.cs script that I created, how do I link those so when option 1 is selected, it goes to the StudyScreen.cs and runs what I need it to run.

using UnityEngine;
using UnityEngine.UI;
using System.Collections;

public class MainMenu : MonoBehaviour {

public Text menu;

// Use this for initialization
void Start () {
    menu.text = "Main Menu Options\r\n\r\n" +
                "1. Study\r\n" +
                "2. Quiz\r\n" +
                "3. Test\r\n" +
                "4. Exit\r\n";
}

// Update is called once per frame
void Update () {
    if      (Input.GetKeyDown(KeyCode.Alpha1))  {StudyScreen();}
    else if (Input.GetKeyDown(KeyCode.Alpha2))  {QuizScreen();}
    else if (Input.GetKeyDown(KeyCode.Alpha3))  {TestScreen();}
    else if (Input.GetKeyDown(KeyCode.Alpha4))  {ExitScreen();}

    }
}

I hope I was able to make it clear as to what I was trying to accomplish. Please let me know if anything is unclear.

Thanks in Advance.
Curtis


texts:
I have a full working game for WP7, I want to port it to WP8 with Monogame. I have installed Monogame and I have done all tests to see that it is working inside Visual Studio Express 2012 for Windows Phone 8. Now I just don't understand how to rebuild my WP7 version game within a Monogame project to target WP8 devices.

So, if you would have the entire solution of a WP7 game, how would you make it work on WP8 with Monogame?

Thanks!


texts: High Performance Vector Graphics Solutions

texts:
I'm looking for a high performance vector graphics library I can use in my games.

I'm thinking along the lines of vector graphics such as those that can be made with SVG.

I'll consider any language at the moment (but must run on Windows).
A solution that takes advantage of GPU hardware would be great.

Thanks in advance.


texts: OpenGL ES 2.0 Shadow Mapping - depth only FBO not working due to GL_FRAMEBUFFER_INCOMPLETE_ATTACHMEN

texts:
I am trying to add simple shadow mapping to my friends gles 2.0 app. It is based on gles 2.0 and PowerVR SDK.

The problem I encounter is that FBO is not valid due to GL_FRAMEBUFFER_INCOMPLETE_ATTACHMEN (0x8CD6) error checked with glCheckFramebufferStatus() function.

I also checked call to glTexImage2D() function with glGetError() and it returns GL_INVALID_OPERATION (0x0502).

Here is my code:

GLuint framebuffer;
glGenFramebuffers(1, &framebuffer);
glBindFramebuffer(GL_FRAMEBUFFER, framebuffer);

GLuint depthTexture;
glGenTextures(1, &depthTexture);
glBindTexture(GL_TEXTURE_2D, depthTexture);

GLenum error = glGetError(); // no error
// I tried also various combination of GL_DEPTH_COMPONENT16 formats and internal formats
glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, 1024, 1024, 0, GL_DEPTH_COMPONENT, GL_FLOAT, 0);
error = glGetError(); // GL_INVALID_OPERATION (0x0502) error

glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);

glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, depthTexture, 0);

GLenum framebufferStatus = glCheckFramebufferStatus(GL_FRAMEBUFFER);

if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE)
{
    GLenum framebufferStatus = glCheckFramebufferStatus(GL_FRAMEBUFFER); // GL_FRAMEBUFFER_INCOMPLETE_ATTACHMEN(0x8CD6)
    printf("Invalid framebuffer\n");
}

I have no idea what is wrong. I tested in on integrated Intelu GPU and Nvidia 1080 Ti GPU so this in probably not a driver bug.