texts: Need to combine a color, mask, and sprite layer in a shader

texts:
My task: to display a sprite using different team colors. I have a sprte graphic, part of which has to be displayed as a team color. The color isn't 'flat', i.e. it shades from brighter to darker. I can't "pre-build" the graphics because there are just too many, so I have to generate them at runtime. I've decided to use a shader, and supply it with a texture consisting of the team color, a texture consisting of a mask (black=no color, white=full color, gray=progressively dimmed color), and the sprite grapic, with the areas where the team color shows being transparent.

So here's my shader code:

// Effect attempts to merge a color layer, a mask layer, and a sprite layer
// to produce a complete sprite

sampler UnitSampler : register(s0); // the unit
sampler MaskSampler : register(s1); // the mask
sampler ColorSampler : register(s2);    // the color

float4 main(float4 color : COLOR0, float2 texCoord : TEXCOORD0) : COLOR0
{
    float4 tex1 = tex2D(ColorSampler, texCoord);    // get the color
    float4 tex2 = tex2D(MaskSampler, texCoord); // get the mask
    float4 tex3 = tex2D(UnitSampler,texCoord);  // get the unit
    float4 tex4 = tex1 * tex2.r * tex3; // color * mask * unit

    return tex4;
}

My problem is the calculations involving tex1 through tex4. I don't really understand how the manipulations work, so I'm just thrashing around, producing lots of different incorrect effects. So given tex1 through tex3, what calcs do I do in order to take the color (tex1), mask it (tex2), and apply the result to the unit if it's not zero?

And would I be better off to make the mask just on/off (white/black) and put the color shading in the unit graphic?


texts: Unity: Record real time game play in high quality using offline rendering?

texts:
I'm looking to record Unity gameplay at really high quality (360 Stereo 8k 120 fps). I can't do this in real time due to the GPU resources required so I need to do offline rendering (frame perfect rendering).
The problem is offline rendering by its nature doesn't accept user input, so I can't record live gameplay footage. I'm looking for a solution that lets me record live gameplay and then render it out at this higher quality.
I considered recording the user input or the gameobjects properties and then playing them back while rendering the footage. I tried a number of assets like Ultimate Replay 2.0, Record and Play, GameObject Recorder, even tried Unity Recorder to an animation but none of them record all of the changes to components on a gameobject. I think I'll have to write my own code, although I'm not sure what the best method would be, I'm reluctant to sink to much development time into this if there's an easier solution that I've overlooked?
Initially I'm looking for a solution that works inside the Unity editor but would love to be able to give this ability to end users.


texts: Scene with Node graph thread safe, with important efficeny

texts:
I will try to be as explicit as I can, and I apologize for my grammar...

I am working on a game engine (specifically on the Render part) and I am facing some conception choice that will involve a lot of code and I would like to do the good one on first try. I am actually working on the Scene graph. I have to specify, that the engine have to be thread safe, and c++11/14 compliant while limiting the user mistake (not allowing engine user moving a pointer that shouldn't be moved...).
So my issue is that I do not know how to give the access too engine user and keep the thread safety without killing performance with 10000 of cache misses or if it is needed to be able to search for a specific Node (when you build the tree don't you know wich Node  you will use?).

Actually I started with a tree of Node something very standar

Each Node know all of its child and they know their parents.
For efficiency purpose every Node who will contain meshes, with associated texture will stock them in a Scene object who will old a pointer on every Node who hold a mesh (for querying the scene transformation matrix of the mesh). The scene will also hold the root Node of the scene.

My question is How should I handle the link between A Node and its family?

One of the solution I thinked about is to use the Observer design pattern.
Use shared_ptr between Node and it's family then only provide NodeObserver to the engine user. But with this solution I don't know how to link the scene ressource holding to the nodes because a shared_ptr will introduce unbreakable cycle and a wear_ptr will introduce to much cache_miss and to much synchronization (at least a lock on every Node every frame...) I could use a naked pointer stored into the Scene object, and at the end of its life Node destructor should removeit from the Scene?

I will be very happy if anyone know how to do that.
Thank you in advance for your time and your help.


texts: Enabling Xbox One Controls with UWP APP made with Unity

texts: I am creating a UWP game for PC it uses the mouse as the only form of navigation;I am using the latest version of Unity to make this UWP game. The question is regarding what happens when the UWP is running on the original Xbox One (which is software compatible with later xbox one models).How is the Xbox One mouse mode enabled in C Sharp in Unity in a UWP app? What is the Xbox one controls that are mapped from a PC mouse? I have tried all sorts of things but I can't get the xbox one controller to work as a mouse like controller.


texts: Using 16 bit index buffers - USHORT vs UINT

texts:
In D3D11, they still have the ability to make 16 bit and 32 bit index buffers.

Few models will use more than the max (20k tri) that a USHORT index buffer can handle, but will I really pay a bad performance cost for always using an INT (32 bit) format?

Memory savings aren't that much (2 bytes per index!).  For a 20k tri model, that's only 40 kB of memory we're saving for using the USHORT (compared with probably a lot more for just the vertex data for that same model).

Is it really worth ever using USHORT index buffers then, or is this just a holdover from when computers had less memory in the 90's?


texts: How can I render a JBox2D ParticleGroup?

texts:
I want to render a ParticleGroup from JBox2d using OpenGL.  I've managed to define a particle group area, but I'm unsure how to draw the individual particles.

Here's how I create the ParticleGroup:

m_world.setParticleRadius(0.15f);
m_world.setParticleDamping(0.2f);

PolygonShape shape = new PolygonShape();
shape.setAsBox(8, 10, new Vec2(-12, 10.1f), 0);
ParticleGroupDef pd = new ParticleGroupDef();
pd.shape = shape;
m_world.createParticleGroup(pd);

This is how I draw a normal Square (which I don't know how to apply to groups of particles):

public void draw(GLAutoDrawable gLDrawable, Vec3 position, float angle){

    gLDrawable.getGL().getGL2().glEnable(GL.GL_BLEND);
    gLDrawable.getGL().getGL2().glEnable(GL.GL_TEXTURE_2D);

    gLDrawable.getGL().getGL2().glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_ONE_MINUS_SRC_ALPHA);

    gLDrawable.getGL().getGL2().glBindTexture(GL2.GL_TEXTURE_2D, TextureFactory.getTextureIndex(TextureCollection.valueOf(getTextureSelection())));
    gLDrawable.getGL().getGL2().glPushMatrix();

    gLDrawable.getGL().getGL2().glTranslatef(position.x * getP2M(), position.y * getP2M(), position.z);
    gLDrawable.getGL().getGL2().glRotated(Math.toDegrees(angle), 0, 0, 1);
    gLDrawable.getGL().getGL2().glBegin(GL2.GL_QUADS);
    gLDrawable.getGL().getGL2().glTexCoord2f(0.0f, 0.0f);
    gLDrawable.getGL().getGL2().glVertex3f(-getWidth() / 2 * getP2M(), -getHeight() / 2 * getP2M(), 0.0f);
    gLDrawable.getGL().getGL2().glTexCoord2f(0.0f, 1.0f);
    gLDrawable.getGL().getGL2().glVertex3f(-getWidth() / 2 * getP2M(), getHeight() / 2 * getP2M(), 0.0f);
    gLDrawable.getGL().getGL2().glTexCoord2f(1.0f, 1.0f);
    gLDrawable.getGL().getGL2().glVertex3f(getWidth() / 2 * getP2M(), getHeight() / 2 * getP2M(), 0.0f);
    gLDrawable.getGL().getGL2().glTexCoord2f(1.0f, 0.0f);
    gLDrawable.getGL().getGL2().glVertex3f(getWidth() / 2 * getP2M(), -getHeight() / 2 * getP2M(), 0.0f);
    gLDrawable.getGL().getGL2().glEnd();
    gLDrawable.getGL().getGL2().glFlush();
    gLDrawable.getGL().getGL2().glPopMatrix();

    gLDrawable.getGL().getGL2().glDisable(GL.GL_TEXTURE_2D);
    gLDrawable.getGL().getGL2().glDisable(GL.GL_BLEND);
}

How should I do this?  (Example code would be great.)


texts: How to flatten out terrain and make better caves with Perlin noise

texts:
I'm currently using Perlin noise to generate a terrain. This is my actual attempt to create caves. I do get some sort of cave structures but they are small and are always close to the edges of the terrain. Also my terrain looks very irregular I'd like to have a more flat terrain. I've been playing with the values I pass to the Perlin noise function but I can't seem to get something good.

Do you have any pointers or suggestions to my actual approach in order to get something more regular within the Minecraft standards?


texts: Powers of 2 textures in Android 2d games?

texts:
I've read a lot about the importance of using powers of 2 png's for textures when using OpenGL ES. However, how does this relate to Google's own documentation regarding the resizing of graphics for the various screen density's. I will explain:

Let's say I have a 256 x 256 texture that I use for in the XHDPI folder for use on Extra High Density screens. Using Google's own recommended scaling factors, I would scale this by 75% to use in my HDPI folder, it would then become 185 by 185 which isn't a power of 2?

Could someone clear this up for me?

As noted, I'm asking specifically with regards to 2D sprites using quads.


texts: How does ads actually make you money when you upload a Game?

texts:
I am an independent game developer and I have made my own game. I want to upload it on the Play store and I understand that you need to pay $25. But there's something I don't understand in terms earning money. I have look on websites and some websites say for every 1000 views on an ad, you get $0.10 but on another, it says every view you get $0.10.

I don't understand the system of earning money when it comes to putting ads in your game. I understand its a bit of a stupid question but it will help when i upload my game for real.


texts:
I am working on a game project in unity which has a procedurally generated terrain made up of 16*128*16 chunks of blocks. The map size is going to be finite (Possibly up to ~100*100 chunks). Currently the data for the chunk is stored in a 1D Array, and takes a couple milliseconds to generate. But generating the mesh takes longer, averaging 30-40ms. So generating terrain as it enters the range of the camera isn't feasible as it's too slow, and generating all the meshes on load up would take a lot of memory as well as a long time. I've thought about attempting to try it on the GPU through Compute Shaders (although I don't have any experience with them).

Would generating the mesh for each chunk in a Compute Shader be viable/efficient? (The chunks could be made smaller if would be more performant)


texts:
In the game you have an object called obj_Corpo, and your image is a 3x3 square. I use it by stretching it horizontally or vertically for 10 or 20 times. Here's an example:

Acontece que no jogo ele não aparece da forma adequada.

It turns out that in the game it does not appear properly.

Note that it only gives horizontal error. This began to happen a few days ago, with no explanation. I've tried other colors and the same thing happens (darkened edges).


texts: Do I need the dev kit in order to release for Wii U?

texts:
In nintendo's developper website I found this quote.

  Q: How much does it cost to develop on Wii U?

  It’s free of charge to participate in the program and to submit games
  to Nintendo for technical certification. There is some cost involved
  for Wii U development hardware, but we run a program to help
  developers who are just getting started.

Now is it necessary to get those dev kits? I mean if I have my own personal console. Use Unity libraries (for example there is a ready .dll for using the WiiMote ), am I obliged to get the dev kit? I plan to develop my game using unity if that makes any changes.


texts:
Whenever I lose focus from my game window, I go from ~60FPS to 6000+, then when the window gains focus again, I go back to around 60 frames per second. And yes, this happens every time I run my game, including Release mode.

Here is an example log output from my game:

[INFO] [10/01/2013 22:37:42.355] Window Gained Focus!
[INFO] [10/01/2013 22:37:45.365] Frames Per Second: 60.0439
[INFO] [10/01/2013 22:37:45.365] Frame Counter: 60
[INFO] [10/01/2013 22:37:46.365] Frames Per Second: 60.0324
[INFO] [10/01/2013 22:37:46.365] Frame Counter: 60
[INFO] [10/01/2013 22:37:47.381] Frames Per Second: 59.4341
[INFO] [10/01/2013 22:37:47.382] Frame Counter: 58
[INFO] [10/01/2013 22:37:49.669] Window Lost Focus!
[INFO] [10/01/2013 22:37:50.383] Frames Per Second: 1240.02
[INFO] [10/01/2013 22:37:50.383] Frame Counter: 9561
[INFO] [10/01/2013 22:37:51.384] Frames Per Second: 1839.02
[INFO] [10/01/2013 22:37:51.384] Frame Counter: 6662
[INFO] [10/01/2013 22:37:52.77] Window Gained Focus!
[INFO] [10/01/2013 22:37:52.400] Frames Per Second: 1656.77
[INFO] [10/01/2013 22:37:52.400] Frame Counter: 34
[INFO] [10/01/2013 22:37:53.400] Frames Per Second: 1512.46
[INFO] [10/01/2013 22:37:53.400] Frame Counter: 60
[INFO] [10/01/2013 22:37:54.401] Frames Per Second: 1391.89
[INFO] [10/01/2013 22:37:54.402] Frame Counter: 60
[INFO] [10/01/2013 22:37:55.402] Frames Per Second: 1289.78
[INFO] [10/01/2013 22:37:55.402] Frame Counter: 58
[INFO] [10/01/2013 22:37:55.876] Quitting with error code: 0

The frame counter is just a simple integer that I increment every loop in the game, and then reset (and print it out) every second. Here is the implementation of my game loop, (inside the run() function), based off of this article.

Is this a problem with my loop, or is this a problem with SDL? I'm not sure why my frame rate is rocketing up.


texts: How is Handles.DrawSelectionFrame supposed to be used?

texts:
The Handles class has a function Handles.DrawSelectionFrame(). Here's the useless official documentation for this function:

Draw a camera facing selection frame.

When I call this function, nothing is displayed. Other handles seem to work fine.
    void OnDrawGizmos() { //results are same in OnSceneGUI in an Editor
        Handles.color = Color.red;
        Handles.DrawLine(transform.position, transform.position + Vector3.up * 100)); //shows up
        Handles.Label(transform.position, "Hello World"); //shows up
        int i = -1;
        //is the size in world units? pixels? the documentation doesn't say
        for (float size = .5f; size  < 1000; size  *= 2) {
            //nothing shows up
            Handles.DrawSelectionFrame(i, transform.position, Quaternion.identity, size, EventType.MouseMove);
            i++;
        }
    }

