texts: Object reference not set to an instance of an object error? (Unity)

texts:
I am creating a simple 2d game in Unity. I tried to make the player able to pick up objects whenever they are clicked, but I keep getting the error I mentioned.
Here are the scripts I used : (Both of them are attached to the same object that the player wants to pick up)

First :

    public class Select : MonoBehaviour
    {
        public GameObject selectionBox;
        public bool isSelected;

        void Start()
        {
            selectionBox.SetActive(false);
        }

        void OnMouseOver()
        {
            Vector2 pos = transform.position;

            selectionBox.transform.position = pos;
            selectionBox.SetActive(true);
            isSelected = true;
        }

        void OnMouseExit()
        {
            selectionBox.SetActive(false);
            isSelected = false;
        }
    }

Second : (that gives the error)

    public class Pickup : MonoBehaviour
    {
        private Select select;
        private Inventory inventory;

        void Update()
        {
            OnMouseDown();
        }

        void OnMouseDown()
        {
            if (select.isSelected && Input.GetMouseButtonDown(0)) //Error here
                print("Click!");
        }
    }

Can anyone please tell me why I am getting this error? And how can I fix it?

Here is the error :
Object reference not set to an instance of an object Pickup.OnMouseDown () (at Pickup.cs:17)


texts: In Unity3D, how can I improve image clarity?

texts:
The same images that appear clearly in Adobe Flash appear blurry in Unity.

My game uses quads, cubes and sprites. I've tried the game on Android, iPhone, Mac  and PC, but the image appears poor-quality on all of them.

A sample screenshot:

What can I do about this?


texts: Unused methods after component inheritance in component based architecture?

texts:
I have a GameObject class, which contains Components, like:

Renderer
Camera
Behaviour
Rigidbody

First I inherited all of them from Component which has an Update() method, and it is called every frame on every game objects' every component.

But then I noticed, that** Renderer and Camera's Update method is unused**. (There are classes like RenderData & CameraData which are isolated and made from primitives, and upon creation of these Components, these Data's pointer is sent to the GraphicsEngine which will process them every frame.)

So having an unused method is bad. So I created a DynamicComponent class, which inherits from Component, and Behaviour & Rigidbody classes are inherited from it.

I moved the Update() from Component to DynamicComponent, and I have now 2 containers at gameobjects:

Components (for components which are inherited directly from Component)
Dynamic Components (for components which are inherited from D.Comp.)

And every frame I only call DynamicComponents' Update().

Now I'm having another issue. There is the Behaviour class, where should be a Start() method, which is called on every Behaviour when the scene is fully initalized.

That means that I should have a Components, D.Components and also a Behaviours container at game objects.

This looks very bad to me.

Having a Component class, with Start(), Update(), etc is very simple and makes a very clean code, but this means that only a few derived classes implement its virtual methods.

What should I do?


texts: Level playing field: Punish the better player or enhance the worse player?

texts:
I am making a 1 vs 1 game where each player controls a car with an identical joystick. The objective for the players is to reach a goal destination before the other player.

The players of the game are placed into categories based of the skills controlling the car e.g. Skill level[1,2,3,4,5] with 5 being the highest skill level.

The players will not be intended to jump up and down in skill levels when playing the game. After a given period, e.g. a week, the skill levels will be updated. This will not be shown to the players.

The objective for me is to make every combination of players in the 1 vs 1 setting be a 50/50 win loss chance for the players.

Example: Player 1(Skill level 5) vs player 2(Skill level 1) should each have 50% change reaching the goal destination first.

I have not been able to find any research on whether the best practice is to limit the abilities of the good player or enhance the abilities of the bad player or maybe a combination.

The idea is to have disabled adolescents playing against their able bodied friends or family members. It is therefore not a possibility to not let good players play against bad ones.
Data from field tests have shown that the disabled adolescents perform worse than able bodied consistently due to spasms.

I am looking for input on how to go about with this; research, your experiences, how other games are doing it? Is there any common recommendations for this?


texts: How to make game sessions like "with friends" games?

texts:
I want to make a game like "words with friends" or "chess with friends" or "Draw Something" or any of the other online multiplayer type games that are based around friends having game sessions with each other.  I have made one app before that had no online features so I know the basics of objective-C and xCode.  I looked up facebook connect so I know how to make friends find other friends to play with through Facebook.  Just not how to make the gaming session.