How is this function supposed to be used?


texts: Collision intepenetration and objects getting stuck (Unity)

texts:
I am having what is probably a newbie problem with Unity, but for the life of me, I can't find a decent solution to it. In short: my rigid bodies collide, but sometimes, they interpenetrate and stay stuck.

I am looking for a solution that would either
1- stop the interpenetration from even happening
2- or at least eject the bodies to 'unstuck' the collision.

By making the physics fixed step 0.01 instead of the default 0.02, I can avoid some of the interpenetration. However, that hardly sound like the proper way to fix this problem.

Here is a screen shot of the bodies colliding. The car on the right is shown completely and you can notice that the ones behind have penetrated the others to some extent.

To give more information that could be relevant:

There is no gravity
All the objects have rigid bodies
Their sizes are 3.5 x 6.8 and they are moving at 8 to 50 m/s
Each object has a conpounded collider made up of 3 box colliders
If I change the fixed step to 0.01 there is a lot less more interpenetration (as I mentioned). Other physics settings do not seem to have any effect
The object is moved by setting its velocity in the FixedUpdate function with rigidbody.velocity = XYZ until there is a collision, then there is no more processing done in FixedUpdate at all. I detect the collision with OnCollisionEnter and set a flag.
I haven't set any collision material, but I can't see that being a factor?

Solved

Thanks to everyone who helped me with the issue.

There were a few factors in play. First, there was the scale. What I did to figure this one is create an empty scene and put 2 cubes in there. I varied the size and position of the cubes (from 68x35 to 0.65x0.35 for size and the position by factors or 10 as well) and attached a script to move them, with variation in speed by factors or 10 as well. So all else being equal (same size on the screen and time to cross it), the size of the objects elected a different response to collision: big object got interpenetration, small ones none. I am not familiar enough with Unity to explain the cause of that, but it is reproductible.

A possible second factor was the shape of my colliders and how it may be possible that they screwed up the ejecting part. The colliders I had were not overlapping, so I simplified them to 2 boxes in the shape of a cross.

Finally I was setting the position of the objects manually in FixedUpdate and that caused some problems with interpenetration at lower scale (at higher scale, it didn't appear to matter). I changed that to work with the body velocity and it helped.


texts: Set the start orientation of the gyroscope to initial phone orientation

texts:
I am making a mobile VR project in Unity, and I have a 360-degree video that starts playing where I can look around using a VR headset.

I am trying to set the start rotation of the video to the same rotation as my phone. So no matter where I look when I start the video, that should be my start rotation. I used Input.gyro.attitude in the start but that did not fix my problem. I think I am using it wrong.

This is my code (on the camera inside the sphere):

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

public class Gyroscope : MonoBehaviour
{
    private bool gyroEnabled;
    private Gyroscope gyro;
    private GameObject cameraContainer; //A camera container for my main camera
    private GameObject videoSphere; //The sphere my video is in
    private Quaternion rot;

    private void Start()
    {
        videoSphere = GameObject.FindGameObjectWithTag("Video");
        cameraContainer = new GameObject("Camera Container");

        gyroEnabled = EnableGyro();

        cameraContainer.transform.position = transform.position; // put the cameracontainer into the sphere
        cameraContainer.transform.rotation = Input.gyro.attitude; // here I want to set the cameracontainer to the rotation of my phones gyroscope
        transform.SetParent(cameraContainer.transform); // make my main camera a child of the camera Container

        videoSphere.transform.localRotation = cameraContainer.transform.rotation; // Here I wanted to set my sphere rotation to the camera rotation
        Debug.Log(videoSphere.transform.localRotation);
    }

    private bool EnableGyro()
    {
        if (SystemInfo.supportsGyroscope)
        {
            Input.gyro.enabled = true; // turn on my gyroscope

            cameraContainer.transform.rotation = new Quaternion(0, 90, -90, 0); // rotate my camera container so the video shows good
            rot = new Quaternion(0, 0, 1, 0); // set the variable rot so that you can turn your device
            return true;
        }
        return false;
    }

    private void Update()
    {
        if (gyroEnabled)
        {
            transform.localRotation = Input.gyro.attitude * rot; //this makes you turn the device and it recognizes the input of the phones gyroscope
        }
    }
}


texts: Is ActionScript 3 used by Serious Indie Developers?

texts:
This question is for dedicated independent game developers:

My dream is to be a game developer. I am a senior in high school who has taken Computer Science for all four years. I have used Java the whole time, but last year I started using PHP and ActionScript 3 (with Flixel). I also used Game Maker for a brief period. I apologize for this, I wanted to get that out of the way and clarify the fact that I have experience of some kind with game development.

I am stuck at the moment because I don't quite know what language to use to develop games at a professional level. I am seriously interested in becoming a dedicated game developer, but this issue is really bothering me. I would like to know what the best option would be for my case, based on your experiences. Any advice is appreciated.

Things to consider:

I am only interested in making 2D games (I am not worried about 3D support)
It would be ideal to use something that can be ported to multiple platforms (so as not to run into this problem later)
I can't seem to figure out what the industry likes to use

So far, this is what I have:

I can't decide if it would be wise to stick with ActionScript 3, or move to C++
I know Flash would be for browser games, but what if I want to make a downloadable game, like Plants Vs. Zombies or Super Crate Box? Would Flash be a smart choice for standalone games, or did they use something else?

Thank you for reading this, as I would like to stop worrying about this and make some games! Also, I hope this wasn't all over the place :)

tl;dr Should I move ahead with AS3 or use something else i.e. C++


texts: How do I bring a child object in its original position after it is translated and rotated?

texts:
This is the original position of the cube and its child object cone.

Over here, I have translated the cone for 2 units

Now I have rotated the parent cube around 25 degrees wrt to the Y-axis

If we translate the cone 2 units back again, it's not in the original position

What formula do I need to apply to the cone while translating it back to bring it back to it's original position?
Code: The below code is a coroutine for translating the child object
  IEnumerator MoveToNewPos()
 {
       Vector3 newPos += Quaternion.Euler(0, 0, 135) * Vector3.left * distance;

    float t = 0;
    float animTime = 30;
    isMoving = true;
    for (; Vector3.Distance(transform.position, newPos) > 0.001f; t += Time.deltaTime)
    {
        float p = t / animTime;
        transform.position = Vector3.Lerp(transform.position, newPos, p);
        yield return null;
    }
   isMoving = false;
}


texts: Unity: Particle System turn invisible when turning camera away

texts:
When turning the camera away the particles disappear as seen: Here.
I set the shape of the spawner to a custom mesh. I usually use Box as the shape of the Particle spawner and never had any problems with it.
Bounds:

Settings of Particle System:


texts: DontDestroyOnLoad() doesn't work in Unity

texts:
I have a problem with DontDestroyOnLoad() in Unity. It does not work!

My code:

private static PlayerSpawningScript instance;

public void Awake()
{
    Debug.Log ("PlayerSpawningScript awake");
    Debug.Log ("Instance: " + instance);
    if (instance == null) {
        Debug.Log ("Initializing PlayerSpawningScript instance");
        instance = this;
        DontDestroyOnLoad (gameObject);
    }
    if (instance != this) {
        Debug.Log ("PlayerSpawningScript instance exists. Destroying new copy.");
        Destroy (gameObject);
    }
    Debug.Log ("PlayerSpawningScript instance: " + instance);
}

public void OnDestroy()
{
    Debug.Log ("Destroying PlayerSpawningSceript instance: " + instance.ToString ());
}

Basing on the console output, I successfully create an instance in scene1, but when I change the scene, it gets destroyed - I know this because I get "Destroying PlayerSpawningScript (...)" before the new scene is loaded, and the same script set up in scene2 does not find an existing instance (which held data saved in scene1) and sets up itself as the instance instead of getting Destroyed. What am I doing wrong?


texts: Creating an update "Tick" on tiles for simulating growth of plants

texts:
In my 2D tile based platformer I have added plants to be able to farm such as the simplest, grass, to other things like corn. Now each of these speacial tiles must be updated to show how much it has grown (Simple states such as 0 = New, 1 = Mature, 2=Blooming)

My question is, what would be the best way to do this?

So far I belive I could:

Update every tile every few seconds, and if a random chance is met, make it grow
Choose a few tiles every frame to update (minecraft does this, same thing in 3D basicly)
???

Now the timeframe for the updates would be something like, a flower blooms every game day (10 minutes in real life), grass spreads every in game hour, etc

Thanks for your help, I think I could do this, I'd just like a little advice if any of these are the right path.


texts: Load/generate new resources on start up in MonoGame

texts:
I've a question about loading resources at the beginning of my game written in MonoGame. I've several spritesheets which I'm loading at the beginning of the game. This take about 5-10 seconds on my computer but I've got some reports it takes up to a minute on other computers...that´s way too long.
The reason is not loading the Texture2Ds but writing new RenderTargets on Startup. I've some colored spritesheets where I generate a black/white version of it on startup. That costs the time.

Now to my question: I've tried to do this operation later in the game so the game starts more quickly and I tried to start the color-> black/white operation when the player creates a new game - that would be a perfect situation to do it. But I always got two different kind of errors:

1. Operation not called on UI thread

or

2. Cannot call Present when a render target is active

As you may have guessed I do the load operation in a separate thread so the UI doesn't get frozen. But the actual problem seems to be, that I can not do RenderTarget operations when I'm already doing SpriteBatch operations (Begin and End).

How can I solve the problem?

Would be happy for any kind of suggestion.

Yheeky


texts: How to let game characters enter existing 3D buildings model in my own game?

texts:
I want to use ShiVa 3D game engine to build a 3D RPG game. And I want to load other people's 3D models into my game so that I wouldn't need to draw these things myself.

Here's a building model I loaded in 3ds Max, I don't know if I loaded this model in game engine, can my character enter this building and see the decoration inside? How can I verify this?

http://i.imgur.com/GHWQjXA.png

And if I cannot let my character enter this building, is there any resources that I can use on the Internet?

Thanks in advance.


texts:
The floodfill algorithm is used in the bucket tool in MS paint and photoshop, but it can also be used for GO and minesweeper.

http://en.wikipedia.org/wiki/Flood_fill

In go you can capture groups of stones, this website portrays it with two stones.
http://www.connectedglobe.com/mindy/cap6.html

This is my floodfill method in Java, it is not capturing a group of stones and I have no idea why because to me it makes sense.

public void floodfill(int turn, int col, int row){
    for(int a = col; a<19; a++){
        for(int b = row; b<19; b++){
            if(turn == black){
                if(stones[col][row] == white){
                    stones[col][row] = 0;
                    floodfill(black, col-1, row);
                    floodfill(black, col+1, row);
                    floodfill(black, col, row-1);
                    floodfill(black, col, row+1);
                }
            }
        }
    }
}

It searches up, down, left, right for all the stones on the board. If the stones are white it captures them by making them 0, which represents empty.


texts: Is there a GLSL command similar to the discard, but it discards the whole mesh and not just a fragment?


texts: How are objects represented in raymarching shaders

texts: How does one represent geometry in raymarching shader? Say I wanted to pass a tree of SDF primitive shaders. My current idea is to pass texture containing their positions as rgb and type as alpha channel but that seems to be quite crude method which additionaly forces me to use same type of blending between  all objects.


texts: Is it copyright infringement if I make a clone of a game for educational purposes, and upload it on github?

texts: Pacman and Snake Xenzia are common examples, and many universities have programming assignments where you recreate parts of a game (or even the entire game) without copying any of the artwork and design, etc. Is it okay to upload something like this (which was NOT written as a part of a course) under a personal profile on Github? Or will you necessarily have nothing to show for embarking on a project such as this one?


texts: How to prune an AI game tree for a game like Magic?

texts:
I've got a game tree structure for my AI that I need to trim in order to gain some depth.

It is a single-player game of perfect information. A good analogy would be a single-player game of Magic the gathering with an oponnenet that plays no card but automaticaly deals you some damage per turn.

Since I don't have an opponent I don't need either minimax (I can do a pure MAX) or a/b pruning.

I got an evaluation function I can use on nodes if necessary. I'm trying to plan ahead and find good combo's of cards to play.

I dont want to hard-code these combos.

I'm finding hard to prune any branch at all since even a branch with bad-scoring node can potentially lead to a good combo that will completely change the game (you know, like : play 5 shitty cards and be almost dead but the 6th card will grant you a win).

Any idea on how to approach pruning in a game tree like that?


texts: How to simulate projectile path in 3D with Physijs andThree.js?

texts:
I'm new in 3D rendering with WebGL. I would like to simulate a 3D projectile path using Three.js and Physijs.

How could I achieve this?


texts: Calling an android method from Unity3D with a JAR plugin

texts:
I am developing a game with Unity only for Android platform and I am requiring to share content of my game through an intent so I have implemented a JAR plugin according to several tutorials with this code:

package a.b.c;

import android.content.Intent;
import android.os.Bundle;

import com.unity3d.player.UnityPlayerActivity;

public class UnityBridge extends UnityPlayerActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    public void callShareIntent() {
        Intent shareIntent = new Intent (Intent.ACTION_VIEW);
        startActivity(shareIntent);
    }
}

The JAR is located at Assets/Plugins/Android with an AndroidManifest file which override the file created by unity, this is its code:

<?xml version="1.0" encoding="utf-8"?>
<manifest android:theme="@*android:style/Theme.NoTitleBar" android:versionCode="1" android:versionName="1.0" android:installLocation="auto" package="a.b.c"
  xmlns:android="http://schemas.android.com/apk/res/android">
    <supports-screens android:anyDensity="true" android:smallScreens="true" android:normalScreens="true" android:largeScreens="true" android:xlargeScreens="true" />
    <application android:label="@string/app_name" android:icon="@drawable/app_icon" android:debuggable="false">
        <activity android:label="@string/app_name" android:name="com.unity3d.player.UnityPlayerNativeActivity" android:launchMode="singleTask" android:screenOrientation="portrait" android:configChanges="mcc|mnc|locale|touchscreen|keyboard|keyboardHidden|navigation|orientation|screenLayout|uiMode|fontScale">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
                <category android:name="android.intent.category.LEANBACK_LAUNCHER" />
            </intent-filter>
            <meta-data android:name="unityplayer.UnityActivity" android:value="true" />
            <meta-data android:name="unityplayer.ForwardNativeEventsToDalvik" android:value="false" />
        </activity>
        <activity android:name=".UnityBridge"></activity>
    </application>
    <uses-feature android:glEsVersion="0x20000" />
</manifest>

I just copied the manifest created by Unity and added this line:

<activity android:name=".UnityBridge"></activity>

... as you can see.

In the other hand, I have created a C# file in order to launch the share method of the plugin, this is its code:

using UnityEngine;
using System.Collections;

public class BotonCompartir : MonoBehaviour {

    AndroidJavaClass androidClass;

    // Use this for initialization
    void Start () {
        if (Application.platform == RuntimePlatform.Android) {
            AndroidJNI.AttachCurrentThread ();
            androidClass = new AndroidJavaClass ("a.b.c.UnityBridge");
        }
    }

    // Update is called once per frame
    void Update () {
        if (Input.GetMouseButtonDown (0) && Application.platform == RuntimePlatform.Android) {
            androidClass.Call("callShareIntent");
        }
    }
}

... and I have attached it to a gameobject.

When I deploy the apk to an android device nothing happens, so What am I doing wrong? Any other suggestion?

Thank you very much


texts:
I have created simple damage formula based on source percent, which return fixed percent of damage.