I only need my game to send a small array (or XML if it's better) of strings and integers from one iPhone to the other as each iPhone takes a turn.  I'm NOT sending some complex video or anything like in "Draw Something."

I was hoping someone could point me in the right direction (whether link to website or book or just a general idea) for how to do gaming sessions between two iPhones.  I read this tutorial http://www.raywenderlich.com/3932/how-to-create-a-socket-based-iphone-app-and-server  but it seems to be more about having two iPhones communicate over a server on a laptop or through the same wifi, not how to have iPhones game together over any Internet connection like in "with friends" games.

I've tried to research this in other places but I'm never quite sure if what the articles I find are talking about is related to what I want or not.  Someone please just point me in the right direction or give me a general outline of what to do.  I will look up the specifics on my own once I know what to look for.  Thank you.


texts: Match-3 algorithm to fill empty space left from removing matches

texts:
I am currently creating a match 3 game.

I am at the point where I have objects dropping down in the column when only one item is removed. So if an item is removed, the above item moves into its old position etc.

The problem I am having now is that when more than one item is removed from a column, the items in that column only drop down to the first item that was removed. Instead of filling in both items that were removed it just drops down to fill in the first one.

So basically, if two(or more) items are removed from a column the second, third, fourth, etc positions are left blank.

The way I am designing my game is I am using units of 1. So each item takes up 1 unit by x and 1 unit by y. This means that I can position the items like in a grid, at 0x1, 0x2, etc.

What kind of algorithm could I use to move multiple items down to fill the empty space?


texts: Multiplayer in a game. How to design it object wise?

texts:
I was suggested on StackOverflow to ask this question here.

I'm working on a simple game and I was thinking of adding multiplayer feature but I'm a bit stuck. I'm not sure what approach should I take, keeping in mind good programming practices.

I have a Player object which is created for each player but then I have many other classes that would have to be able to access them. The thing is, if I initialise them in, let's say my main method, then I can't relate to different instances of player class from other classes. The only solution to my problem that comes to my mind is using some form of global objects but afaik using anything globally in apps is usually not a good practice. Any suggestions/ideas?


texts:
I am trying to make DirectX display a sprite from a sprite sheet I found on the internet but it doesn't seem to be displaying the texture in the correct position as I am specifying it.

D3DXVECTOR2 scaling = D3DXVECTOR2(1.0,1.0);
D3DXVECTOR2 center = D3DXVECTOR2(64,64);
D3DXMatrixTransformation2D(&mat,NULL,0.0,&scaling,NULL,rot,&position);
sprite->SetTransform(&mat);
sprite->Draw(zombieTexture,&srcRect,NULL,NULL,0xFFFFFFFF);

srcRect is defined as follows:

srcRect.top = 384;
srcRect.bottom = 512;
srcRect.left = 512;
srcRect.right = 640;

which instead of giving this texture:

It gets this one: (ignore the rotation)

What am I doing wrong?


texts: Frequent stuttering, high FPS spikes with VSync option turned on in Unity standalone build

texts:
I'm experiencing an issue using Unity 4.3.2 and standalone builds. If I turn on VSync in the project's Quality settings, running the game at the native monitor resolution, I'll frequently get high framerate spikes (over 100FPS), and a strong stutter for a few frames, and then it drops back down to 60FPS and runs normally. If I run the game at a lower resolution (800x600 for example), the framerate stays at around 500FPS and the stuttering is consistent.

However, if I turn off VSync in the Quality settings, and force it on in the Nvidia Control Panel, I don't experience any stuttering or framerate spikes, nor when I turn off VSync completely (but lots of screen tearing, which is very ugly and distracting).

Can anyone explain this behavior? Is there anything that can be done to circumvent it? I'd imagine other Unity developers have used the built in Unity VSync with success before (or maybe not?!) so I'm hoping I'm just doing something wrong on my end.


texts: In today's video game industry, why isn't every game released on PC?

texts:
In this day and age, you absolutely must use a computer to make a video game; and, no, "users making their own content using our editor built into the game itself" doesn't count. I'm talking about the base game that you purchase to use that editor.
Given that you made the game using a computer and special hardware is required to test/run it on anything else (PS4/5 Dev machines, etc). Why do games come out on, say, just a console? The basic testing prior to copying files over to a console for specific-issue testing is performed on a computer, programming is done on a computer, compiling is done on a computer, etc.
You actually have to do more work to release something exclusive to a console.
So, to re-iterate, why aren't games always released for home computers?


texts: How can I have a Mecanim animation with displacement and physics?

texts:
I have 3D wolf models from my animator with displacement (i.e the wolf transforms with animation, not in-place). I have added rigid bodies to the models. I am facing following issues while executing them in my project:

When I turn on IsKinematic on my rigid body (i.e disable physics) the animations work perfectly, with displacement. But I need to have physics enabled on my wolf because it doesn't detect collision when physics is disabled and gravity doesn't have any impact.
When turn off IsKinematic (i.e enable physics), the animations don't work; the wolf start wobbling and flying in the air.

How can I resolve this?


texts:
For my Android app this is the gameloop:

public void run(){
    while(true){
        if(frames == 0)
            cTime = System.currentTimeMillis();

        if(System.currentTimeMillis() >= lastUpdate + 5){
            if(gameState == PLAYING)
                updatePhisic();

            updateSprites();
            this.postInvalidate();
            lastUpdate = System.currentTimeMillis();
        }

        /*try{
            Thread.sleep(sleeptime);
        }catch(InterruptedException e){}*/

        if(System.currentTimeMillis() >= cTime + 1000){
            frameRate = frames;
            frames = 0;
        }
        else
            frames++;
    }
}

Please consider this should work for multiple devices.

Testing in some devices:

My phone: 180 FPS
A Smaller phone: 200 FPS
A Tablet: 120 FPS

I'm trying to put it at 60 FPS but the player moves so slow, I don't know how to calculate the Delta for player. I mean that at 180 FPS in my phone works fine, that is the speed that I want. But at 120 FPS in a tablet freezes a bit.

I think that painting the screen 60 times in a second would be enough.

And this freezes sometimes:

if(System.currentTimeMillis() >= lastUpdate + 5)

This does not:

try{
    Thread.sleep(sleeptime);
}catch(InterruptedException e){}

Why?


texts:
Recently I got used to modern languages which include a stock good random generator, which usually is the Mersenne Twister; now that I got back to C++ I have to decide what to use.

I searched for Mersenne Twister implementations and I noticed there are so many: is there one which is more used and widespread, or am I supposed to pick one assuming they are all equally good?


texts:
red is my origin point, blue is my offset, both are 2D vectors, how can calculate blue after rotation?
this is the code I've been trying(just throwing things against a wall to see what sticks)
public static Vector2F CalcPointWithRotation(Vector2F origin, Vector2F point, float rotation)
{
    return new Vector2F((float)Math.Cos(rotation) * origin.x, (float)Math.Sin(rotation) * origin.y);
}


texts: Why does Intersector.overlaps return false?

texts:
I am trying my hand at creating a simple game using libGDX.

The idea is: We have a hero who jumps and world consist of dynamically created moving platforms in an auto side-scrolling manner. In order to progress our hero need to jump on these platforms and avoid falling. I have figured out how to do this using the built-in libGDX collision detection mechanism.

Code is:

    public boolean collides(Hero hero){
    if (position.y < hero.getY() + hero.getHeight()) {
        return Intersector.overlaps(hero.getBoundingRect(),boundingRect);
    }
    return false;
    }

But, our hero need to die when hits side of a platform. Following code should do the trick but even though bounding rectangle of hero surely overlaps(see below image) the bounding rectangle of platform Intersector.overlaps returns false no matter what.

My code for this task:

    public boolean   collidesSide(Hero hero){
    float heroYH = hero.getY() + hero.getHeight();
    float heroXW = hero.getX() + hero.getWidth();
    if (heroYH > position.y && heroXW>position.x){ // Platforms position
        Gdx.app.log("Platform","hero.bound:" + hero.getBoundingRect().toString() + " plat.bound:" +boundingRect.toString());
        Gdx.app.log("Platform","Intersect: " + Intersector.overlaps(hero.getBoundingRect(),boundingRect));
        if (Intersector.overlaps(hero.getBoundingRect(),boundingRect)){
            Gdx.app.log("Platform","CollidesSide: True");
            return true;
        }
        return false;
    }

    return false;
    }

It seems that I have missed some logic or doing something wrong.

How should I handle this issue?

Also this is the output log

Platform: Intersect: false
Platform: hero.bound:20.0,64.65544,25.0,32.0   plat.bound:-3.0893557,96.0,19.0,5.0
Platform: Intersect: false
Platform: hero.bound:20.0,65.13417,25.0,32.0 plat.bound:-4.4350085,96.0,19.0,5.0
Platform: Intersect: false
Platform: hero.bound:20.0,65.74593,25.0,32.0 plat.bound:-5.779882,96.0,19.0,5.0
Platform: Intersect: false
Platform: hero.bound:20.0,66.43762,25.0,32.0 plat.bound:-7.042242,96.0,19.0,5.0
Platform: Intersect: false
Platform: hero.bound:20.0,67.29663,25.0,32.0 plat.bound:-8.372085,96.0,19.0,5.0
Platform: Intersect: false

UPDATE:

The Red and Cyan rectangles seen in images are rendered output of Bounding Rectangle(hit boxes) of each object, not actual sprite.


texts: What would a "2nd person" viewpoint consist of?

texts:
Traditional narratives have one of three viewpoints:

First person (I fought the monster)
Second person (You fought the monster)
Third person (He/She/It fought the monster)

First and Third person viewpoints are very prevalent in video games, but I got to wondering what a Second person viewpoint would be like.

First person ('I' am the character, seeing through 'my' eyes)
Second person (???)
Third person (He/She/It is the character, seen through a third party's eyes)

The only thing I can think of is a game where the viewpoint is a character you're not directly controlling, who is usually (always?) looking at the character you are.  But how would that differ from a Third person perspective with a very limited camera?


texts: Image rendering with additional space around it

texts:
When I try to display an image that is 400 pixels wide and 800 pixels high, it is not displayed this way. Instead it is diplayed like this: Instead it is displayed like this

You can see at the bottom and a few pixels right to the phone some thin white lines, I did not add this manually and it is not part of the picture, the picture is perfectly cropped around the phone.

When in my fragment shader I add + vec4(1, 1, 1, .5) it shows the area that the phone should have covered. Image

Code for creation of an object that holds info about the image:

GuiTexture phone = new GuiTexture(loader.loadTexture("phone_cropped"), Display.getWidth() / 2, Display.getHeight() / 2, 2, 400, 800);

The loadTexture method:

public int loadTexture(String fileName) {
    Texture texture = null;
    try {
        texture = TextureLoader.getTexture("PNG", new FileInputStream("res/" + fileName + ".png"));
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    int textureID = texture.getTextureID();
    textures.add(textureID);
    return textureID;
}

The line that calls the render class to render the image

guiRenderer.render(guis);

The transformation matrices that the image is multiplied by:

float width = gui.getWidth() / 2;
        float height = gui.getHeight() / 2;

        Matrix4f modelMatrix = new Matrix4f();
        modelMatrix.m00 = 2.0f / (float) Display.getWidth();
        modelMatrix.m11 = 2.0f / (float) Display.getHeight();
        modelMatrix.m30 = -1;
        modelMatrix.m31 = 1;

        shader.loadModel(modelMatrix);

        Matrix4f transformationMatrix = Maths.createTransformationMatrix(
                new Vector2f(
                           gui.getxPos(),
                        - (gui.getyPos())
                ), gui.getRotation()
                ,new Vector2f(
                        width,
                        height
                )
        );

        shader.loadTransformation(transformationMatrix);

Vertex shader code:

gl_Position = modelMatrix * transformationMatrix * vec4(position, 0.0, 1.0);
textureCoords = vec2((position.x+1.0)/2.0, 1 - (position.y+1.0)/2.0);

This does not happen to all images, when I load in an image that is square and I try to display it with width 400 and height 800 it works perfectly. Image

With different images it yields different extra space.

All images are .png. The phone image is 1009x2057 pixels. I also tried to use a phone that was 2048 pixels high (1006x2048) since this is a power of 2, that still yields a white line on the side but does look better: image

The square (3rd image) that was elongated to look like a rectangle and does display correctly is 256 x 256 pixels.

All displayed images have a slight rotation because without rotation the little white thin lines don't always show up, the rotation did not change anything about the images.

To load images I use slick utils TextureLoader class.


texts: Cocos2d-x setContentSize, setScale give poor graphic quality

texts:
I want to create sprite with size is relative to the screen size. I.e: Sprite size is equal to screen width * 0.2.

I use setContentSize and setScale but it gives ugly and poor graphic quality. I've read about multiple resolution supports, but it doesn't work on this case because i need sprite size adapt to the any screen size.

Testing on iPhone 7, i scale an image from 512x512 to 64x64.

This is error of cocos2d-x or anyway to archive it?


texts:
I'm currently looking at how to easily simulate some stellar systems (meaning some central stars and then some planets with maybe satellites), in order to allow later some space based strategy game (hence with space ships moving around). This should all be based around time (so the state of each system differs through time)

I'm quite struggling with the math behind this topic, like for example:
- ellipse related math,
- creating the path from planet A to B having time in mind (respective positions will change over time)...

Do you know of any resources for that ? I wouldn't mind even buying books about it...

side note: how to display all this stuff isn't a matter at this point in time, I'll simple plans for that (basically sticking to 2D and a "high level view" with no space ships/planets details, just markers)


texts:
I'm trying to simulate the environment on a Squash Court on Android with my own physics and using OpenGL for visualization. Basically, its about a rubber ball bouncing around in 3d, not just on the floor but also on the walls.

What I'm not quite sure about is what kind of physical concepts are altering the movement of the ball or how much they are.

Obviously there's gravity...
Also, air friction, but I'm not sure how to calculate air friction of a rubber ball that is roughly 40mm in diameter. I've tried different formulae but I wasn't happy with them (eg. some were linear to speed and some were quadratic lol) and I was missing some material-dependant constants.
Then there's the normal force applied from the solid shape on which the ball bounces. I don't think I need to alter any values as the normal force is "taken into account" by changing the ball's direction. I mean, if the solid shape where the ball bounces is vertical, normal force is zero but the ball still changes direction. Correct?
Now, every collision reduces the kinetic energy as it emits sound and warms the ball. I assume that this reduction is greater if the ball hits the solid shape on a tighter angle. Is there a way to quantify it? So far, all I could do was use values "to make it look like it might be".
Furthermore, I suspect that the angle at which the ball hits the shape is not equal to the angle in which it leaves the ball. Obviously, if the ball hits at 90° (orthogonal), then it will leave at 90°. On the other hand, if the ball hits at, say, 45°, it might leave at 30° (compared to the solid shape eg. the floor).
There is spin which I have not spend much thought on but if anyone knows where I might find something about that I'd be greatful.
Other forces/effects on the trajectory of the ball...??

Thanks in advance :)

Edit: To summarize, I am looking for (1) an applicable formula that represents air friction with possible constant values depending on the rubber-ball-scenario, for (2) a confirmation that my way of handling normal force is correct, that (3) a way of quantifying energy loss of the ball in a collision, (4) how (if) the angle after the collision is altered, with regard to the incoming angle, and lastly (5) how to handle spin.


texts: What types of games benefit most from lockstep? What games are not suitable for a lockstep protocol? What are the disadvantages of lockstep?


texts: How to apply toastr notifications when user get leveled up?

texts:
This question is about when user get leveled up the toastr will pop up.

What I want to do is i want to put the toastr.js inside my script but I don't have idea how to implement.

** Link and Script **

<link rel="stylesheet" href="{{ asset("css/toastr.min.css") }}">
<script src="{{ asset('js/toastr.min.js')}}"></script>

** Profile.blade **

 <script>
   @if(Session::has('success'))
    toastr.success("{{ Session::get('success') }}")
   @endif
 </script>

** Controller **

         use Session;

          while($user->curr_exp >= $user->exp_needed){
             if($user->level == 10 || $user->level == 15 || $user->level == 20)
               {
                  $user->reward_token += 1;
               }
                  $user->curr_exp -= $user->exp_needed;
                  $user->prev_exp = $user->exp_needed;
               if($user->level <= 19){
                   $user->exp_needed = $user->prev_exp * 1.4;
               }
               elseif($user->level >= 20 && $user->level <= 39){
                   $user->exp_needed = $user->prev_exp * 1.1;
               }
               elseif($user->level >= 40 && $user->level <= 59){
                   $user->exp_needed = $user->prev_exp * 1.05;
               }
               elseif($user->level >= 60 && $user->level <= 79){
                   $user->exp_needed = $user->prev_exp * 1.04;
               }
               elseif($user->level >= 80 && $user->level <= 99){
                   $user->exp_needed = $user->prev_exp * 1.03;
               }
               elseif($user->level == 100){
                   $user->exp_needed = $user->exp_needed * 0;
               }
                   $user->level += 1;
                   Session::flash('success','You leveled up!');
                   $user->save();
               }

I'm using laravel framework 5.4.36 version. I'm confused how to display a live notifications on the user's profile every time they leveled up.

Any ideas? Thank you


texts: Unity3D: Efficiently loading chunks in an infinite voxel engine

texts:
I'm developing a voxel engine in C# using Unity and I'm currently trying to implement infinite terrain, so I took a look at other Unity voxel engines that have infinite terrain. I've seen three different ways of doing it:

Using a dictionary to store the chunks and store the block data in another dictionary
Using a dictionary to store the chunks and store the block data on every chunk
Using a fixed size array and shifting it every time the player moves

The engines using approach 1 and 2 were pretty slow at chunk loading.
The engines using approach 3 were faster but produced lag every time the player entered a new chunk.

I've already tried to implement it using approach 1, but my chunk loading speed got slower by about 10 times, so it was really unplayable.

How is it done in efficient or popular voxel engines like Minecraft or VoxelFarm?
Do you have experience with voxel rendering and know a better approach?

Thanks in advance!


texts:
I'm reading about efficient Frustum culling algorithms. I found an article about a smart method that first use the Frustum AABB (Axis Aligned Bounding Box) to eliminate most of the scene before check again against the actual frustum representing the camera.

I didn't do any performance test yet, but maybe somebody else did and can answer this question.

Let's say I'm using an Octree to quickly check again the camera bounding box. But I do not want to do a second pass again the camera planes. If I simply render everything so far, isn't that actually faster than do the second pass?

Assume object geometry is loaded into VRAM using hardware vertex buffers.


texts:
I am making a 2D game for Android. Almost completed the game but now I need a pause game option. I added a pause icon on the top right side of the screen. The icon is a GUI texture.
What I did so far :

I made a script which will bring up some buttons (which is not working) and attached it to the GUITexture.This is the script :

#pragma strict

function OnMouseDown() {
   Debug.Log("*Pause Menu Opens*");
   Time.timeScale = 0;

   if (GUI.Button(Rect(10,10,100,50),"Restart"));
      Application.LoadLevel(Application.loadedLevel);

   if (GUI.Button(Rect(10,60,100,50),"MainMenu"));
      Application.LoadLevel("MainMenu");
}

Now the problem stands at the part where the buttons won't show up and the game freezes at the first frame. Please if you can help I would be really thankful.

Edit #1 : I just noticed that when I click "Pause" the game freezes and it takes me to the MainMenu. That's because I added the GUIButton which takes you to the main menu. I think the whole script structure is wrong. I also forgot to mention that I am new to scripting/unity.

Thank you.


texts: How to achieve programming experience with PS3 or Xbox360?

texts:
Possible Duplicate:
  How to get PS3/Xbox 360 experience without having access to Dev kits?

Is there a way to achieve programming experience with PS3 or Xbox360 systems without the development kit that only are selling to great videogame companies ?

There are a lot of game companies that request experience with these systems and I don't know how to achieve this.


texts: GraphicRaycaster on the child object containing buttons blocks Raycast from the parent object containing GraphicRaycaster. How to solve it?

texts:
What I'm trying to achieve is to detect clicks on buttons in UI. Here is the tree:
I have a parent object SlotMachineScreen containing GraphicRaycaster with a script detecting clicks attached to it:
if (Input.anyKeyDown)
        {
            //Set up the new Pointer Event
            m_PointerEventData = new PointerEventData(null);
            //Set the Pointer Event Position to that of the mouse position
            m_PointerEventData.position = Input.mousePosition;

            //Create a list of Raycast Results
            List<RaycastResult> results = new List<RaycastResult>();

            //Raycast using the Graphics Raycaster and mouse click position
            m_Raycaster.Raycast(m_PointerEventData, results);
            foreach (RaycastResult result in results)
            {
                Debug.LogWarning("Hit " + result.gameObject.name);
            }
        }

And there are a bunch of child objects with a GraphicRaycaster (red ones) with buttons in it, that I want to detect a click on. But there is no response from my sprit at all when I click on them.
I found one solution so far, but its not what I need: the solution is to move all buttons from child containers to SlotMachineScreen.
Are there any different ways to solve this problem?


texts: How Client send info to Host in Unity Multiplayer

texts:
I want to send player name and other details from client to host device. I have setup game for maximum two players connection.

Here is the code that I have tried multiple times with different changes:

    void Start ()
{
    spriteRenderer = GetComponent<SpriteRenderer> ();
    circleCollder = GetComponent<CircleCollider2D> ();
    //      StartCoroutine (ColorSwitcher ());
    InitialTasks ();
}

private void InitialTasks ()
{
    isAlive = true;
    GameManager.Instance.IsPlayerWin = false;
    int selectedTheme = Random.Range (0, ballSprites.Length);
    spriteRenderer.sprite = ballSprites [selectedTheme];
    trailRenderer.material = trailMaterials [selectedTheme];
    destroyParticleObj.GetComponent<ParticleSystemRenderer> ().material = trailMaterials [selectedTheme];

    hidePlayerName += OnTouchHidePlayerName;

    if (!isLocalPlayer) {
        // remote player
        gameObject.tag = GameConstants.TAG_REMOTE_PLAYER;
    } else {
        // local player
        Debug.Log ("locally set player name: " + DataCollection.localPlayer.PlayerName);
        playerNameText.text = DataCollection.localPlayer.PlayerName;
//      StartCoroutine (SomeDelayForSendingPlayerDetails ());
    }

//  if (isServer)
//      RpcSetRemotePlayerName (DataCollection.localPlayer.PlayerName);
//  else
//      CmdSetRemotePlayerName (DataCollection.localPlayer.PlayerName);
}

public override void OnStartLocalPlayer ()
{
    base.OnStartLocalPlayer ();
    CmdSetRemotePlayerName (DataCollection.localPlayer.PlayerName);
}

[ClientRpc]
private void RpcSetRemotePlayerName (string remotePlayerName)
{
    playerNameText.text = remotePlayerName;
    Debug.Log ("rpc remote player name: " + remotePlayerName);
}

[Command]
private void CmdSetRemotePlayerName (string remotePlayerName)
{
    RpcSetRemotePlayerName (remotePlayerName);
    Debug.Log ("cmd remote player name: " + remotePlayerName);
}

Basically I want to interchange names of both players in 2 players multiplayer game. So please give me some advice into this.


texts:
I'm using a combination of sprite sheets for well, sprites and individual textures for infinite tiling.

For the tiling textures I'm obviously using Wrap to draw the entire surface in one call but up until now I've been making a seperate batch using Clamp for drawing sprites from the sprite sheets. The sprite sheets include a border (repeating the edge pixels of each sprite) and my code uses the correct source coordinates for sprites.

But since I'm never giving coordinates outside of the texture when drawing sprites (and indeed the border exists to prevent bleed over when filtering) it's struck me that I'd be better off just using Wrap so that I can combine everything into one batch.

I just want to be sure that I haven't overlooked something obvious. Is there any reason that Wrap would be harmful when used with a sprite sheet?


texts:
I'm developing a game in C++, making use of the Entity-Component system.

I'm going to store a list of each component, with each component's position in the list mapping to it's entity. So, the 5th item in the list is a component for Entity 5, etc.

My inspiration came from this:

https://www.gamedev.net/resources/_/technical/game-programming/implementing-component-entity-systems-r3382

My question is what data structure is the best for this. I guess my options are an array or a vector of Components. When using either the array or the vector, is it possible to have empty elements. So, for example element 0, 1 and 4 might contain components, but positions 2 and 3 empty. I know I could achieve this with pointers to components, but is this the best way?

Advice appreciated.

Thanks,
Rich.


texts:
I am preparing sounds system to my game in xna. I am using XACT Tools, and i got problem.

There is class SoundCategory. I can change sound level for all sounds in that category easily.

SoundCategory category = engine.GetCategory("music");
category.SetVolume(float_value);

But there is no such function like:

category.AddVolume(float_value);

Which would increase or deacrease that value. There is also no function that get current volume so i can do thing like:

float vol = category.Add(float_value);
vol += 0.1;
category.SetVolume(vol);

Is there some clever way to achive what i want without creating some additional variables which keep current volume for all sounds categories ?


texts: Starting a Coroutine after another Coroutine ends

texts:
I have a method that fades the screen to black, then fades away back again using coroutines but I couldn't get the 2nd part to work.
FadeToBlack() works if I put yield return null instead of yield return StartCoroutine(LightUp()); so I know that isn't the problem
 private IEnumerator FadeToBlack()
{

    for (float t = 0.01f; t < fadeOutTime; t += Time.deltaTime)
    {

        color = new Color(0, 0, 0, 1);
        night.color = Color.Lerp(night.color, color, Mathf.Min(1, t / fadeOutTime));
        yield return StartCoroutine(LightUp());

    }}

If I put yield return StartCoroutine(LightUp()); in FadeToBlack instead of null it immediately turns black without the fading part. Here's what LightUp(); looks like
private IEnumerator LightUp() {
    for (float t = 0.01f; t < fadeOutTime; t += Time.deltaTime)
    {
        color = new Color(0, 0, 0, 0);
      Color colorD = new Color(0, 0, 0, 1);
        night.color = Color.Lerp(colorD, color, Mathf.Min(1, t / fadeOutTime));

        yield return null;

    }
}


texts: Best way to play footstep-sounds of character?

texts:
I am developing an XNA-Game, which is pretty much a runner game (side-scrolling).

Now I am in the middle of adding sounds to my game. And as it turns out, I am having quite some problems with the footstep-playback.

The following is in C#, but I am quite sure that anyone will understand it:

 public static void StartStepTimer()
 {
     _stepTimer = new DispatcherTimer();
     _stepTimer.Interval += TimeSpan.FromMilliseconds(500);
     _stepTimer.Tick += _stepTimer_Tick;
     _stepTimer.Start();

     _step = _content.Load<SoundEffect>("Sound\\World\\Summer_1");
     _stepInstance = _step.CreateInstance();
     _stepInstance.Volume = 0.4f;

 }

  private static void _stepTimer_Tick(object sender, EventArgs e)
  {
      _stepInstance.Play();
  }

As you can see, I am playing the footstep based on a timer. I am using this method, since the gamespeed gets higher during gametime (I can change the interval in that case).

But this method isn't really working. The playback lags.
I thought of making a prerendered 10s soundfile and looping that in gametime, but than the playback won't fit when the gamespeed rises.

Any suggestions?


texts: Animated textures for models; How to write a shader?

texts:
Was watching some Rocket League and notice there was animated decals and wheels.

.

I would like to implement something similar to the effects in the image above.

How would I go about writing a Unity Shader to do the wheel effect?

I don't know much about Shaders, but can I edit the standard Unity Shader to do the animation effect?


texts: How to create life-like sprites from photo or video capture like was done for games like Mortal Kombat 1?

texts: I know they digitized actors but how can I get those same results? How to take a photo or video of someone and digitize it for a 2D game? Digitized sprites were used in several video games through the 90s but fell out of favor when textured 3D graphics became more common.  What technology is used today for creating MK1 realism?


texts: Essential knowledge for making HTML/JavaScript-based games

texts: I was wondering if any experts out there could share the knowledge and resources of what is necessary to start making games with the latest HTML standards and JavaScript (or what some like to call HTML 5). Are there JavaScript libraries that are essential to the process? Aside from the <canvas> tag, what other pieces of HTML do we need to be aware of?


texts:
I've been trying for a while to implement a frustum culling method using a per-computed AABB in object space and transforming it's corners into clip space.

  bool
  PlatformMath::OBBInFrustrum(const AABox& bounds,
                              const Matrix4& modelMatrix,
                              const Matrix4& viewMatrix,
                              const Matrix4& projMatrix) {

    //matrix to transfrom points to clip space
    Matrix4 wvpMatrix =
      (projMatrix * viewMatrix * modelMatrix).getTransposed();

    //transform all 8 box points to clip space
    Vector4 obb_points[8];
    obb_points[0] = wvpMatrix * Vector4(bounds.m_min.x,
                                        bounds.m_min.y,
                                        bounds.m_min.z, 1.f);
    obb_points[1] = wvpMatrix * Vector4(bounds.m_max.x,
                                        bounds.m_min.y,
                                        bounds.m_min.z, 1.f);
    obb_points[2] = wvpMatrix * Vector4(bounds.m_min.x,
                                        bounds.m_max.y,
                                        bounds.m_min.z, 1.f);
    obb_points[3] = wvpMatrix * Vector4(bounds.m_max.x,
                                        bounds.m_max.y,
                                        bounds.m_min.z, 1.f);
    obb_points[4] = wvpMatrix * Vector4(bounds.m_min.x,
                                        bounds.m_min.y,
                                        bounds.m_max.z, 1.f);
    obb_points[5] = wvpMatrix * Vector4(bounds.m_max.x,
                                        bounds.m_min.y,
                                        bounds.m_max.z, 1.f);
    obb_points[6] = wvpMatrix * Vector4(bounds.m_min.x,
                                        bounds.m_max.y,
                                        bounds.m_max.z, 1.f);
    obb_points[7] = wvpMatrix * Vector4(bounds.m_max.x,
                                        bounds.m_max.y,
                                        bounds.m_max.z, 1.f);

    obb_points[0] *= (1 / obb_points[0].w);
    obb_points[1] *= (1 / obb_points[1].w);
    obb_points[2] *= (1 / obb_points[2].w);
    obb_points[3] *= (1 / obb_points[3].w);
    obb_points[4] *= (1 / obb_points[4].w);
    obb_points[5] *= (1 / obb_points[5].w);
    obb_points[6] *= (1 / obb_points[6].w);
    obb_points[7] *= (1 / obb_points[7].w);

    // Test z axis from 0 to 1
    {
      float maxVal = Math::NEG_INFINITY, minVal = Math::INFINITY;

      for (SIZET j = 0; j < 8; j++) {
        float proj = obb_points[j].z;

        maxVal = max(proj, maxVal);
        minVal = min(proj, minVal);
      }

      if (!rangeOverLap(minVal, maxVal, 0, 1)) {
        return false;
      }
    }

    // Test x and y axis from -1 to 1
    for (SIZET i = 0; i < 2; i++) {
      float maxVal = Math::NEG_INFINITY, minVal = Math::INFINITY;

      for (SIZET j = 0; j < 8; j++) {
        float proj = obb_points[j].comp[i];

        maxVal = max(proj, maxVal);
        minVal = min(proj, minVal);
      }

      if (!rangeOverLap(minVal, maxVal, -1, 1)) {
        return false;
      }
    }

    return true;
  }

Using my directx graphics debugger, I know that the obb_points have been correctly calculated into homogeneous clip space (right before dividing by w). Despite this, objects that should be rendered are not. (They are out of the clip space range). What am I doing wrong?


texts: What are some good learning resources for OpenGL?

texts:
I have been using the OpenGL ES on the iPhone for a while now and basically I feel pretty lost outside to the small set of commands I've seen in examples and adopted as my own. I would love to use OpenGL on other platforms and have a good understanding of it.

Every time I search for a book I find this HUGE bibles that seem uninteresting and very hard for a beginner. If I had a couple of weekends to spend on learning OpenGL what would be the best way to spend my time (and money)?


texts:
I'm developing a simple multi-player puzzle game in Java.  Both players should be able to view the same game board on his own computer. Then, when one player makes an action in the game (ex. drags an object onto a coordinate space), the game's view should update automatically on the other computer's game screen. I'd like all this to happen over the internet, not requiring both computers to be on the same LAN connection.

If I need to use SQL/PHP to accomplish this, I'm unsure how to design the database to accomplish something as simple as the following:

Player A drags element onscreen
Game sends coordinates of element to database/server

Player B's computer detects a change to an item in the database
Player B's computer grabs the coordinates of Player A's item
Player B's machine draws onscreen elements at the received coordinates

Could somebody point me in the right direction?


texts: Specifying force and angle in ApplyImpulse in box2d

texts:
I need to apply an impulse on a object with a particular force and at a particular angle in Box2d. If I am right the syntax would be the following:

  body.GetBody().ApplyImpulse(new b2Vec2(direction,
  power),body.GetBody().GetWorldCenter());

The problem is my direction is in angles. I found a discussion where it was said that the way we can convert an angle into a vector would be as:

  new b2Vec2(Math.cos(angle*Math.PI/180),Math.sin(angle*Math.PI/180));

Now I am not sure how to combine these two. In other words, if I wish to apply a force of 30 units at an angle of 30 degrees at the center of the object, how should I do it?


texts: How do I get my mouse-based input system to work on Android?

texts:
I am developing the ball breaker game in unity and right now my game work with mouse click button. but i want my game work in android. so what changes i want to do in this code? So when i set the arrow and its jump ball and hit the brick.
Here is the code with image :-

BallController.cs

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

public class BallController : MonoBehaviour {

    public enum ballState {
        aim,
        fire,
        wait,
        endShot
    }

    public ballState currentBallState;

    public Rigidbody2D ball;
    private Vector2 mouseStartPosition;
    private Vector2 mouseEndPosition;
    private float ballVelocityX;
    private float ballVelocityY;
    public float constantSpeed;
    public GameObject arrow;

    // Use this for initialization
    void Start () {
        currentBallState = ballState.aim;

    }

    // Update is called once per frame
    void Update () {
        switch (currentBallState) {
        case ballState.aim:
            if (Input.GetMouseButtonDown (0)) {
                MouseClicked ();
            }
            if (Input.GetMouseButton (0)) {
                MouseDragged ();

            }
            if (Input.GetMouseButtonUp (0)) {
                ReleaseMouse ();
            }
             break;

        case ballState.fire:

            break;

        case ballState.wait:

            break;

        case ballState.endShot:

            break;
        default:
            break;

        }

    }

    public void MouseClicked(){
        mouseStartPosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
        Debug.Log (mouseStartPosition);
        //didClick = true;
    }

    public void MouseDragged(){
    //  didDrag = true;
        //Move the Arrow
        arrow.SetActive(true);
        Vector2 tempMousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
        float diffX = mouseStartPosition.x - tempMousePosition.x;
        float diffY = mouseStartPosition.y - tempMousePosition.y;
        if (diffY <= 0) {
            diffY = .01f;

        }
        float theta = Mathf.Rad2Deg * Mathf.Atan (diffX / diffY);
        arrow.transform.rotation = Quaternion.Euler (0f, 0f, -theta);
    }
    public void ReleaseMouse(){
        arrow.SetActive (false);
        mouseEndPosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
        ballVelocityX = (mouseStartPosition.x - mouseEndPosition.x);
        ballVelocityY = (mouseStartPosition.y - mouseEndPosition.y);
        Vector2 tempVelocity = new Vector2 (ballVelocityX, ballVelocityY).normalized;
        ball.velocity = constantSpeed * tempVelocity;
        if (ball.velocity == Vector2.zero) {
            return;
        }
        currentBallState = ballState.fire;

    }

}


texts: GLSL Unsigned Int Values Not Retrieved Properly

texts:
I have packed several values needed for shading a particular vertex into a single 32-bit uint. In the shader, it is unpacked like this:

vec3 color;
uint vertexData = data;
float sunlight, artificialLight;
bool occlusion;

artificialLight = float(vertexData & 31u);
vertexData = vertexData >> 5;
sunlight = float(vertexData & 31u);
vertexData = vertexData >> 5;
occlusion = bool(vertexData & 1u);
vertexData = vertexData >> 1;
color.b = float(vertexData & 127u);
vertexData = vertexData >> 7;
color.g = float(vertexData & 127u);
vertexData = vertexData >> 7;
color.r = float(vertexData & 127u);

The color produced by this extraction is much different from the originally intended color. For example:

130, 245, 90 --> 78, 125, 249   (These values are not exact)

I took the code and put it into my main c++ program and ran it with a debugger. It showed the right values.

130, 245, 90 --> 130, 245, 90

EDIT

I have taken a uint produced by my compressor and directly inputted it into my shader like this

vertexData = 2179293184;

Every vertex is shaded with the color of green this value corresponds to. So apparently, there is something going wrong with the transmission of the values. What might be causing this?


texts:
I am building a game in XNA that features colored laser beams in 3D space.

The beams are defined as:

Segment start position
Segment end position
Line width

For rendering, I am using 3 quads:

Start point billboard
End point billboard
Middle section quad whose forward vector is the slope of the line and whose normal points to the camera

The problem is that using additive blending, the end points and middle section overlap, which looks quite jarring. However, I need the endpoints in case the laser is pointing towards the camera!

See the blue laser in particular:


texts:
I am working on a tile based game in Java. I have a 2D array of tiles (JComponents) in a GridLayout, this is fine for creating the world (I think), but I am stumped at how to move the sprite smoothly between tiles. Currently, each JComponent tile draws the world and the sprite in accordance with booleans representing state (i.e. to show the sprite or not to show the sprite), however, this is not smooth. The sprite simply disappears from one tile and appears in another.

Any ideas on how I could go about moving the sprite in a smooth manner?

I am new to the whole game dev thing, so please be patient.

Regards,
Jack Hunt


texts:
I'm developing some game in order to learn OpenGL.

I can make an object follow me around when I move forward, backward, left, right, up or down, by setting it's position right infront of the camera.

Problem starts when the camera rotates / tilts (looking up, down, left, right...).

The object is indeed sticks infront of the camera position (because I calculate a vector going out from the camera position and place it there), however I can't make the angle of the object to rotate/tilt along with the camera, so it is just fixed.

I think I might have to set the object coordinate system to correlate with the camera's coordinate system, but I can't figure out how. Maybe I'm wrong and there's another way to do that.

My game implementation

I have 4 vectors for the camera and 4 vectors for each object: origin, x, y and z (to represent the objects coordinate system).

To move the camera, I substract z axis from origin.

Same for other directions.

In order to tilt the camera, for example to the right, I just calculate rotation around Z axis and apply to X,Y axes.

Note: Movement in the world works good, in all directions and angles.

Here's the (the relevant) code I use to position objects in the world. Before drawing them I first put them in their origin (recall: I save an origin and x,y,z axes to all my objects), then do some scale to fit my desired size:

// translate to position
gl.glTranslatef((float)origin.x, (float)origin.y, (float)origin.z);
// scale to size
gl.glScalef((float)size.x, (float)size.y, (float)size.z);

Any ideas?


texts: Centralized ResourceManager Class for every type of Asset in an Game Engine

texts:
I am trying to Implement resource manager for my hobby game engine.
The problem I am trying to solve is that I want one centralized resource manager, which delegates resource loading to a bunch of "subsystems" which are each responsible for managing their own type of resource, like in the code below.

struct Resource {
    std:: extensionType;
    std::string path;
    int refCount;
};

class ResourceLoader {
    virtual ResourceType* loadResource(std::string) = 0;
    virtual void unloadResource(ResourceType*) = 0;
};

class ResourceManager {
    std::map<std::string, ResourceLoader*> _loaders;

    void addResourceLoader(std::string extensionType, FileLoader* loader);
    template<typename T>
    T* loadResource(std::string filePath);
    void reloadAll();
}

class TextureResource: public Resource {
    TextureHandle* handle;
};

class TextureLoader: public ResourceLoader {
    ResourceType* loadResource(std::string); //load + return a TextureResource
    void unloadResource(ResourceType*); //unload texture
};

//Later on, to use:
int main(int argc, char* argv[]) {
     ResourceManager resourceMgr;
     TextureLoader textureLoader;
     resourceMgr.addResourceLoader(textureLoader);
     TextureResource* texture = resourceMgr.loadResource<TextureResource*>("SOMETEXTURE.PNG");
     return 0;
}

This is just an example of my implementation.
My problem shows up with more specific types of resources like Shaders.
I want to store shaders as a ShaderSet or ShaderProgram ( in OpenGL every shader program has its own ID ), so when I am loading ShaderProgram, I need to specify at least vertex shader and fragment shader ( vertex filepath and fragment filepath ), but with my current logic I can't think of an elegant solution for this problem.

for example to have something like this:

T* loadResource(std::string vs_filePath, std::string fs_filepath);

I can't figure out how can I have ShaderProgram saved in the same resource manager class, any Ideas?


texts: What does SetTextureStage(0, D3DTSS_COLORARG2, 0) in DirectX mean?

texts:
I'm trying to convert some DirectX code to Ogre3D and was wondering what the following translates to:

pDev->SetTextureStage(0, D3DTSS_TEXCOORDINDEX, 0)
pDev->SetTextureStage(0, D3DTSS_COLORARG1,     D3DTA_TEXTURE)
pDev->SetTextureStage(0, D3DTSS_COLOROP,       D3DTOP_MODULATE)
pDev->SetTextureStage(0, D3DTSS_COLORARG2,     0)

What is the modulation operation happening here? Is the texture getting modulated with the background? Or is it getting zeroed?

I've tried searching for what this means and unfortunately I haven't come across anything meaningful. Any help to shed light on this matter will be much appreciated.


texts: What's the difference between Canvas and WebGL?

texts:
I'm thinking about using CAAT as a part of a HTML5 game engine. One of it's features is the ability to render to Canvas and WebGL without changing anything in the client code. That is a good thing, but I haven't found precisely: what are the differences between those two technologies?

I would specially like to know the differences of Canvas and WebGL in the following regards:

Framerate
Desktop browser support
Mobile browser support
Futureproofability (TM)


texts:
I'm a Unity game developer. I have a bit of a conundrum. I have two enumerators, one that displays text one character at a time, and the other takes the whole text and fades it in over time:

private IEnumerator FadeTo(float aValue, float tValue)
{
    float alpha = GameText.GetComponent<Text>().color.a;
    for (float i = 0; i < 1.0f; i += Time.deltaTime / tValue)
    {
        Color alphaChange = new Color(1, 1, 1, Mathf.Lerp(alpha, aValue, i));
        GameText.GetComponent<Text>().color = alphaChange;
        yield return null;
    }
}
private IEnumerator CharXChar(string text)
{
    for (int i = 0; i < text.Length; i++)
    {
        yield return new WaitForSeconds(0.1f);
        GameText.GetComponent<Text>().text = GameText.GetComponent<Text>().text + text[i];
    }
}

The problem is, I do not know how to get the FadeTo enumerator to modify each character individually. I just need a step in the right direction. Any help would be greatly thanked.


texts: XNA Development on PC but Designing for Xbox 360

texts: I'm working on a project with a buddy, he doesn't have a 360 nor does he have the money to get one right now, but we want our game to be submitted to XBLIG.  So right now we're both designing our game on the PC but we're using adapted 360 controllers.  What are the things we need to keep in mind during the process so that we can "easily" port our game to the 360 from the PC?


texts: Is it normal for the baking timer in Unity to increase?

texts:
I'm having an unusual reaction from trying to bake my scene for Occlusion Culling (the scene was starting to lag and I thought this would optimize it) and I wanted to ask for advice.

What's happening:
This scene and the previous scene are very similar in structure and appearance, only one scene has 2 large models in it. I selected every model/object in the scene that wasn't a character, or had any animation, set it to static, then clicked 'bake' (according to the tutorial I was following and the previous being very successful) and this is where it starts going wrong.

In the previous scene, beside Auto Generate Lighting On is a loading bar, which had 126 Jobs Remaining and took about an hour and a half to do (I was watching a show and each was 30 minutes long, I saw 3 before it completed) but this time, it showed:

Baking... [ETA: 10:26:20]

And when it first started, it had 9 hours instead, then spiked up to 11 after 30 minutes. I'm not sure why there's such a dramatic difference between the two and with my very limited experience on this, I wanted to ask for advice from more experienced Devs.

edit: This is a screenshots of everything that appears in the static dropdown menu:


texts: Unity: How to use delegates with EventManager ? and use variable number of arguments in listenners?

texts:
As answered here, I would like to know how to implement an EventManager with delegate instead of UnityAction for pass arguments. I tried but I did not succeed.

Also, can someone tell me if it's a better solution than following ? And is it possible to change this code for invoke listenners with a variable number of arguments?

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

namespace Assets.Scripts
{
    [System.Serializable]
    public class Event : UnityEvent<System.Object> { }

    public class EventManager : MonoBehaviour
    {

        public static EventManager Instance;

        private Dictionary<string, Event> _eventDictionary;

        private void Awake()
        {
            ...
        }

        public static void StartListening(string eventName, UnityAction<System.Object> listener)
        {
            Event thisEvent = null;
            if (Instance._eventDictionary.TryGetValue(eventName, out thisEvent))
            {
                thisEvent.AddListener(listener);
            }
            else
            {
                thisEvent = new Event();
                thisEvent.AddListener(listener);
                Instance._eventDictionary.Add(eventName, thisEvent);
            }
        }

        public static void StopListening(string eventName, UnityAction<System.Object> listener)
        {
            if (Instance == null) return;
            Event thisEvent = null;
            if (Instance._eventDictionary.TryGetValue(eventName, out thisEvent))
            {
                thisEvent.RemoveListener(listener);
            }
        }

        public static void TriggerEvent(string eventName, System.Object arg=null)
        {
            Event thisEvent = null;
            if (Instance._eventDictionary.TryGetValue(eventName, out thisEvent))
            {
                thisEvent.Invoke(arg);
            }
        }
    }
}


texts: Deferred rendering and gaussian blur - artifacts

texts:
I compute Gaussian blur in two passes (horizontally and vertically). Shaders look like this:

Horizontal blur - fragment shader:

#version 420
layout (location = 0) out vec4 outColor;
in vec2 texCoord;
float PixOffset[5] = float[](0.0,1.0,2.0,3.0,4.0);
float Weight[5] = float[]( 0.2270270270, 0.1945945946, 0.1216216216, 0.0540540541, 0.0162162162 );
float scale = 4.0;

uniform sampler2D texture0;
uniform vec2 screenSize;

void main(void)
{
    float dx = 1.0 / screenSize.x;
    vec4 sum = texture(texture0, texCoord) * Weight[0];
    for( int i = 1; i < 5; i++ )
    {
        sum += texture(texture0, texCoord  + vec2(PixOffset[i], 0.0) * scale * dx ) * Weight[i];
        sum += texture(texture0, texCoord - vec2(PixOffset[i], 0.0) * scale * dx ) * Weight[i];
    }
    outColor = sum;
}

I use deferred rendering and the following
screens shows a diffuse material texture after blurring. I simplified a render loop for the sake of clarity(only one render target - a diffuse material).

A render loop - first case:

bind fbo1
gbuffer stage
unbind fbo1
bind fbo2
read a diffuse texture, render to a temporary texture (full screen quad)
read a temporary texture, horizontal blur, render to a temporary texture (full screen quad)
read a temporary texture, vertical blur, render to a temporary texture (full screen quad)
unbind fbo2
read a temporary texture, render to the default framebuffer (full screen quad)

The final image has artifacts(flickering pixels). Some of them are placed between two  triangles which create the full screen quad.

A render loop - second case:

bind fbo1
gbuffer stage
unbind fbo1
bind fbo2
read a diffuse texture, render to a temporary texture (full screen quad)
read a temporary texture, horizontal blur, render to a temporary texture (full screen quad)
unbind fbo2
read a temporary texture, vertical blur, render to the default framebuffer (full screen quad)

Some artifacts may appear between triangles:

A render loop - third case:

bind fbo1
gbuffer stage
unbind fbo1
bind fbo2
read a diffuse texture, horizontal blur, render to a temporary texture (full screen quad)
unbind fbo2
read a temporary texture, vertical blur, render to the default framebuffer (full screen quad)

The final image doesn't contain artifacts.

How to fix that ? The above code is simplified but normally the first case(render loop order) is most useful, for example: I want to blur a glow texture and use it when shading.


texts: How can I get an asset for my ObjectField?

texts:
I am trying to learn how to use ScriptableObjects.  I have an ObjectField:

Foo myFoo = null;
myFoo = EditorGUILayout.ObjectField("My Foo", myFoo, typeof(Foo), true) as Foo;

I have a Foo in my Scene and in my Assets folder.  In the editor, I can set myFoo to be the Foo in my Scene, but not my Assets folder.  How can I get the prefab from my Assets folder?

(I have tried setting the allow scene objects to false, but I still can't find myFoo in the Assets folder.)

It allows me to drag and drop myFoo in from my Assets folder, but it doesn't stay there.  If I use the Scene one, it does.  But when I search for it in Assets, it is not there.


texts: How can we sell rights to our computer game

texts:
We have an indie team that created a game on PC using Unity. We created the game for a long time and everything was exciting. We just don't even have money for advertising.
We had to borrow $100 for steam direct to release the game into early access. Since there was no money for advertising, the game collected only $66. But we did not receive them either, due to the fact that payments from Steam come only when income is above $100.
I'm looking for a way to sell the rights to this computer game to recoup our costs. We are so desperate that we are ready to sell all the rights to the game together with source code (The game was created for more than two years).
How can we go about finding a buyer for this game?


texts: LibGDX Tiled Map - how to get embedded objects

texts:
I am using LibGDX to learn Game Development. I have reached the phase I am learning to use Tiled Maps.

In Tiled map editor, there is a feature where we can pick a tile in the tile set, go to View -> Tile Collision Editor, and add shape objects to a tile.

I can see that the shapes are saved in the tmx file and associated to the tile.

For testing purpose, I have also made the tile animated (similar option is available under view menu) and the OrthogonalTiledMapRendered automatically animated it (so this information is being accessed somehow).

I wanted to find out if there is anyway to retrieve other information embedded at tile level like the embedded shapes and objects.

Here is the sample xml from the tmx file.

<tile id="7">
    <properties>
        <property name="customProp1" value="customValue1"/>
    </properties>
    <image width="16" height="16" source="black_hole_swallow_4.png"/>
    <objectgroup draworder="index">
        <object id="0" x="0.25" y="0">
            <polyline points="0,0 15.625,-0.25"/>
        </object>
    </objectgroup>
    <animation>
        <frame tileid="5" duration="300"/>
        <frame tileid="7" duration="200"/>
    </animation>
</tile>


texts: How can I deduce my RPG lags for better performance?

texts:
Okay, so I've started making a game using Khan Academy's Processing JavaScript, and I'm trying to delag it a bit since the framerate is very shaky. So, I've taken the advice of someone, and they told me instead of new object_name(), I could instead use something like object_name.create() by having this code:
Object.constructor.prototype.create = function() {
    var obj = Object.create(this.prototype);
    this.apply(obj, arguments);
    return obj;
};

So, I'm assuming it's helping since the framerate improved a bit, but not at all that much. I've been using a lot of OOP, and people have told me that Khan Academy's memory is acting weird, so it's not as good to use OOP, but I'm used to using it, so I'd like to see what kind of things there could be to help improve my program in framerate. I'm planning to check if the NPCs and enemies are in range, then draw them, but I'm not sure if this would help, because I'm not very familiar with the computers and how fast they would run certain things. Thank you.
For reference, this is my game Quests of a Warrior
This is the comment that someone posted that I happened to see, and that's why I used the object_name.create() for now. Discussion post (expand_key will lead you there)
If you are unfamiliar with Processing JavaScript, you can go to the documentation, although it doesn't include much (Khan Academy version). You'll find it here, but you can also glance at the real Processing JavaScript (notice that some can't be used for Khan Academy purposes) here
EDIT: I've figured out that you can do object pooling! The method shown here uses gEntityObjectPool. Is this in pure JavaScript?


texts: Why the changes to the children and grand children objects not taken into account?

texts:
Currently I am working on a framework for a game utilising the SFML graphics library and in one of the classes representing a renderable object in the framework there is an sf::Sprite that is used to represent and draw the object. The issue is that the object instance of class 1 that is represented by the sf::Sprite (which is a private member variable of class 1), is in turn a private member variable of class 2 of which an instance is in turn a private member variable of class 3 from which the sprites belonging to the instances of class 1 and 2 must be retrieved to be rendered in the renderer class. In classes 1, 2 and 3 there are appropriate getter functions like so:

class One
{
     public:

     //Functions
     One();
    ~One();

     sf::Sprite getOne(){ return oneRep;};
    animate();

     private:
     //One variables
     sf::Texture oneTexture;
     sf::Sprite oneRep;

};

class Two
{
     public:

     //Functions
     Two();
    ~Two();
     One getCOneInst(){ return cOneInst;};

    private:

    //Class 1 private member variable
    One cOneInst;
};

class Three
{
    public:

    //Functions
    Three();
    ~Three();

    initTestSprite();
    One getCTwoInst(){ return cTwoInst;};

private:

    //Class 2 private member variable
    Two cTwoInst;
};

class Renderer
{
    public:

    //Functions
    Renderer();
    ~Renderer();

    private:
    //Class 3 private member variable
    Three cThreeInst;

    //Test Class One private member variables
    One testCOneInst;
    sf::Texture oneTexture;
    sf::vector2f position

};

Which are used to access the sprites representing the instances of class 1 and 2 from the instance of class 3 so that the renderer class may render them to the screen of the game. The issue is that: if an instance of class 1 (represented by the sf::Sprite) is constructed in the renderer class like so:

initTestSprite()
{
    testCOneInst.setTexture(oneTexture);
    testCOneInst.setTextureRect(textRect);
    testCOneInst.setColor(sf::Color(255, 255, 255, 255));
    testCOneInst.setPosition(position);
}

And should the getter function be called on the instance of classOne to retrieve the sprite representing the instance of classOne for rendering in the render class

window.draw(testCOneInst.getOne());

The render class through the function above will render the sprite representing the instance of class One: testCOneInst correctly. The problem and the question is: When the sprite representing the instance of class One must be retrieved from the instance of class Two in which the class One instance is a private member variable – the functions that should be able to be called on the class One sprite to manipulate the texture being applied to it, for example setting the IntRect texture to a new location in order to animate the sprite representing the instance of class One does not function correctly – the original texture is still applied to the sprite representing the instance of class One, if the sprite is accessed by the renderer class from  the instance of class 2 and in turn the instance of class 3 like so:

cThreeInst.getCTwoInst().getCOneInst().animate();

Before rendering the sprite with the updated texture changes to the window like so:

window.draw(cThreeInst.getCTwoInst().getCOneInst().getOne());

The changes to the IntRect of the sf::Sprite instance representing class 1 will not be show when the sprite is rendered – and the question is why?


texts: XNA Content Pipeline With Map Creation Utility

texts:
I've been looking into how to use the XNA Content pipeline appropriately for a game I am working on. I have however been having a hard time wrapping my head around it and am not sure on the best way to proceed.

The specific example is, I have a top down 2-d RPG style game. I want to create a utility (probably Windows Forms) that will allow me to easily create and edit maps. Each map consists of 1 or more graphic layers, each layer containing a N x N grid of tiles. In turn each tile starts out as a bitmap.

Given the above information I see a few ways to proceed:

Store the map info in an XML file compatible with the Content Pipeline XML loader. Each tile is stored as a string reference to the corresponding texture asset. Texture assets are added in the game project.
Store the map info in an XML file compatible with the Content Pipeline XML loader.
Each tile is stored as the path to the corresponding .bmp/.png files.

Now there are things that I really don't like about both approaches. The main issue with approach one is that the map creation and the .xnb texture asset creation are completely separate. The .xml map file is created by the utility, while the texture asset is added to my content in my game. This becomes an issue trying to make sure the .xml map file and all the texture assets in the project stay in sync.

Approach two would allow me to keep all the appropriate image file next to the map files using the map utility. However, it seems like I shouldn't have to do something like this. Also I would need to be more intelligent about loading the maps so that I am not rapidly loading the same image off disc for each tile.

So my question is: If you want to add a content generation utility (like a map editor), what is the best way to make sure that the custom content (map file) stays in sync with the texture assets. Also, keep in mind that in my map editor I would need the ability to load and display the texture assets.

Any input is much appreciated.


texts: How do I find the 2D direction to a 3D location?

texts:
I'm writing a 3D space flightsim, and I'm trying to display a 2D arrow on screen that points to the player's selected target. To clarify, the arrow needs to point in the direction that the player has to turn to reach the target.

I've tried several approaches but I can't seem to make this work for all cases. My current attempt involves constructing a plane from the player's local X/Y, projecting the target position onto it (to make the calculation 2D) then calculating the angle between the player's up and the vector to the projected target position.

I can't help but think I'm over-thinking this and there must be a better, simpler way. Anyone have any suggestions?

UPDATE:

Based on Sam's answer, I've tried the following code:

//Find the direction to the target, and normalize it
kglt::Vec3 target_dir = (target_pos - ship_pos);
target_dir.normalize();

kglt::Vec3 v1, v2;
v1 = ship_up.cross(ship_dir);
v2 = ship_up.cross(target_dir);
v1.normalize();
v2.normalize();

//Get the angle of rotation for the arrow
float angle = kmRadiansToDegrees(atan2(ship_up.dot(v1.cross(v2)), v1.dot(v2)));

But the returned angle is always around 180.0 (although normally -179.xx). Is there any obvious error somewhere? I'll continue debugging and update if I figure it out!

UPDATE2

Nevermind, the bug isn't in this section of code. My bad!


texts: How can I efficiently form terrain from a large number of cubes in XNA?

texts:
I have a project with a floor built from with small cubes (100x100 of them).
If I exceed that size, the performance of my game suffers. How can I efficiently draw a larger number of identical models?

Here's how I'm currently drawing the ground:

    //Function to draw my ground ( 100 X 100 X 1)
    public void DrawGround(GameTime gameTime)
    {
        // Copy any parent transforms.
        Matrix[] transforms = new Matrix[this.model.Bones.Count];
        this.model.CopyAbsoluteBoneTransformsTo(transforms);

        //loop 1 cube high
        for (int a = 0; a < 1; a++)
        {
            //loop 100 along cube
            for (int b = 0; b < 100; b++)
            {
                //loop 100 cubic wide
                for (int c = 0; c < 100; c++)
                {
                    // Draw the model. A model can have multiple meshes, so loop.
                    foreach (ModelMesh mesh in this.model.Meshes)
                    {
                        // This is where the mesh orientation is set, as well
                        // as our camera and projection.
                        foreach (BasicEffect effect in mesh.Effects)
                        {
                            effect.EnableDefaultLighting();
                            effect.World = transforms[mesh.ParentBone.Index] * Matrix.CreateTranslation(this.position);
                            effect.View = this.view;
                            effect.Projection = this.projection;

                        }

                        // Draw the mesh, using the effects set above.
                        mesh.Draw();
                    }
                }
            }
        }
    }

I think it is better to use the a vertex buffer, but I have not found a tutorial for that I want to do. Can you explain how I can do this?


texts:
I have one way - xml and code like this:

<Texture file="file_name.jpg">
  <Sprite id="ID_SPRITE_1" coordinates="0 0 64 64"/>
  <Sprite id="ID_SPRITE_2" coordinates="64 0 64 64"/>
  <Sprite id="ID_SPRITE_4" coordinates="128 0 64 64"/>
</Texture>

then parse and load it, when application starts, then use resources by id.

What another ways to describe paths and propeties of resources used by developers and why?


texts: How to damp the velocity of an object only in one axis in Box2d?

texts:
I want to damp the velocity of a ball linearly on the x-axis. but when applying linear damping on the ball, the damping also applies in the y-axis which makes it look like its floating.

I tried to refer the Manual but it says: "Damping parameters should be between 0 and infinity, with 0 meaning no damping, and infinity
meaning full damping. Normally you will use a damping value between 0 and 0.1. I generally do not use
linear damping because it makes bodies look like they are floating."

So how can I damp the ball in the axis while there is no damping in the y-axis


texts: How I can count how many time gameOver scene is loaded?

texts: I'm building a game using unity 3d and I want to add an interstitial ads to it, but I want it to appear after the player lost every 3 times. So when the player loses for the first time the ads will appear, and when he loses for the second and third time, nothing appears until he lost for fourth time.


texts: Image 1 becomes image 2 with sliding effect from left to right?

texts:
I would like to show a second image appearing while a "door" is closing on my character. I've got my character in the middle of the screen and a door coming from the left. When the door passes my character, I would like to have this second image appearing little by little.

So far, I've gotten by with fadingOut the character and then fadingIn my second image of the character at the same position when the door is completely closed, but I would like to have both of them at the same time. (the effect that image 1 becomes image 2 when the door is sliding from left to right). Would you know how to do this with Cocos2d?

Here are the images :

at first, the character is blue, and the door is coming from the left :

Then, behind the black door, the character becomes red, but only behind this door, so it stays blue when the door is not on him, and will become completely red when the door passes the character :

EDIT : with this code, the black door hides the red and blue rectangles : (And if i add each of my layers at a different depth, and only use GL_LESS, same thing)

blue.position =  ccp( size.width*0.5 , size.height/2 );
        red.position =  ccp( size.width*0.46 , size.height/2 );
        black.position =  ccp( size.width*0.1 , size.height/2 );

        glEnable(GL_DEPTH_TEST);

        [batch addChild:red z:0];
        [batch addChild:black z:2];

        glDepthFunc(GL_GREATER);

        [batch addChild:blue z:1];

        glDepthFunc(GL_LESS);

        id action1 = [CCMoveTo actionWithDuration:3 position:ccp(size.width,size.height/2)];
        [black runAction: [CCSequence actions:action1, nil]];


texts: How do I get the current location when using slick 2D library?

texts: I'm developing a map kind of simple game using slick 2D library, and I want to get the current location of the user.  When the user runs into a special location (ex: hole) to indicate that is dangerous. How can I achieve this?  I'm a new comer to games.


texts: How can I improve the "smoothness" of a 2D side-scrolling iPhone game?

texts:
I'm working on a relatively simple 2D side-scrolling iPhone game.  The controls are tilt-based.  I use OpenGL ES 1.1 for the graphics.  The game state is updated at a rate of 30 Hz... And the drawing is updated at a rate of 30 fps (via NSTimer).  The smoothness of the drawing is ok... But not quite as smooth as a game like iFighter.  What can I do to improve the smoothness of the game?

Here are the potential issues I've briefly considered:

I'm varying the opacity of up to 15 "small" (20x20 pixels) textures at a time... Apparently varying the opacity  in this manner can degrade drawing performance
I'm rendering at only 30 fps (via NSTimer)... Perhaps 2D games like iFighter are rendered at a higher frame rate?
Perhaps the game state could be updated at a faster rate?  Note the acceleration vales are updated at 100 Hz... So I could potentially update part of the game state at 100 hz
All of my textures are PNG24... Perhaps PNG8 would help (due to smaller size etc)


texts: Procedural object generation and unique identification

texts:
My question relates to procedural content generation and data management of the emerging objects in a database.

I assume a networked game, with a server-client model. Unspecified objects in the game world are generated while the game is running with procedural algorithms (for example perlin noise). The players (/clients) can modify the properties of these objects, but have to notify the server of these changes. How could this communication address unique objects, so that both the server and the client know of which object they are speaking?

Not only the inner properties of the objects can differ, but also visible, such as the position. When the player wants to select one of these objects the game has to find out the id - does anyone know which methods or algorithms can accomplish that?


texts: Is there a tool to automatically pack individual textures into one big png?

texts:
I'm currently was working on a texture pack for minecraft (but this question is not restricted to that). All terrain textures are squared and stored in one big terrain.png. (FYI that's from Glimmar's Steampunk pack). I'd like to store each texture in an individual file and have same automated process pack them into the terrain.png later on (maybe leaving the not yet created ones their default). At the moment I do this manually by copy/pasting them with gimp (at least the raster helps a lot here) but I'd really like to do this automatically. Basically this seems to be what happens behind the scenes of the Painterly pack customizer already. So,

  Is there a tool that replaces some squarespolygons* in a png file with new ones (also png), the position of which might be configured in a separate file?

edit Some automated resizing for different resolution versions might be nice as well...

edit2 Meanwhile I learned that "position [...] configured in a separate file" means atlas, and since the question originated from Minecraft texture packs (IIRC the format got changed meanwhile), the ideal tool would allow for using an existing atlas to replace some of the tiles

*) might as well ask the general case


texts: How were old mobile games (J2ME/MIDP/JAR) monetized? (2000s era)

texts:
When I was in school, me and my friends were just exchanging *.jar files via IrDA and Bluetooth.
However now I realize, that old phone games were of high quality and whole studios stood behind them.
What was the "official" way of getting a game to your old mobile phone? How did mobile game developers get their revenue those days?


texts:
I have this code for creating a light:

            GameObject lightGameObject = new GameObject ("Light1");
            lightGameObject.AddComponent (typeof(Light));
            lightGameObject.light.color = Color.white;

            lightGameObject.light.intensity = 0.5f;

I want to change the light's intensity to 0.5f but when I run the game, the intensity's still at 1.


texts: Background music not stopping while game is set to paused

texts:
I am implementing pause game functionality in a Unity3D game using the following script

    public class PauseGame : MonoBehaviour
    {
        /// <summary>
        /// class to pause the game using Time.timeScale and
        /// implement the related behaviours associated the game
        /// </summary>

        #region Fields

        // Boolean variable that informs script if game should be paused or not, false by default.
        private bool isPaused = false;

        #endregion

        #region MonoBehaviour Messages

        /* ----------------------------------------
         * At Start,
         *
         */
        void Start()
        {

        }

        /* ----------------------------------------
         * Whenever 'ESC' key is pressed, toggle 'isPaused' boolean
         * and call SetPause() to pause/resume game
         */
        void Update()
        {
            if (Input.GetKeyDown(KeyCode.Escape))
            {
                isPaused = !isPaused;
                SetPause();
            }

        }

        #endregion

        #region Methods

        /* ----------------------------------------
         * A function to pause/resume the game
        */
        public void SetPause()
        {
            Debug.Log("SetPause");

            // Invert 'isPaused' boolean and convert it into a float variable, being true = 1; and false = 0f.
            float timeScale = !isPaused ? 1f : 0f;

            // Set the Time Scale as 1(game runs normally) or 0(game pauses)
            Time.timeScale = timeScale;

        }
        #endregion
    }

All the game elements pause as expected using the above, except the background music. I can pause the background music by additionally referencing the AudioSource and disabling it while timescale is set to 0. However, I was wondering whether it was a bug. Kindly suggest.


texts:
I've seen some tutorials on programming a good game loop, but none mention where (in the game code) I should call it.

My guess is I should call it from the main() method. Am I right? Is there another way?

Second question:

I'm using Java, and my game loop is a method in the same class as main(). When I tried to call it, the compiler did not recognize the gameLoop() method, because it wasn't static. So I changed it to static, as well as render() and update().

But it just doesn't make sense to me. What should I do in this case?


texts: Memory usage increasing ~10kb every frame

texts:
I am currently developing a game for Android (using the SDK) and have been trying to reduce the memory usage. I have discovered that during each frame, the memory usage increases by about 10kb. The game runs at 60fps so adds over half a megabyte every second which, over time, significantly increases the total memory usage of the game.

This is not a huge problem as, after a short while, the memory is released by the garbage collector and it returns to a normal level. Despite this, I would like to know if such per-frame memory increases are normal for games developed in Java. If not, are there any tips or solutions to reducing the framely memory increase (other than not instantiating objects in every update/draw call - I have made sure I'm not doing this).

This is the draw method for my game:

public void draw(Canvas canvas){
    if(screenScaleX > 1f || screenScaleY > 1f)
        canvas.scale(screenScaleX, screenScaleY);

    canvas.drawColor(Color.BLACK);
    if(skipFrames > 0){
        skipFrames--;
        return;
    }

    pp.preDraw(this, canvas);

    scrollX = (player == null ? 0 : player.getBounds().getX()) * SCALE_FACTOR - 1280f / 2f;
    scrollY = (player == null ? 0 : player.getBounds().getY()) * SCALE_FACTOR - 720f / 2f;

    if(battle != null)
        battle.draw(this, canvas);

    popTranslate(canvas);

    canvas.scale(SCALE_FACTOR, SCALE_FACTOR);

    synchronized(objects){
        if(objectModCount > 0){
            Collections.sort(objects, GameObject.RenderLayer.RENDER_COMPARATOR);
            objectModCount = 0;
        }

        uCopy.clear();
        uCopy.addAll(objects);
        for(GameObject obj : uCopy){
            if(battle != null)
                if(!(obj instanceof Dialog))
                    continue;
            if(!obj.shouldScale())
                canvas.scale(SCALE_FACTOR_1, SCALE_FACTOR_1);

            obj.draw(this, canvas);

            if(!obj.shouldScale())
                canvas.scale(SCALE_FACTOR, SCALE_FACTOR);
        }
    }

    pp.draw(this, canvas);

    canvas.scale(SCALE_FACTOR_1, SCALE_FACTOR_1);

    pushTranslate(canvas);

    windows.draw(this, canvas);
    guis.draw(canvas, this);
    pp.postDraw(this, canvas);

    if(FRAME_SYNC){
        if(delta > 17L && delta < 33L){
            dSyncDiff = 33 - delta;
            try{
                Thread.sleep(dSyncDiff);
            }catch(InterruptedException e){
                e.printStackTrace();
            }
        }
    }

    frameCounter++;

    if(screenScaleX > 1f || screenScaleY > 1f)
        canvas.scale(1f / screenScaleX, 1f / screenScaleY);
}

As can be seen in the code above, I do not instantiate any objects, even primitives so the memory should not increase. All of my rendering and update code follows this sort of style so should be the same. Unless Androids SDK is memory inefficient (which I don't imagine it is), I really cannot see why or how the memory increase so much every frame. I have moved all primitives that are used to members of the class that owns this draw method and done the same for all others.

Update: Could it possibly be due to unavoidable creation of strings. For example, because strings are immutable, I would have to create a new string every time I want to update the contents of some text being drawn to the screen (and this does happen framely).


texts: How can I implement persistent state for objects defined in a level?

texts:
I am developing a 2D Metroidvania which consists of a series of interconnected levels that can be revisited.

Each level is represented by a Tiled TMX file in which I have specified where various objects of different sprite classes spawn (for example, enemies, pickups, levers, etc.). When starting a new game, loading a saved game, or changing a level, my game loop runs through the appropriate TMX file and generates all the objects in that level.

I handle level changes in the following way: If the Player object intersects a Portal object, a change_map() method is called which loads a new map (the one associated with the intersected portal) and positions the player at the appropriate position on the new map.

Some of my objects have states which I would like to be persistent through level changes and saving and quitting the game. For example, if a player unlocks a door and the state attribute of the door is set to "open," I would like the door to be open when the player returns. I want something similar for levers, which can be set to left or right, and various other objects. Further, the player will sometimes have collected items which I do not want to respawn when the player revisits the area.

My question is thus how can I handle this kind of persistence?

I am working in Python, although I think you can abstract away from that.


texts: Directional light view frustum stabilisation

texts: Calculating directional light view frustum based on scene objects(bounding frustum) results in noticeable scene jittering on camera movement in CSM and non-CSM rendering code paths. What are the techniques to reduce or eliminate these jittering artifacts?


texts: How does the 3G network assign IP to smartphones?

texts:
I am playing a game on the 3G network using Android or Iphone.
Suppose I am moving from one cell to another; Will the IP Address change?
If yes, then how can I continue the same game while changing the base station, as my IP address is already registered in The game server?
Is there something DHCP?


texts: Unity SphereCast HitInfo Give me an interpolation of the normal surface?

texts:
I'm doing a SphereCast for a GroundCheck of a player.
I have my Raycast hitInfo, and here in the picture at the left, I Debug.drawRay in black the direction of the hitInfo.normal every frame

It seems like hitInfo.normal give me an interpolation of the normal, not the real normal of the surface...

I only want the real normal of the surface... (red normals I have draw on the right), and may be the green one (the perfect normal between 2 surface), but if I can have only the red one, it would be great

How can I do it ?

Thanks !


texts: Unable to check Cardboard XR Plugin in Unity

texts: I tried to create a project for Cardboard VR. I imported the git VR package from the Google Cardboard XR Plugin for Unity repository on GitHub. Then, in Project settings -> XR Plug-in Management I tried to check Cardboard XR Plugin, The package is not installed, I got the error message which is shown the below screenshot.


texts: Which Unreal Engine 4 project files can I ignore in source control?

texts:
I want to put an Unreal Engine 4 project under source control with git. (I know the editor has Perforce and Subversion support, but I don't care for those.)

What folder and files do I include in the repository and which can I ignore?

The way I see it, the following is needed: Config, Content, Source, *.sln, *.uproject

Things that I can ignore: Binaries, DerivedDataCache, Intermediate, Saved, *.suo, *.sdf, *.opensdf

Is this correct?


texts:
I'm using Unity 5.3.x (free version) on a Windows machine.
I would like to build my simple desktop game either for Windows and Linux, but Linux (and Mac) build is disabled.
Am i missing something ?

Thanks


texts: Bullet holes on curved surfaces and corners

texts:
So right now I am making an FPS game where the gun creates bullet holes (plane with texture) on impact, but there is a problem with that, if I shoot at the edge the plane will stick out and also bullet holes will not look proper when I shoot at a curved surface. I know there's at least 2 ways one is shaders and another mesh manipulation, but I could not find any tutorials on how to do it and never understood neither of them. Is anyone able to explain in detail exactly how I would achieve the effect?
Thanks in advance.


texts:
My text doesn't seem properly align to top left even I already set it in Rect Transform.

Please advice. Thank you.


texts: Transformations between coordinate systems

texts:
In a graphics engine, I have three three-dimensional orthogonal coordinate systems, O, A and B.

A and B are the result of two different transformations from O. I now want to calculate the transformation matrix R, which takes you from A to B. R should be the rotation and translation with respect to coordinate system A, not the original coordinate system O.

Which of the following is correct?

(1) B = A * R or (2) B = R * A

By doing some simple worked examples, it seems that (1) is correct. However, my intuition says that (2) is correct, because the transformation to A should be applied before the transformation to B, via R. Which is it?

Thanks :)


texts: Do the dynamic shader linking concepts introduced in DirectX11 ShaderModel 5.0 still work in DirectX12? In the documentation the reflection API is still available (e.g. ID3D12LibraryReflection), claiming it is provided especially for the shader linking technology, but I couldn't find other important interfaces like ID3D11FunctionLinkingGraph or ID3D11ClassLinkage in DX12.


texts: How do I set decimal values in 1D blend tree?

texts:
I have created a 1D blend tree.
It is being used for a 3rd Person Controller.
The blend tree consists of 3 animations:

aim pistol down to the floor
aim pistol at middle of the screen (straight forward)
aim pistol up in the sky

To determine the blend value (which animation should be played), I inspect the current mouse position and convert it a value between 0 (aim low) and 1 (aim high). The middle position would be 0.5.
Here is my code:
float f = Input.mousePosition.y / Screen.height;

Debug.Log("Blendval " + f.ToString());//
_animator.SetFloat("BlendVal", f);

I tried to insert these decimal values in the blend tree like this:

However, this doesn't work.
Unity converts my "0.5" to 0.
I don't see why.
I can instead use integers like this:

Why doesn't Unity allow me to use 0, 0.5 and 1?
Why do I have to use "other" values like -1, 0 and 1?
Thank you!
Edit:
I don't understand what is going on.
I have just typed 0.5 here instead of 0:

And then suddenly I could enter the values as desired, and even "Automate Threshold" would do what I expected:

But now it won't accept negative values anymore.
Strange.


texts: Why would I lose the D3D device during an HLSL unroll?

texts:
I have a pixel shader that downsamples a texture from one size to another. The downsample shader uses a nested 'for' loop to traverse the uv coordinates. When the for loop executes more than four times( [unroll(8)] for example ) the graphics device is lost and all hell brakes loose...Here is shader code:

void DownsamplePass_Pixel_Shader( in float4 Position : POSITION0,
           in float4 PositionSS : VPOS, out float4 vEnergy : COLOR0 )
{
    float width = LastMipInfo.x;
    float height = LastMipInfo.y;
    float mip = LastMipInfo.z;
    float mult = LastMipInfo.w;
    float4 vPos = PositionSS;
    float4 vColor = 0;
    int ncPixels = 0;

    // depending on the size of the visibility buffer( texture to downsample )
    //      it may be necessary to sample more than a 2x2 block of pixels( if the size is greater than twice the target )
    //      this is only necessary for the first pass
    if( bFirstDownsamplePass )
    {
        [unroll(8)]
        for( int y = 0; y < mult; ++y )
        {
            [unroll(8)]
            for( int x = 0; x < mult; ++x )
            {
                float2 vCoord = float2( ( vPos.x * 2 * mult ) / width + x * ( 1 / width ), ( vPos.y * 2 * mult ) / height + y * ( 1 / height ) );
                float4 vTexel = tex2Dlod( g_SamplerMip, float4( vCoord, 0, mip ) );
                if( all( vTexel.rgb == 0 ) )
                    continue;

                vColor.rgb += vTexel.rgb * tex2D( g_SamplerMultiplier, vCoord ).rgb;
                ncPixels++;
            }
        }
    }
    else
    {
        float2 vCoords[ 4 ];
        vCoords[ 0 ] = float2( ( vPos.x * 2 ) / width, ( vPos.y * 2 ) / height );
        vCoords[ 1 ] = float2( vCoords[ 0 ].x + ( 1 / width ), vCoords[ 0 ].y );
        vCoords[ 2 ] = float2( vCoords[ 0 ].x, vCoords[ 0 ].y + ( 1 / height ) );
        vCoords[ 3 ] = float2( vCoords[ 1 ].x, vCoords[ 2 ].y );

        // calc average energy
        float4 vColor = 0;
        int ncPixels = 0;
        for( int i = 0; i < 4; ++i )
        {
            float4 vTexel = tex2Dlod( g_SamplerMip, float4( vCoords[ i ], 0, mip ) );
            if( all( vTexel.rgb == 0 ) )
                continue;

            vColor.rgb += vTexel.rgb;

            ncPixels++;
        }
    }

    vEnergy = float4( vColor.rgb / max( ncPixels, 1 ), 1 );
}

I could just define each uv coordinate but I'm interested in knowing why this problem occurs!


texts:
right now in my game, four enemies spawn in four spawn points with a delay, but what I want to do is that if you don't kill the enemy after a couple seconds, an animation (it's an animation of a scratch, basically to let the player know it has been attacked) appears.

Right now I have a script that display an image (it's an image because I was testing the scripts), but now I want to change the image for the animation but after trying and failing a lot of times I decided to ask here, and hopefully someone can help me.

This is the script of the "attack", and it's attached to the enemy prefab:

public Image TargetImage;

void Start ()
{
    TargetImage.enabled = false;
}

public void spawnAttack(){
    StartCoroutine (playerIsAttacked (5, TargetImage));
}

public IEnumerator playerIsAttacked (float t, Image im)
{
    yield return new WaitForSeconds (t);
    TargetImage.enabled = true;
}

}

and this is in the timed spawn script:

public class TimedSpawn : MonoBehaviour {

public GameObject spawnee;
public bool stopSpawning;
public float spawnTime;
public float spawnDelay;

void Start () {
    InvokeRepeating ("SpawnObject", spawnTime, spawnDelay);
}

public void SpawnObject (){
    GameObject newSpawn = Instantiate (spawnee, transform.position, transform.rotation) as GameObject;
    newSpawn.GetComponent <enemyAttack> ().spawnAttack ();

    if (stopSpawning) {
        CancelInvoke ("SpawnObject");
    }
}

}


texts: Better way of handling the relation between Bullet and Enemy

texts:
I was wondering how should I design this relation in terms of "better OOP"?

Should I have a Singleton EnemyManager which contains a list of enemies (EnemyList); then Bullets can access the EnemyList to check for collision?

Or should I just pass EnemyManager as a reference to each Bullet so Bullets can still access the EnemyList but not in a Singleton way?

Or is there any other better ways of doing?

Please advise.