DAMAGE_PERCENT = Exp(Log(100) * (1 - (100 - SOURCE_PERCENT) / 150)

Here is the result:

percent[0]: 4.641589
percent[1]: 4.786301
percent[2]: 4.935525
....
percent[98]: 94.04449
percent[99]: 96.97654
percent[100]: 100

How can I make it return same results but with reversed SOURCE_PERCENT value?

So percent[0] should return 100 and percent[100] return 4.641589?


texts:
Main question:
How can I make this possible so that I can press a UI button inside the canvas while the cursor is locked?

Hello, I am creating a 3D video game. I have fully functional character control like walking using WASD keys and view rotation using mouse.

Now the last thing I need is to have cursor in the middle that can click on UI buttons on canvas like this:

https://www.youtube.com/watch?v=PPCwvqIqNxM&feature=youtu.be

I cannot click on UI buttons while the cursor is on locked constantly. So I created the pulse where the cursor will be locked and unlocked with a pulse so I can click on buttons.

This is the code I'm using:

//Inside the Update function.
float Lock = 0.0375f;
timer += Time.deltaTime;
if (timer > 0.02f && timer <= Lock)
{
    Cursor.lockState = CursorLockMode.Locked;
}
else if(timer > Lock)
{
    Cursor.lockState = CursorLockMode.None;
    if(timer >= Lock + 0.1f)
        timer = 0;
}
Cursor.visible = true;

It works, but not 100% proficient.

So, when I start building and run the game, here is what is happening:

https://www.youtube.com/watch?v=Fur6Al4zj3I&feature=youtu.be

What's happening is I cannot click the UI button after building and running the game. The only time I can press the button is when I am moving side by side while hovering over the button, otherwise if I stand still, I cant click the button.

This is the same crud I've been getting when I am designing one thing like a button for example, but when running, the button looks completely different from the designer. Same it applies here, I am running inside the Unity editor works, but when running inside the built game doesn't work like how it's suppose to.

For that, I just need help in what in the world I must do to make it work on both unity editor and built game, maybe I'm doing something wrong with the code? I need help. Any questions, please ask. Thank you.


texts: rotating an object from sourceAngle to destAngle, both 0-359, clockwise or counter clockwise?

texts:
I've got a game object i need to rotate. It's current angle is player.rotation, the destination is targetAngle, both in degress, 0 to 359. I've got a function named rotateDirection(float sourceAngle, float destAngle) that needs to return -1 or 1 depending on whether the shortest way to reach the destination angle would be clockwise or counterclockwise.

For example - for sourceAngle 300 and destAngle 0 the function would return 1 for clockwise.

The solution is most probably going to leave me looking silly, and i usually don't like just asking for code, but my brain is completely broken so please help me with this one :)


texts: How can i add spaces between gameobject when Instantiate?

texts:
void Update()
    {
        if (Input.anyKey)
        {
            foreach (Transform child in go.transform)
            {
                if (Input.inputString == child.name)
                {
                    Instantiate(child);
                }
            }
        }
    }

I want to Instantiate the gameobjects with a space between each one that i will set with public variable. And that the gameobjects position will start from the 0,0,0 of the terrain.

For example like that:


texts: Phaser: Scaling to fill screen, maintain pixel ratio, but not aspect ratio

texts:
I've used libraries in other languages before that provide different types of scaling via viewport types. The best example of what I want is from a library called libgdx for Java, their ScreenViewport.

  The ScreenViewport does not have a constant virtual screen size; it will always match the window size which means that no scaling happens and no black bars appear. A player with a bigger screen might see more of the game than a player with a smaller screen size.

Essentially what I want is to:

Fill the screen meaning that there's no black bars or the sides of the game

Maintain the pixel ratio meaning that every in-game pixel is equal to one pixel on screen, so no stretching

Not maintain aspect ratio meaning that it doesn't matter to my game what the aspect ratio of the game is. Its job is to forget about aspect ratio and follow the above two criteria

The way how I'm achieving this is by using Phaser's EXACT_FIT scaling type so that the canvas automatically resizes to fit the window. Then upon resizing, I update the size of the camera and the game's renderer so that they match the new canvas size.

Here's the code I have in my create function.

this.scale.scaleMode = Phaser.ScaleManager.EXACT_FIT; // Phaser.ScaleManager.SHOW_ALL USER_SCALE

    this.scale.pageAlignHorizontally = true;
    this.scale.pageAlignVertically = true;

    this.scale.setResizeCallback(function () {
        var width = window.innerWidth;
        var height = window.innerHeight;
        console.log('size: ' + width + ', ' + height);
        this.camera.setSize(width, height);
        this.game.renderer.resize(width, height);
    }, this);

It works fantastic in the horizontal axis, but when the window shrinks vertically, there is some vertical stretching of the pixels.

Here's a working example of my issue
http://shooty.us.to/scale/

And here's the code on GitHub, in case it's of any help.
https://github.com/qwertysam/space-game

Thank you for reading, any help is appreciated!

EDIT:

I've isolated the issue, it appears to be that when the game is initially created, the height that I specify is the initial height of the canvas. e.g.

var game = new Phaser.Game(16 * 80, 9 * 80, Phaser.AUTO, '');

Phaser's scaling method allows the canvas to grow in height, but not to shrink in height. The renderer is rendering to a much taller canvas (which goes off-screen) than expected, therefore causing the vertical stretching. Any thoughts on how I can shrink the canvas myself, or would that conflitch with Phaser's ScaleManager? Thanks!


texts: How can I make the player stop at the collision point and not before?

texts:
I am making a Java platform game (I have created many top-down games, but nothing with gravity like a platformer) and I have implemented terminalVelocity, etc.

My problem is that, say when the player is falling at a rate of 8 pixels, I check collision for the player 8 pixels ahead before it moves, and if there is a collision the player does not move. But, say that there are 4 pixels until a block but the player is moving at 8 pixels, the collision detection stops the player because 8 pixels ahead there is a block, but the player hovers because there is a 4 pixel gap.

How would I make the player fall those extra 4 pixels?


texts: spriteBatch.draw is not getting overloaded

texts:
I am following this tutorial from gamefromscratch.com tutorial 11.
I am using libGdx framework in Android studio .

public class OrthogonalTiledMapRendererWithSprites extends OrthogonalTiledMapRenderer {

public OrthogonalTiledMapRendererWithSprites(TiledMap map) {
    super(map);
}

@Override
public void renderObject(MapObject object) {
    if(object instanceof TextureMapObject) {
        TextureMapObject textureObj = (TextureMapObject) object;
            spriteBatch.draw(textureObj.getTextureRegion(), textureObj.getX(), textureObj.getY()); // getting error in this line
    }
}
}

I am getting an unresolved error in the following line

spriteBatch.draw(textureObj.getTextureRegion(), textureObj.getX(), textureObj.getY());

The code in render() method is

public void render () {
    Gdx.gl.glClearColor(1, 0, 0, 1);
    Gdx.gl.glBlendFunc(GL20.GL_SRC_ALPHA, GL20.GL_ONE_MINUS_SRC_ALPHA);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
    camera.update();
    tiledMapRenderer.setView(camera);
    tiledMapRenderer.render();
    }

I am new in game development please help me solve this error.
Thanks in advance


texts: What 2D engine can I use to port my flash game to iOS and Android?

texts: I would like to port my 2D flash game to Android and iOS. Is there any cross platform engine you could recommend? Corona is the only promising one I have found so far.


texts: Find which collider is causing collision (implementing danger zone)

texts:
I have multiple SphereColliders attached to GameObject, one bigger to detect collision danger zone and the other, smaller, for actual collision (both triggers!). When the OnTriggerEnter() how do I find which one of those two caused trigger enter event?

private void OnTriggerEnter(Collider other)
{
    foreach (var collider in GetComponents<SphereCollider>())
    {
        if(isColliding(collider)) //how to find if this particular trigger isColliding ?
        {
            if(collider.radius > 0.5)//smaller or bigger one
               GetComponent<MeshRenderer>().material.color = _dangerColor;
            else handleCollision();
        }
    }

}

Because the accepted answer provides two solutions, it would be in order to specify how I solved the problem. In the end I went for keeping outter collider and doing "manual" overlap test for inner one (since I did not need physics response, it was the lesser evil). It also turned into new feature, it allows me to lerp danger color.


texts:
I am currently developing my first classes in Unreal Engine 4. Coming from using UScript extensively, I'm getting a little bit confused by how typecasting works in pure C++. More specifically, class/object casting.

I am currently putting together a switch statement in MyCustomGameMode which calls upon MyCustomPlayerController for MyCustomPlayerControllerVariable.

The function in question that I am overriding is this one: virtual UClass* GetDefaultPawnClassForController(AController* InController);

Currently I'm trying to call the variable with the following line of code, which I know is incorrect, but I'm not sure why:

Cast<MyCustomPlayerController>(InController).MyCustomPlayerControllerVariable

I am interested in casting the "InController" to MyCustomPlayerController but Cast<MyCustomPlayerController>(InController) doesn't seem to work, what am I doing wrong here?


texts:
I've read this wall jumping question but I'm having trouble implementing it. I've gotten as far as implementing a timer that controls when wall jumping is possible. Right now, if I go up against a wall, then jump, I'll have a timer that will later run out (and then I won't be able to wall jump in mid air).

However, I'm not sure how to implement it. I see two problems here - one is to determine the direction the player should go, and how to cancel out the effects of holding down a directional arrow key and counteracting the velocity I would apply when I jump off the wall. Also, I'm having troubles of determining when I hit another wall, so I can wall jump again.


texts: How can I add banking and rotation to this object manipulation script?

texts:
I have made a drone script that allows user to move in four directions and ascend/descend.
I found a nice tilt snippet which makes the thing bank when it moves.
However, when I include this, the rotation I input using "f" and "h" keys works but the drone snaps back to it's original orientation (not position in space, but the angle of the object on the Y axis).I would like to be able to bank and also rotate the drone, what should I change? Here is the C# script  attached to the drone:

using UnityEngine;
using System.Collections;

public class PlayerController : MonoBehaviour
{
    public float speed;
    public float tilt;
    public float power;

    /**
     * Every update perform tranlations and rotations based on user input.
     * */
    void FixedUpdate ()
    {
        float moveHorizontal = Input.GetAxis ("Horizontal");
        float moveVertical = Input.GetAxis ("Vertical");

        Vector3 movement = new Vector3(moveHorizontal, 0.0f, moveVertical);
        rigidbody.velocity = movement * speed;

        // Add the tilt. (When this line is left out, rotation performs as expected)
        // When it is left in, the drone rotates but snaps back to it's original orientation on key release.
        rigidbody.rotation = Quaternion.Euler (rigidbody.velocity.z, 0.0f, rigidbody.velocity.x * -tilt);

        // Ascend.
        if (Input.GetKey ("t"))
        {
            rigidbody.AddRelativeForce (Vector3.up * power);
        }

        // Descend.
        if (Input.GetKey ("g")) {
            rigidbody.AddRelativeForce (Vector3.down * power);
        }

        // Rotate clockwise.
        if (Input.GetKey ("h"))
        {
            transform.Rotate(0, 5, 0, Space.Self);
        }

        // Rotate anti-clockwise.
        if (Input.GetKey ("f"))
        {
            transform.Rotate(0, -5, 0, Space.Self);
        }
    }
}

Maybe also worth noting that when I leave the tilt line in, any rotation I apply to the drone in transform properties is not applied, when taken out, I can set the starting orientation fine.


texts: Does AndEngine have a way to manage scenes?

texts: Does AndEngine have a way to manage scenes (for example, main splash, menu, options, main game), and should I use a different scene per activity?


texts: Is there any way to earn money with an open source game?

texts: I know FreeToPlay games are financed by advertisements and/or selling additional content, but what about an Open Source single player game to which several people have contributed? And how can a fair sharing be determined?


texts:
I have the following problem:

In a 2D game the screen can scroll in any of the 4 directions. Basically, the center of the screen during scrolling moves from (x1,y1) to (x2, y2) whereby (x1,y1) is the current focus and (x2, y2) is the desired focus. The latter changes frequently depending on what happens in the game.

At the moment, I only scroll if the distance d between (x1,y1) and (x2, y2) is above a certain threshold and also I am scrolling the faster the larger d is.

This already results in a quite smooth movement of the screen but I am still not completely happy with it. I was wondering if there are any standard or best-practice approaches to the problem of smoothing the path of the screen? I can imagine something with b-splines but I have no concrete idea of how to approach this.


texts: glsl Expected token ')', found 'identifier' with function mix

texts:
I have a Fragment shader that contains:

[...]
float c = texture2D(tex, tc).a;
float alpha = mix(0.0f, 1.0f, c);
gl_FragColor = vec4(1, 1, 1, alpha) * color;

This works fine on my desktop and Nexus 5. However I get an exception while running on a Wiko mobile:

0:22: L0001: Expected token ')', found 'identifier'

Line 22 is the line containing the mix function.

What I'm doing wrong?


texts: Good practices in data management in big projects?

texts: I am making a game using Unity ECS. All the data I have: Items, Defined Interactions, Monsters etc. are stored as .json. What are good practices to manage this data? For now I am storing all those objects in dictionary fashion where keys are "ModName.ObjectType.ObjectTag" for example "Core.Item.Sword1". All parts of the game has access to this data bank because it's static. I am not sure if what I am doing is right and if there could be problems that emerge. Overall, what are good practices for managing assets in game which should be moddable?


texts: Unity - Open offline web pages in a browser window by clicking a button?

texts:
I currently have a Unity game where the user can click on buttons to open up web pages, I use the following script on the button for this...

public void OpenURL(string url)
         {
             Application.OpenURL(url);
         }
     }

The URL is then put into the box that this script produces in the inspector and works perfectly.

However what I would now like to do is open the pages OFFLINE instead, so people without an internet connection can see the information.
The way I envisage doing this is to save the web pages so they can be opened up locally in a browser offline.
However I am stumped as to how to tell the button to open the relevant file and open it - is there a way of doing this?  Maybe save the web page file in a local folder and point the button to that file?

This would be way easier that the only alternative I can think of - to save each web page as an image and have them open up as an image popup within the game as opposed to in the browser (there are a lot, so I would rather not have to do this!)

This is for PC Standalone only.

Any help would be greatly appreciated.

Thanks in advance!


texts: In the Direct3D 9 Effect API, how do you find the texture variable linked to a sampler?

texts:
In Direct3D 9 effect files you can write a sampler state that specifies a texture variable to use, like

Texture2D g_texSkyDome;
SamplerState g_samplerSkyDome
{
    Texture = <g_texSkyDome>;
    // ...other sampler states...
};

Using the ID3DXEffect API, is it possible to extract the texture variable assigned to a given sampler state variable?  I've been searching the docs but can't find anything about this.


texts: Udp VS Tcp connection for a platformer multiplayer

texts:
Tcp is connection based so it's really good for chat or login or anything that needs reliability. Udp should be used for lots of small packets like position packets... The problem is that in a game like what I'm doing right now (terraria like), I can't decide what to use and how to use it properly. I though about using both at the same time, but can't find a way to ensure the udp "connection" will work.

If I were to choose UDP, is there a way I could make a "connection" out of it? to rely on it for login or chat messages?

And if I were to use TCP, would there be a way to speed it up?

More info : I'm doing this in C#.NET with XNA (I know it's no longer developped but I like it :P).
I would also like to use Serialized objects (.Net BinaryFormatter), but it uses streams, and stream are only available in TCP... which makes it more attractive...

Thanks a lot!


texts: Are 3D textures used for ground tiles in 2.5D games?

texts:
In an isometric system, each tile can be painted with texture. Normally, (if I recalled the technical term) the fastest method to paint these ground tiles with appropiate texture is to use something like UV mapping. However, that is not what I have seen on most of isometric tile-based game (such as final fantasy tactics). For example, if I map the texture onto each grid, then the texture would appears to be flat. Now, in modern day game, each tile may have some part sprouting out (for example, grass). What I want to ask is how should I implements the isometric system such that this feature is supported?

The next problem is, if I implement such feature, then I have to make change to the art process too--- UV texture mapping will not work anymore. My question is, what change would I have to make to the art process? How would an artist color a 3D isometric tile?

Basically, I just want to know how this isometric system will work out for both programmer and artists. The grid system seems to require high degree of coordination between programmer and artist.

EDIT: Rephrase the question


texts: Double jump, without allowing two jumps after falling down a cliff

texts:
I created a script that allows the player to double jump, which works like a charm.

The problem is if the player walks off a cliff, they will still be able to jump twice. But that isn't how double jump works, right?

Can someone tell me how to make it so that if the player falls down a cliff, they will be able to jump only once?

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

public class PlayerController : MonoBehaviour
{
    private Rigidbody2D rb;
    private Animator anim;

    private float movementInputDirection;

    public float movementSpeed = 10f;
    public float jumpForce = 16f;

    public int amountOfJumps = 1;
    private int amountOfJumpsLeft;

    private bool isFacingRight = true;
    private bool isWalking;
    private bool isGrounded;
    private bool canJump;

    public float groundCheckRadius;
    public LayerMask whatIsGround;

    public Transform groundCheck;

    void Awake()
    {
        rb = GetComponent<Rigidbody2D>();
        anim = GetComponent<Animator>();
    }

    void Start()
    {
        amountOfJumpsLeft = amountOfJumps;
    }

    void Update()
    {
        CheckInput();
        CheckMovementDirection();
        UpdateAnimations();
        CheckIfCanJump();
    }

    private void FixedUpdate()
    {
        ApplyMovement();
        CheckSurroundings();
    }

    private void CheckMovementDirection() //flips sprite
    {
        if (isFacingRight && movementInputDirection < 0)
        {
            Flip();
        }
        else if (!isFacingRight && movementInputDirection > 0)
        {
            Flip();
        }

        if(rb.velocity.x != 0)
        {
            isWalking = true;
        }
        else
        {
            isWalking = false;
        }
    }

    private void UpdateAnimations()
    {
        anim.SetBool("IsWalking", isWalking);
    }

    private void CheckInput()
    {
        movementInputDirection = Input.GetAxisRaw("Horizontal");

        if (Input.GetButtonDown("Jump"))
        {
            Jump();
        }
    }

    private void ApplyMovement() //player movement
    {
        rb.velocity = new Vector2(movementSpeed * movementInputDirection, rb.velocity.y);
    }

    private void Flip()
    {
        isFacingRight = !isFacingRight;
        transform.Rotate(0f, 180f, 0f);
    }

    private void Jump()
    {
        if (canJump)
        {
            rb.velocity = new Vector2(rb.velocity.x, jumpForce);
            amountOfJumpsLeft--;
        }
    }

    private void CheckSurroundings()
    {
        isGrounded = Physics2D.OverlapCircle(groundCheck.position, groundCheckRadius, whatIsGround);
    }

    private void CheckIfCanJump()
    {
        if (isGrounded && rb.velocity.y < 0.01)
        {
            amountOfJumpsLeft = amountOfJumps;
        }

        if (amountOfJumpsLeft <= 0)
        {
            canJump = false;
        }
        else
        {
            canJump = true;
        }
    }

    private void OnDrawGizmos()
    {
        Gizmos.DrawWireSphere(groundCheck.position, groundCheckRadius);
    }
}


texts: Translate camera position toward camera orientation

texts:
I have a camera position (Vec3) and camera horizontal/vertical angle. Now I want to translate my camera position toward the current camera orientation - what is the best way to do that? I am sure it's simple but the logic escapes me.

(I am using GLM math lib btw)


texts: What are some techniques for designing fun, challenging Mario-style platformer levels?

texts:
I have everything I need to make a Mario type game. I just have no idea how to design the levels to make it challenging or fun. Any tips?

The only way to kill enemies is by jumping on them, so I thought it would be too hard to make a boss. I was just going to make the last level long. Is this a bad idea?


texts: Detecting first or second Mouse Button Release?

texts:
I want to know how to detect if the user has released the mouse button the first time, or the times after that:

Pseudo-Code:

 if *first* (Input.GetMouseButtonUp(0))
   {
       do something
   }

 if *second, third, fourth..etc.* (Input.GetMouseButtonUp(0))
   {
       do something else
   }

I really have no idea on how to accomplish this. I'm sure it's pretty simple though!


texts: Artifacts when draw particles with some alpha

texts:
I want to draw in my game some particles. But when I draw one particle above another particle, alpha channel from this above "clear" previous drawed particle.
I set in OpenGL blend in this way:

glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA );

My fragment shader for particle is very simple:

precision highp float;
precision highp int;
uniform sampler2D u_maps[2];
varying vec2 v_texture;
uniform float opaque;
uniform vec3 colorize;
void main()
{
    vec4 texColor = texture2D(u_maps[0], v_texture);
    gl_FragColor.rgb = texColor.rgb * colorize.rgb;

    gl_FragColor.a = texColor.a * opaque;
}

I attach screenshot from this:

Do you know what I made wrong ?

I use OpenGL ES 2.0.


texts: lag compensation for slow bullets (opposing players perspective)

texts:
I have figured out how the server is suppose to "rewind" for bullet collisions so that when you hit a player on your screen, the server will also say you hit them. However, when you press a key to shoot on your computer, it will take x ms until the opponent sees that you shot. by then, the moving opponent will be past the position that you fired while the sever says that they were still hit anyway.

What you will see: You aim and shoot at them, the bullet hits them and they take damage (this works out perfectly so far)

What they will see: They are moving and you shoot at them. the bullet trails behind them and misses, flying off into the distance. Yet they still take damage.
How can this be fixed?


texts:
I was following this tutorial to understand using custom shaders : http://www.cocos2d-x.org/wiki/User_Tutorial-Realistic_looking_animated_real-time_clouds

I understand that CC_Time is Cocos2d-x built-in uniform vec4-object that holds different versions of time in it's components.
Can someone please explain or point me to a resource so that I can understand what are its different components. Thanks.


texts: Problem with Animating on local position Unity

texts:
Currently, I am having a Cube that needs to be animated to roll on its edge. Using unity built-in animation feature, I created 4 animations (RotateUp, RotateDown, RotateLeft, RotateRight). At the end of each animation I would put an Event to call a method on my script. To be able to move the object every time the animation is played, I put the cube with animator attached inside a parent object.
Below is the script attached to my cube.

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

public class RedCubeBehavior : MonoBehaviour
{

    Animator anim;

    bool isMoveTriggered = false;

    void Start()
    {
        anim = gameObject.GetComponent<Animator>();
    }

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.UpArrow))
        {
            MoveUp();
        }
        else if (Input.GetKeyDown(KeyCode.DownArrow))
        {
            MoveDown();
        }
        else if (Input.GetKeyDown(KeyCode.LeftArrow))
        {
            MoveLeft();
        }
        else if (Input.GetKeyDown(KeyCode.RightArrow))
        {
            MoveRight();
        }

        if (isMoveTriggered)
        {
            if (IsBackToIdle())
            {
                transform.parent.position = transform.position;
                transform.localPosition = Vector3.zero;
                isMoveTriggered = false;
            }
        }
    }

    void AnimationFinished()
    {

        anim.Play("IdleState");

    }

    public void MoveUp()
    {
        if (isMoveTriggered)
        {
            return;
        }
        else
        {
            Debug.Log("MoveUp");
            isMoveTriggered = true;
            anim.Play("RotateUp");
        }
    }

    public void MoveDown()
    {
        if (isMoveTriggered)
        {
            return;
        }
        else
        {
            Debug.Log("MoveDown");
            isMoveTriggered = true;
            anim.Play("RotateDown");
        }
    }

    public void MoveLeft()
    {
        if (isMoveTriggered)
        {
            return;
        }
        else
        {
            Debug.Log("MoveLeft");
            isMoveTriggered = true;
            anim.Play("RotateLeft");
        }
    }

    public void MoveRight()
    {
        if (isMoveTriggered)
        {
            return;
        }
        else
        {
            Debug.Log("MoveRight");
            isMoveTriggered = true;
            anim.Play("RotateRight");

        }
    }

    bool IsBackToIdle()
    {
        return anim.GetCurrentAnimatorStateInfo(0).IsName("IdleState");
    }

}

Every time the arrow key is pressed the object would rotate but in the end when AnimationFinished() is called, the cube would just roll back to its starting position (because of playing IdleState). It will only work (the object didn't return to its starting position) if I pressed the arrow twice quickly.

I've tried to not call the IdleState (which is only an empty state), but what happens next is it just won't play another animation again when triggered.

What should I do in order to get it work without having to press the key twice?


texts:
Often "singletons" are problematic for testing, so with my next game I'm trying my best to avoid them. But there is bunch of data (configuration or game state information) that different parts of my game require to function. So far I've used events (publish/subscribe) to pass around for example keyboard/touch actions.

Is it a bad idea to try to do the same with configuration/game state? So for example user changes some configuration parameter and instead of all those that need it doing something like ConfigurationSingleton.getParam("someparam") my event handler would call all those interested in param changes with SomeSubscriber.paramChanged("someparam", "new value").

How do you usually make available this kind of "global state/configuration" data in games?


texts: Unity: Trying to add an in-scene 'press E to open' tag as UI element

texts:
In Unity 5.4.1 I'm trying to add a tag that says 'press E to open' to a door as you approach it. I've got a RayCast pointing forward from the player, detecting the door and , connected to my PlayerController, I've got a copy of a prefab GameObject which itself contains a Text UI element. The GameObject _interactionTag is instantiated into the scene when the player is close enough.
But I'm having some trouble getting it to display correctly in the scene and I'm not sure why.

Here are the relevant parts of my PlayerController:

public class PlayerController : MonoBehaviour {
    public Canvas _canvas;
    private Vector3 _fwd;
    private RaycastHit _hit;
    public GameObject interactiveTag;
    private GameObject _interactiveGameObject = null;
    private GameObject _interactionTag;

    void Update () {
        _fwd = transform.TransformDirection(Vector3.forward);
        if (Physics.Raycast(transform.position, _fwd, out _hit, 3)) {
        if (_hit.distance<1) {
            _interactiveGameObject = _hit.collider.gameObject;
            GameObject _interactionTag = (GameObject) Instantiate(interactiveTag, _interactiveGameObject.transform.position, _interactiveGameObject.transform.rotation);
           _interactionTag.GetComponentInChildren<Text>().text = _interactiveGameObject.GetComponent<IsInteractive>().interactionText; // this gets a text string from the door 'press E to open'
           _interactionTag.transform.SetParent(_canvas.transform, false);
        }
    }
}

In game, the _interactionTag is appearing - though it's backwards and does not appear attached to the door. Also is any of this the best way of getting the 'press E to open' tag to appear attached to the center of the door? I'm beginning to wonder if what I'm doing is best practise.
Thanks for any help.


texts: How to increase the selectable size of an object for dragging

texts:
I am currently dragging a gameobject like this.

   Vector3 screenSpace;
   Vector3 offset;
   void OnMouseDown(){

 //translate the cubes position from the world to Screen Point
 screenSpace = Camera.main.WorldToScreenPoint(transform.position);
 //calculate any difference between the cubes world position and the mouses Screen position converted to a world point
 offset = transform.position - Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x,Input.mousePosition.y, screenSpace.z));
 }

  private float speed = 7.5f;

  void OnMouseDrag(){
     Vector3 curScreenSpace = new Vector3(Input.mousePosition.x, Input.mousePosition.y,    screenSpace.z);
     Vector3 curPosition =  Camera.main.ScreenToWorldPoint(curScreenSpace) + offset;
     transform.position = curPosition;
 }

Sometimes a user doesn't click directly on an object so is there a way that if a user is between 3-7 pixels off, it still counts as a click and drag? Any help is appreciated.


texts: Recognising when a user is clicking below a particular sprite

texts:
I have a game, built using pixi.js, where I want to run some code every time the user presses below a certain sprite. I am handling the press event using hammer.js. The problem is that the y attribute of the sprite and the y attribute of the user’s touch event don’t  match what I can see on my screen.

As, an example, consider the code below:

if (touchPointer.clientY > this.children.marker1.position.y) {
  console.log("******* Clicked Below the Line ********: ");}
else{
  console.log("******* Clicked Above the Line ********: ");}

The problem I have is that, when I click slightly above the sprite, the first section of code will run (which prints “Clicked Below the Sprit”), even though on the screen, I can clearly see the pointer is above the sprite.
I am guessing, what’s going on is that the y positions for the pointer and the sprite are being calculated differently, but I don’t know how to go about ensuring they’re calculated consistently, so I can properly compare sprites against the pointer. Any suggestions?


texts:
I'm trying to build a space game and one of the key parts is building on spherical planet. I want the buildings to be build on a grid (some building are 1x1, some 6x4,..., kinda like StarCraft). My problem is, I can't seem to find a way to build the buildings near poles, while maintaining properly oriented grid.

I think that joining cells near poles is a bad idea, because there will be parts, where 1 cell is continued by 2 cells and it will be impossible to build over these parts.

Any ideas how to solve this? Should I forget about the grid and just check, if the building collides with other buildings?


texts: Microfacet model - BRDF obtain extreme values at grazing angles

texts:
I've been trying to replicate the result of this paper (linked directly to PDF paper, but you don't need to read it to give an answer) and encountered a problem with the BRDF according to the following well-known formula:

where F,G,D are Fresnel reflection, Shadow masking, and microfacet distribution respectively. The trouble I encounter is in the denominator, where i is the incident ray, n is the surface normal, and o is the angle of view.

Just by looking at the formula, probably you can already guess what happen when the ray comes from grazing angle: |in| approach zero, and if I look at it also at grazing angle then |on| would also approach zero. And as much as I hoped that FGD would approach zero faster than the denominator, it doesn't. (I used GGX distribution, but the same thing happen to Beckmann or Phong) The resulting BRDF I calculated is something completely different from not only the paper that I'm trying to replicate, but also from most other BRDF.

(strong peak at grazing angle, I did it for refraction case but it's the same for reflection)

(result from the paper, most brdf have this shape)

I double checked D,F and G so it can't be any of those, but then what went wrong? Has anyone tried this BRDF model and encountered a similar problem?


texts: OpenGL Textures not sitting right on model

texts:
I have been trying to get textures loading properly onto my models but to no avail. I'm using picopng to load my images.

Here is my code.
[Texture code]

std::vector<unsigned char> buffer, image, aaa;

std::ifstream file(location.c_str(), std::ios::in | std::ios::binary | std::ios::ate);
std::streamsize size = 0;
if (file.seekg(0, std::ios::end).good()) size = file.tellg();
if (file.seekg(0, std::ios::beg).good()) size -= file.tellg();
if (size > 0)
{
    buffer.resize((size_t)size);
    file.read((char*)(&buffer[0]), size);
}
else {
    buffer.clear();
}
unsigned long w, h;
int error = decodePNG(image, w, h, buffer.empty() ? 0 : &buffer[0], (unsigned long)buffer.size());

if (error != 0) std::cout << "error: " << error << std::endl;

glEnable(GL_TEXTURE_2D);
GLuint id;
glGenTextures(1, &id);
glBindTexture(GL_TEXTURE_2D, id);

glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);

glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);

glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, &image[0]);

glBindTexture(GL_TEXTURE_2D, 0);

glGenerateMipmap(GL_TEXTURE_2D);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
float mipMapingAffectivness = 0.4f;
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_LOD_BIAS, mipMapingAffectivness);

Any advice?

[Update]
I have tried flipping the image but to no avail, I have tried all 8 orientation variations and non seem to work.


texts: Distribute XNA as a standalone zip or exe (no installer needed)?

texts:
I want to know how would I distribute my XNA such that it won't distribute as an installer/setup files? I just want a zip of files such that when the user can run instantly after extracting into a folder. I am making a small prototype of some functionalities, and I would like my co-workers to visually see it so that we can communicate better. However, this must means I must frequently release my projects (as I update it frequently), so I want to know a way to produce easy-to-launch distribution.

I tried to turn Build option in Visual Studio to Release, and try copy and zip all the files inside Release folder. However, when I zip it and send to my coworkers, they said nothing comes up after they open the exe.


texts: How do I ensure consistent behaviour when using Unity's Collider2Ds for triggers and collisions?

texts:
I am experiencing inconsistent behavior using Unity's 2D Physics engine and their Collider2Ds to detect collisions and triggers on my projectiles. I will classify it into two problems. The first is that occasionally the projectile will pass through walls/objects it should collide with. The second is that occasionally the projectile will pass through enemies that it should hit without triggering. I will try to elaborate in detail below.

A projectile is organized into a container Projectile GO and two children GO: a PhysicsColliders GO and a HitBoxColliders GO.

The PhysicsCollidersGO job is to hold the colliders that define the solid regions of the projectile using Collider2D components. It's GO is on a Projectile layer which is set to collide with other solid layers such as the ones my walls are on. Walls are static colliders.

The HitBoxCollidersGO job is to define the a HitBox area. It's GO is on a HitBox layer and also uses Collider2D components that are set to be triggers. A HitScript on the GO listens for OnEnterTrigger.

Projectiles are set in motion by setting the velocity of the RigidBody once upon firing.

Here is a visual of the structure:

 ProjectileGO
  - PhysicsCollidersGO
  - HitBoxCollidersGO

Here are descriptions of the GameObjects and their components:

 ProjectileGO
   - RigidBody2D Component (collisionDetectionMode is set to Continious)

 PhysicsCollidersGO (Layer is set to Projectile)
   - BoxCollider2D Component

 HitBoxCollidersGO (Layer is set to HitBox)
   - BoxCollider2D Component (IsTrigger is set)
   - HitScript Component

Problem 1. Projectiles will sometimes not collide with walls/solid objects/etc...

Problem 2. Projectiles will sometimes not trigger a hit.

What could be causing these inconsistencies?  How can ensure that collisions and triggers will consistently behave correctly?


texts:
I have a Canvas that has multiple UI Panels in it for an inventory, crafting, etc. To open these panels I currently have a monobehaviour class on the Canvas with methods like OpenInventory(), etc.

For every item within the inventory I use ScriptableObjects. However, some items open the crafting panel when right clicking, I created a class that extends the Item class and added a method to it that gets added to the inventory slot and gets called when right clicking that item.

Because the monobehaviour on the Canvas is an instance, I can't access it from a ScriptableObject.

Long story short, is there a way to open a UI panel from a ScriptableObject? If not, what would be the best way to fix this issue?


texts:
I'm trying to change the texture of an Image actor on my Scene2D stage, however I can't seem to get it working. It seems like setDrawable() doesn't really do anything.

For example, this will make the texture of the Image cookie.png:

Image itemImage = new Image(new TextureRegionDrawable(new TextureRegion(new Texture(Gdx.files.internal("cookie.png")))));
itemImage.setPosition(10, 10);
getStage().addActor(itemImage);

However, this will not:

Image itemImage = new Image();
itemImage.setPosition(10, 10);
itemImage.setDrawable(new TextureRegionDrawable(new TextureRegion(new Texture(Gdx.files.internal("cookie.png")))));
getStage().addActor(itemImage);

Am I missing something?


texts: I created a house in blender which is a big cube with the upper face intended and pulled down back to the ground. The floors are other boxes and windows and doors are cut out using a boolean modifier. The problem is that the character controller from the Unity standard assets seems to get stuck between the floors and the walls. I have seen that counter strike maps are mostly not made out of cubes but a lot of planes put together. Is that the proper way to model walkable buildings?


texts: Are there any serious advantages for C++ compared to C?

texts:
so I know a little bit about C (read like a few university level textbooks on it, I am not an experienced programmer or anything) and now I would like to learn the ropes of the Unreal engine to fidle with it an make my first 3D game :P (I know it's a huge step easier said than done but I just want to go with it)
My question is about how wise would it be to stuck with what I already know and built upon it?
Will I hit soon some nasty walls while trying to make things work using C should I instead use C++ or will I be fine? In other words does C++ will make my life easier or can do things I wouldn't be able to do with C or that I needed serious puzzlesovling skills and much bigger hardware level knowledge in order to overcome them while using C?
Long story short should I invest more time expanding what I know in C or should I start learning C++ instead which would save me time and bring me the most comfort?


texts:
Ive been programing a C++ game/server for the past year.  I have been using MYSQL for character logins, items, monsters, etc, etc. (im on windows).  My question is, what are some of the databases that some big time developers use.  IE. Battle.net, Diablo II, Diablo III, mythos, hellgate , etc, etc, etc.  Do they have their own database they built?  Or do they use an existing framework for logins, and character transfers.

I do know that in diablo II, they use character files to to transfer characters into the game world.  But what about the login into battle.net.

Would it be wiser for me to stick with MYSQL, or is there something out there faster and more stable, or should I create a login type of system that looks through a file to see if you provided the correct password.

Can't wait to get some replies.  Thanks!

PS.  Currently the framework is much like battle.net, where you login into a lobby, create, and join games.  The game server/lobby server are different servers too.  So im just wondering about the lobby server for logins because I'm expecting several hundred thousand connections/logins.


texts: Where do I start if I want to independently learn game graphic design?

texts:
I want to learn how to create custom graphics, not use freely available resources. But I have been looking around for articles or tutorials on how to start with 2D game design in general, and I can't seem to find a good starting point — books or otherwise. I mostly come across resources for those that have had formal studies in graphic design (advanced stuff), but I won't have the luxury of formal studies for a good while (if at all). On the other hand, I find resources for learning the programming side of things, but not on how to create the graphics you'll manipulate.

Are there any good resources for learning game oriented graphic design? Specifically 2D, which is the one I'm most interested in, but 3D is also welcome.


texts:
I'm trying to render a skybox with a cubemap on it and to do so I'm using DDS Texture Loader from DirectXTex library. I use texassemble to generate the cubemap (texture array of 6 textures) into a DDS file that I load at runtime. I generated a cube "dome" and sample the texture using the position vector of the vertex as the sample coordinates (so far so good), but I always get the same face of the cubemap mapped on the sky. As I look around I always get the same face (and it wobbles a bit if I move the camera). My code:

//Texture.cpp:

    Texture::Texture(const wchar_t *textureFilePath, const std::string &textureType) : mType(textureType)
    {
        //CreateDDSTextureFromFile(Game::GetInstance()->GetDevice(), Game::GetInstance()->GetDeviceContext(), textureFilePath, &mResource, &mShaderResourceView);
        CreateDDSTextureFromFileEx(Game::GetInstance()->GetDevice(), Game::GetInstance()->GetDeviceContext(), textureFilePath, 0, D3D11_USAGE_DEFAULT, D3D11_BIND_SHADER_RESOURCE, 0, D3D11_RESOURCE_MISC_TEXTURECUBE, false, &mResource, &mShaderResourceView);
    }

// SkyBox.cpp:

void SkyBox::Draw()
{
    // set cube map
    ID3D11ShaderResourceView *resource = mTexture.GetResource();
    Game::GetInstance()->GetDeviceContext()->PSSetShaderResources(0, 1, &resource);

    // set primitive topology
    Game::GetInstance()->GetDeviceContext()->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);

    mMesh.Bind();
    mMesh.Draw();
}

// Vertex Shader:

cbuffer Transform : register(b0)
{
    float4x4 viewProjectionMatrix;
};

float4 main(inout float3 pos : POSITION) : SV_POSITION
{
    return mul(float4(pos, 1.0f), viewProjectionMatrix);
}

// Pixel Shader:

SamplerState cubeSampler;
TextureCube cubeMap;

float4 main(in float3 pos : POSITION) : SV_TARGET
{
    float4 color = cubeMap.Sample(cubeSampler, pos.xyz);
    return color;
}

I tried both functions grom DDS loader but I keep getting the same result. All results I found on the web are about the old SDK toolkits, but I'm using the new DirectXTex lib.


texts:
So I have an object that has a handle attached to it, the player is supposed to rotate this handle. For that, I'm taking in the horizontal and vertical axis of a controllers analogue stick and transform these values into degrees, which I then use to rotate the object.
The problem is that I can't seem to completely block out the possibility of rotating the handle counterclockwise, as the player is only supposed to rotate it clockwise. What happens is that every couple of frames while I try rotating counterclockwise it detects a clockwise rotation, executing my according code, even though I was rotating counterclockwise consistently.
The principles I use to determine which direction the rotation is going is done by comparing the input angle of the last frame to the current input angle, like:
// Variant 1:
var inputAngle = Mathf.Atan2(x, y) * Mathf.Rad2Deg;

float angleDifference = inputAngle - previousAngle;
if (angleDifference > 180f) angleDifference -= 360f;
if (angleDifference < -180f) angleDifference += 360f;

if (Mathf.Sign(angleDifference).Equals(-1))
{
// Counterclockwise rotation
}
else
{
// Clockwise rotation
}

// ...

previousAngle = inputAngle;

In another attempt, I tried to do this comparison by simply checking if my current angle is larger than my previous one while having the input transformed in a 0° to 360° range and also handling the overflow from going back to 0° from 360°, which did not work consistently either.
So I tried to see what the values are giving in this faulty case, but what this told me was simply that the values are not as I expected them to be, as the current angle should be smaller than the previous one while rotating counterclockwise, in those cases and I can't figure out why or how to prevent it?

So I guess in the end my question would be how can I consistently prevent a player from rotating counterclockwise by reading a controller's analogue stick input.


texts: How to increase the rotation of a quaternion by a percentage of X % in a Unity script?

texts:
There is a simple way to increase the rotation described by a quaternion by a percentage X?

Sorry, but in the documentation of Unity3D I found nothing and I have a poor knowledge on the topic.


texts: Online RTS Game Architecture for Mobiles

texts:
We came up with an idea for a real-time strategy game for mobile devices that can play with other players over a network. I'm trying to plan out the architecture/protocol required for such as system. Some other related questions (1,2) mention that P2P is the way to go for RTS games. The problem is that most mobile phones cannot open TCP ports to allow incoming connections, so a central server would be required to relay messages between the players. Another issue that is mentioned on the linked questions is the difference in floating point operations and random number generators, etc among different platforms (Our game would run on iOS and Android for example) so running the game simulation on each device may not be optimal. I could run the game simulation on a server and have it broadcast updates, but simulating/broadcasting up to 200 units per game would be quite expensive especially when multiple people are using the same server to play games. The server's performance might drop significantly with more than a few hundred people using it.

I'm currently thinking the central server would be the best method, but would require a lot of server power. I'm looking for any suggestions on a architecture/protocol that would work for this game and any insight on the issues I mentioned with existing protocols.


texts: Exported FBX Blender Model not showing up in XNA

texts:
I really do apologise if this question has been asked before, but I recently created a model in Blender 2.63, exported it to an FBX file, and tried to display it in XNA (using 4.0 Refresh), but all that shows up is the standard XNA blank screen. My code for drawing the model is:

    void RenderModel(Model model, Matrix world, Matrix view, Matrix projection)
    {
        foreach (ModelMesh mesh in model.Meshes)
        {
            foreach (BasicEffect fx in mesh.Effects)
            {
                fx.World = world;
                fx.View = view;
                fx.Projection = projection;
                //fx.Texture = untagged;

                //fx.EnableDefaultLighting();
            }

            mesh.Draw();
        }
    }

where

    world = Matrix.CreateTranslation(Vector3.Zero);
    view = Matrix.CreateLookAt(new Vector3(0, 0, 10), Vector3.Zero, Vector3.UnitY);
    projection = Matrix.CreatePerspectiveFieldOfView(MathHelper.ToRadians(45), 800f / 600f, 0.1f, 100);

The above code worked for some other models I tried, so I'm pretty sure it's something wrong with the exported model. I exported the model from Blender using the XNA strict settings, and there are no animations, just a texture, which seems to be connected properly to the FBX from the text in the FBX file.

If anyone can tell me how I can create a simple model in Blender and make it usable for XNA, that would be great. Thanks a lot!

EDIT: Added program versions for Blender and XNA


texts:
I've got a JAVA based game with an OpenGL rendering front that is drawing a large amount of sprites every frame (during testing it peaked at 700). Now this game is completely unoptimized. There is no spatial partitioning (so a sprite is drawn even if it isn't on screen) and every sprite is drawn separately like this:

graphics.glPushMatrix();
{
    graphics.glTranslated(x, y, 0.0);
    graphics.glRotated(degrees, 0, 0, 1);

    graphics.glBegin(GL2.GL_QUADS);

    graphics.glTexCoord2f (1.0f, 0.0f);
    graphics.glVertex2d(half_size , half_size); // upper right

    // same for upper left, lower left, lower right
    graphics.glEnd();
}
graphics.glPopMatrix();

Currently the game is running at +-25FPS and is CPU bound. I would like to improve performance by adding spatial partitioning (which I know how to do) and sprite batching. Not drawing sprites that aren't on screen will help a lot, however since players can zoom out it won't help enough, hence the need for batching. However sprite batching in OpenGL is a bit of mystery to me. I usually work with XNA where a few classes to do this are built in. But in OpenGL I don't know what to do.

As for further optimization, the game I'm working on as a few interesting characteristics. A lot of sprites have the same texture and all the sprites are square. Maybe these characteristics will help determine an efficient batching technique?


texts: How to add a falloff (transparency) to projector shader in Unity?

texts:
I am new to Unity shaders and I was wondering if it was possible to add a falloff variable to control the transparency of the projected color. Here is the shader code :
Shader "Projector/Tattoo" {
    Properties {
        _Color ("Tint Color", Color) = (1,1,1,1)
        _Attenuation ("Falloff", Range(0.0, 1.0)) = 1.0
        _ShadowTex("Cookie", 2D) = "white" {}
    }

    Subshader {
        Tags {
            "RenderType" = "Transparent"
            "Queue" = "Transparent+100"
        }
        Pass {
            ZWrite Off
            Offset -1, -1

            Fog{ Mode Off }

            ColorMask RGB
            Blend OneMinusSrcAlpha SrcAlpha

            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag
            #pragma fragmentoption ARB_fog_exp2
            #pragma fragmentoption ARB_precision_hint_fastest
            #include "UnityCG.cginc"

            struct v2f
            {
                float4 pos : SV_POSITION;
                float4 uv : TEXCOORD0;
            };

            sampler2D _ShadowTex;
            float4x4 unity_Projector;
            float4 _Color;
            float _Attenuation;

            v2f vert(appdata_tan v)
            {
                v2f o;
                o.pos = UnityObjectToClipPos(v.vertex);
                o.uv = mul(unity_Projector, v.vertex);
                return o;
            }

            half4 frag(v2f i) : COLOR
            {
                half4 tex = tex2Dproj(_ShadowTex, i.uv);
                tex.a = 1 - tex.a;
                if (i.uv.w < 0)
                {
                    tex = float4(0,0,0,1);
                }
                tex = _Color * tex;
                return tex;
            }
            ENDCG
        }
    }
}


texts: Destroying copy of DontDestroyOnLoad GameObject?

texts:
I have a Main Menu with level selecter up to 5 different scenes on one Map.
I also have a MenuManager which doesn't get destroyed between the scenes to gather the bool information of level finished or not.
When I start the game and change for example level 1 and move back to the Main Menu again the MenuManager gets copied. I tried this at first:

  public static GameObject _menuInstance;

void Awake()
{
    if (_menuInstance == null)
    {
        _menuInstance = this.gameObject;
    }
    else
        Destroy(gameObject);
}

My problem with that is that the copied GameObject that get's destroyed is the wrong one.

This is the copy that gets created after I switched the scenes and back to Main Menu.

This is the original MenuManager that should be the _menuInstance Object and the other one should be destroyed.

How can I not delete the original one and delete the one without the references?

I come up with something but I am not sure if this is the right way to do this.

    //I changed the code in the Awake() function to
    void Awake()
{
    if (_menuInstance == null)
    {
        _menuInstance = this.gameObject;
    }
}
//I checked one of the missing references to be null and then destroy the fake copy.
Update()
{
   if(_startTheGame == null)
     Destroy(gameObject);
}


texts: Using heavyweight ORM implementation for light based games

texts:
I'm just about to engulf myself in an MVC-based/Component architecture in C#, using MySQL's connector/Net for the data storage, and probably some NHibernate/FluentNHibernate Object-relational-mapping to map out the data structure. The goal is to build a scalable 2D RPG.

Then I think about it...and I can't help but think this seems a little "heavy weight" for a 2D RPG, especially one which, while I plan to incorporate a lot of functionality and entertaining gameplay, may be ported to something like Windows Phone or Android in the future.

Yet, on the other hand even a 2-Dimensional RPG can become very complicated, and therefore must incorporate a lot of functionality. While this can be accomplished with text/XML/JSON for data storage, is there a better way? Is something such as Object-Relational-Mapping useful in such an application?

So, what do you think? Would you say that there is a place for such technologies? I don't know what to think...


texts: Player choices affecting a massive online world

texts:
Current generation MMOs are pretty static in that choices don't really affect the world for more than the scope of one or two quests -- but that doesn't give you a good sense of immersion, simply a temporary task.

I've had this idea of an MMO where whenever you make major decisions (such as burning down or sparing a village), you get teleported into an instanced version of the world with your changes (the village is burnt, the peasants are killed, etc) along with other players that have made the same choices.

The problem is that this requires a very large amount of instances, and players will be extremely fragmented and sparse throughout the world -- except in those areas that cannot be changed (for example, a central trading post.)

How do you solve this fragmentation problem, allowing more social interaction among players? It's hard to have an MMO with millions of players, each making different decisions.


texts: How to achieve an orbit-adjustable rotation?

texts:
Here's a script:

public float RotationSpeed = 100f;
public float OrbitSpeed = 50f;
public float DesiredMoonDistance;
public Transform target;

public Vector3 axis = Vector3.forward;

void Update () {
    transform.Rotate(Vector3.forward, RotationSpeed * Time.deltaTime);
    transform.RotateAround(target.position, Vector3.forward, OrbitSpeed * Time.deltaTime);

    float currentMoonDistance = Vector3.Distance(target.position, transform.position);
    Vector3 towardsTarget = transform.position - target.position;

    transform.position = transform.position + (DesiredMoonDistance - currentMoonDistance) * towardsTarget.normalized;
}

which makes a continous rotation at DesiredMoonDistance on a Z axis:

The problem with this script is that the rotating object needs a 'tilt' at the start.

If both the objects (the planet and the moon) have the same initial position, the rotation won't start, no matter how big the distance is set, because of this:

Vector3 towardsTarget = transform.position - target.position;
transform.position = transform.position + (DesiredMoonDistance - currentMoonDistance) * towardsTarget.normalized;

towardsTarget becomes (0,0,0) and there's no escape from that black hole.

I'm trying to figure out, how to adjust the script with some if's for a situation, when their position is equal, so I don't have to make stupid moves like moon.transform.translate(.0001f,0f,0f) so it tilt's at the start.

My real goal is to adjust this, so even if I change the DesiredMoonDistance to 0 in the inspector and then increase it, it will unstuck and go to the desired distance.


texts: Weird block selector selection (to floor or not to floor)?

texts:
Well, I am creating a Minecraft like engine in XNA, and since I first implemented the block selector (the cube that allows you to select blocks in 3D space) it has always been very inaccurate. Here is what I mean:

And here is the code that does the selecting (note that I have tryed to ceil then floor the vectors but none correct the abnormal positioning of it):

private Block GetSelectedBlock()
{
    Block block = new Block();
    block.BlockType = BlockType.none;

    for (float x = Variables.SELECTION_MIN; x < Variables.SELECTION_MAX; x += 0.1f)
    {
        Vector3 targetPoint = camera.Position + (camera.LookVector * x);
        //targetPoint = Util.FloorVector3(targetPoint);
        //targetPoint = Util.CeilVector3(targetPoint);

        blockSelector.UpdatePosition(new Vector3((int)targetPoint.X, (int)targetPoint.Y, (int)targetPoint.Z));
        block = world.GetBlock((int)targetPoint.X, (int)targetPoint.Y, (int)targetPoint.Z);

        if (block.BlockType != BlockType.none)
        {
            blockSelector.Visible = true;
            break;
        }

        blockSelector.Visible = false;
    }

    return block;
}

Also the two following screen shots show where the block selection cube is placed when I do call the blockSelector.UpdatePosition() function but do not cast the values to integers:

Any ideas what I am doing incorrectly?

Also regarding Blecki's answer here is what I implemented based on his idea:

       private Block GetSelectedBlock()
    {
        Block block = new Block();
        block.BlockType = BlockType.none;

        for (float x = Variables.SELECTION_MIN; x < Variables.SELECTION_MAX; x += 0.1f)
        {
            Vector3 targetPoint = camera.Position + (camera.LookVector * x) + new Vector3(0.5f, 0.5f, 0.5f);
            targetPoint = Util.FloorVector3(targetPoint);

            blockSelector.UpdatePosition(new Vector3((int)targetPoint.X, (int)targetPoint.Y, (int)targetPoint.Z));
            block = world.GetBlock((int)targetPoint.X, (int)targetPoint.Y, (int)targetPoint.Z);

            if (block.BlockType != BlockType.none)
            {
                blockSelector.Visible = true;
                break;
            }

            blockSelector.Visible = false;
        }

        return block;
    }

It seems to allow you to place blocks alot more accurately but it is still off centre:


texts:
I would like to get some information on how I can control my gameObject with a wiiRemote. Can't seem te find a decent guide on how to implement the WiiRemote into Unity.

My game is just a simple catch-game in 2D. Balls falling from the sky, and need to be collected in a bowl.
The player is controlling a stick (Controlled by WiiRemote) that has to lead the balls to the bowl.
I would like to be able to move the stick using the WiiRemote, and rotate the stick by turning the WiiRemote.

So far I seem to be able to connect my WiiRemote to my PC (windows), but I have no idea how to read the input from it in Unity.


texts: What is the best way to code grinding for a skate game in Unity?

texts:
I am making a inline skate game, what could be the best method to code the grinding system, there are many various and complex stuff to use but what could be used to set it up simple and not that complex? I made some research, I come up with Catmull Splines or Bezier curves but that seems very complex, my Idea is getting something simple to build up on that and improve it. Maybe use a simple waypoint system that the player follows along while jump on a trail or something. Any ideas or suggestions? Because you cant find any tutorials on grinding system in YouTube or somewhere.

Thanks.


texts:
I am trying to implement a saw blade hazard in my platformer. The saw blade simply moves from point A to point B, and back, at constant velocity. (Let's assume all saw blades move at the same velocity.)

I currently achieve this using my engine's built-in tweening functionality, which allows me to specify a start position, end position, and duration of the tween.

I start the object at position A, tween to position B, then tween it back to A.

This works well enough, but it limits what I can do with level design. There is no way for me to start the saw blades at intermediate points, which means I can't really design interesting patterns with them, for example, getting them to pass some intermediate point at the same time in their cycles.

Ideally, I'd like to be able to set the terminal points, duration of a cycle, as well as the initial configuration of the saw blades. This would allow me to start them at a pattern I want to repeat, and simply let them run.

So, my question is: How can I set up my moving hazards so that I can easily achieve and experiment with different patterns and synchronizations?

I work in Godot 3.0, but I don't think that matters. I am looking for general advice about how to set up moving hazards so that they can be synced in reliable yet highly customizable ways.