# Question
Title: How to change position of a gameobject from another gameobject's script?
Earlier I had a script attached to my player for its movement using keyboard inputs. Then I decided to do the same thing using onscreen UI buttons so I created an empty gameobject inside my canvas and added the buttons to it and also attached a new script to it which would change the position of my player on pressing those buttons. But my buttons don't work for obvious reasons since I am not actually changing my player's position yet. If I were on the same gameobject like before I would simply do:

```
transform.position = <new position here>;

```

Can anyone tell me how to do this exact thing on another gameobject's script?

# Answer
> 4 votes
```
//This script will explain how to reference a gameObject
using UnityEngine;

public class HowToReference : MonoBehaviour {

    //We start of by decalring a class variable of the type GameObject. This can be public if we  want to asing it from the editor.
    public GameObject myFirstObjectReference;
    // Use this for initialization
    void Start () {
        //Now we will explroe severel ways of how to asing our object from code.
        myFirstObjectReference = GameObject.Find("Name of the object in the scene");//This will search for the object by name;
        myFirstObjectReference = GameObject.FindGameObjectWithTag("The tag of the game object");//This will find a gameObject with the specified tag
        //By making the field public in the declaration we could also simply use drag and drop to asing the reference from the unity editor. There are plenty of tutorials online for this.
    }

    // Update is called once per frame
    void Update () {
        // Now that we have a reference we can do what ever we want with the object. For example :
        myFirstObjectReference.transform.position = new Vector3(1, 1, 1);
    }
}

```

---
Tags: c#, unity
---


# Question
Title: How to Initialize OpenGL without 3rd party libraries?
How can I initialize OpenGl in C++ without any 3rd party library such as glew, freeglut or glut. How would I initialize basic OpenGL requirements, like the context?

I am running Windows 10, and I use Visual Studio.

# Answer
On Windows, the process goes like this:

* Create a Win32 window normally (code not included, ask if you need it)
* Create a dummy GL context
* Query the available pixel formats
* Create the actual GL context (in the below code inside `CreateRenderer()`, context version is 4.1)
* Query OpenGL function pointers. Including code for them all would be too big so here's one.

Query the function pointer:

```
HMODULE libgl = LoadLibraryA("opengl32.dll");
PFNGLCULLFACEPROC glCullFace = GetProcAddress((HMODULE)libgl, "glCullFace");

```

Here's the rest of the code (error handling omitted for brevity):

```
namespace Dummy
{
    HWND hwnd;
    HDC hdc;
    HGLRC hrc;
    WNDCLASSEX wcl;
}

LRESULT CALLBACK DummyGLWndProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam )
{
    switch (msg)
    {
    case WM_CREATE:
    {
        Dummy::hdc = GetDC( hWnd );

        if (!Dummy::hdc)
        {
            return -1;
        }
    }
        break;

    case WM_DESTROY:
        if (Dummy::hdc)
        {
            if (Dummy::hrc)
            {
                wglMakeCurrent( Dummy::hdc, 0 );
                wglDeleteContext( Dummy::hrc );
                Dummy::hrc = 0;
            }

            ReleaseDC( hWnd, Dummy::hdc );
            Dummy::hdc = 0;
        }

        PostQuitMessage( 0 );
        return 0;

    default:
        break;
    }

    return DefWindowProc( hWnd, msg, wParam, lParam );
}

void CreateDummyGLWindow()
{
    Dummy::wcl.cbSize = sizeof( Dummy::wcl );
    Dummy::wcl.style = CS_OWNDC;
    Dummy::wcl.lpfnWndProc = DummyGLWndProc;
    Dummy::wcl.hInstance = reinterpret_cast<HINSTANCE>(GetModuleHandle( nullptr ));
    Dummy::wcl.lpszClassName = "DummyGLWindowClass";

    if (!RegisterClassEx( &Dummy::wcl ))
    {
        OutputDebugStringA( "Failed to register dummy window class!\n" );
    }

    Dummy::hwnd = CreateWindow( Dummy::wcl.lpszClassName, "", WS_OVERLAPPEDWINDOW, 0, 0, 0, 0, 0, 0, Dummy::wcl.hInstance, 0 );

    Dummy::hdc = GetDC( Dummy::hwnd );

    PIXELFORMATDESCRIPTOR pfd = { 0 };

    pfd.nSize = sizeof( pfd );
    pfd.nVersion = 1;
    pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL;
    pfd.iPixelType = PFD_TYPE_RGBA;
    pfd.cColorBits = 24;
    pfd.cDepthBits = 24;
    pfd.iLayerType = PFD_MAIN_PLANE;

    int pf = ChoosePixelFormat( Dummy::hdc, &pfd );

    if (!SetPixelFormat( Dummy::hdc, pf, &pfd ))
    {
        OutputDebugStringA( "Failed to set dummy window pixel format!\n" );
    }

    Dummy::hrc = wglCreateContext( Dummy::hdc );

    if (!wglMakeCurrent( Dummy::hdc, Dummy::hrc ))
    {
        OutputDebugStringA( "Failed to make current dummy OpenGL context!\n" );
    }
}

void DestroyDummyGLWindow()
{
    if (Dummy::hwnd)
    {
        PostMessage( Dummy::hwnd, WM_CLOSE, 0, 0 );

        BOOL bRet;
        MSG msg;

        while ((bRet = GetMessage( &msg, 0, 0, 0 )) != 0)
        {
            TranslateMessage( &msg );
            DispatchMessage( &msg );
        }
    }

    UnregisterClass( Dummy::wcl.lpszClassName, Dummy::wcl.hInstance );
}

void ChooseAntiAliasingPixelFormat( int& outPixelFormat, int samples )
{
    const int attributes[] =
    {
        WGL_DRAW_TO_WINDOW_ARB, GL_TRUE,
        WGL_ACCELERATION_ARB, WGL_FULL_ACCELERATION_ARB,
        WGL_COLOR_BITS_ARB, 24,
        WGL_ALPHA_BITS_ARB, 8,
        WGL_DEPTH_BITS_ARB, 24,
        WGL_STENCIL_BITS_ARB, 8,
        WGL_DOUBLE_BUFFER_ARB, GL_TRUE,
        WGL_SAMPLE_BUFFERS_ARB, samples > 0 ? 1 : 0,
        WGL_SAMPLES_ARB, samples,
        WGL_FRAMEBUFFER_SRGB_CAPABLE_ARB, GL_TRUE,
        0, 0
    };

    PFNWGLCHOOSEPIXELFORMATARBPROC wglChoosePixelFormatARB = (PFNWGLCHOOSEPIXELFORMATARBPROC)wglGetProcAddress( "wglChoosePixelFormatARB" );
    int returnedPixelFormat = 0;
    UINT numFormats = 0;
    BOOL status = wglChoosePixelFormatARB( Dummy::hdc, attributes, 0, 1, &returnedPixelFormat, &numFormats );

    if (status != FALSE && numFormats > 0)
    {
        outPixelFormat = returnedPixelFormat;
    }
}

void CreateRenderer( int samples )
{
    PIXELFORMATDESCRIPTOR pfd = { 0 };
    pfd.nSize = sizeof( pfd );
    pfd.nVersion = 1;
    pfd.dwFlags = PFD_DOUBLEBUFFER | PFD_SUPPORT_OPENGL | PFD_DRAW_TO_WINDOW | PFD_SUPPORT_COMPOSITION;
    pfd.iPixelType = PFD_TYPE_RGBA;
    pfd.cColorBits = 24;
    pfd.cDepthBits = 24;
    pfd.iLayerType = PFD_MAIN_PLANE;

    CreateDummyGLWindow();
    int pixelFormat = 0;
    ChooseAntiAliasingPixelFormat( pixelFormat, samples );
    PFNWGLCREATECONTEXTATTRIBSARBPROC wglCreateContextAttribsARB = (PFNWGLCREATECONTEXTATTRIBSARBPROC)wglGetProcAddress( "wglCreateContextAttribsARB" );
    DestroyDummyGLWindow();

    if (!SetPixelFormat( WindowGlobal::hdc, pixelFormat, &pfd ))
    {
        OutputDebugStringA( "Failed to set pixel format!\n" );
    }

    int otherBits = 0;

    const int contextAttribs[] =
    {
        WGL_CONTEXT_MAJOR_VERSION_ARB, 4,
        WGL_CONTEXT_MINOR_VERSION_ARB, 1,
        WGL_CONTEXT_FLAGS_ARB, WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB | otherBits,
        WGL_CONTEXT_PROFILE_MASK_ARB, WGL_CONTEXT_CORE_PROFILE_BIT_ARB,
        0
    };

    HANDLE context = wglCreateContextAttribsARB( WindowGlobal::hdc, 0, contextAttribs );

    if (!wglMakeCurrent( WindowGlobal::hdc, (HGLRC)context ))
    {
        OutputDebugStringA( "Failed to activate forward compatible context!\n" );
    }
}

```

**Edit to answer the SDL question**:

SDL makes all this huge amount code to shorten into several lines and additionally the same code works on Windows, Linux, macOS and other OSs. It's well maintained and funded by Valve etc. and has been around for a long time. It also includes input handling code etc.
> 5 votes

---
Tags: opengl, c++
---


# Question
Title: When and how often does Epic charge me royalties on my game?
I want to know about that 5% royalties that Epic charges for the Unreal Engine if I sell games above $3000.

What about if my game just made $300? Do I still need to pay 5% royalties to them? And how many times should I pay? For example, I made a game that was sold for above $3000 so I paid 5% royalties but do I still need to pay it again for the same game?

# Answer
> 2 votes
The EULA states that you need to pay Epic 5% of the *gross revenue* attributable to your game. However you are exempt from this for the first $3,000.00 in gross revenue for each game per calendar quarter.

Note that gross revenue is *not your profit*. It is the amount of money generated by your game; if, for example, you sell your game on the iOS app store for $0.99, and you sell 4000 copies, that is a gross revenue of $3960.00 even though you actually see less than that due to Apple's cut. Epic's example is as follows:

> The royalty is based on gross revenue from end users, regardless of whether you sell your Product to end users directly, self-publish via the App Store or any similar store, or work with a publisher. The following simplified example illustrates the application of the royalty to gross sales: if your Product earns $10 on the App Store, Apple may pay you $7 (having deducted 30% as a distribution fee), but your royalty to Epic would still be 5% of $10 (or $0.50).

As to your specific questions:

> What about if my game just made $300? Do I still need to pay 5% royalties to them?

No. If your game has a gross revenue of $300 total, or $300 per quarter, you do not owe any royalties to Epic.

> And how many times should I pay? For example, I made a game that was sold for above $3000 so I paid 5% royalties but do I still need to pay it again for the same game?

If your game has a gross revenue of $3001 in one quarter, you have to pay Epic 5% of the $1. If your game has a gross revenue of $0 the next quarter, you don't owe Epic anything for that quarter. The royalties are all based around a quarterly model.

You have to consider each game separately, not in total. If you have two games that move $3000 in a quarter, you don't owe any royalties. If you have two games that move $3001 in a quarter, you owe 5% of the extra $1 twice (one for each game).

It is also important to note that Epic considers in-app purchase revenue and ad revenue part of the gross revenue for royalty-computation purposes, so it's not only the initial sales of your game that factor in.

# Answer
> 0 votes
The First $3000 is for only the developers, that is why it is free of royalty. But distribution fee or "Steam" royalty is not allowed in calculating Gross (Net) Product Sales Revenue. Here is an example of calculating gross revenue for a quarter of a year (the first quarter of the first year in sales life) given in the picture from this "Form" for tracking royalty dues.

Form Link: http://help.epicgames.com/customer/en/portal/articles/2313883-how-do-i-submit-a-royalty-report-for-my-ue4-project-?b\_id=9727

It is only $50 due for the first quarter if "Gross revenue is $4000" thus "$4000 less $3000" or $1000 is the "Current Quarter Less $3000 (which is the allowed deduction per game)". More pictures to help you calculate.

(Click on the image for larger view)

---
Tags: unreal-4
---


title: Impossible rooms in 3D games

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

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

# Answer
For engines without native portal features, these types of spaces are usually created using invisible teleportation volumes.

The level author creates two or more exact copies of the area, with subtle changes between them. Each one matches what the player should see from certain positions in the space, and is internally consistent within itself.

Then, when the player crosses a threshold in one space, they're invisibly teleported to the modified copy. (And vice versa)

Diagram by Reddit user spotpilgrim.

In the simplest case, there's some space we can stand where we can't see the parts that change all at once - say we have to go through a U-shaped corridor in between. This section of the space is the same in both copies, so when the player teleports, they can't immediately tell anything happened - it looks like they're moving through a single consistent space. It's not until they get around the corner that they spot something that shouldn't be there, based on their memory of what was actually a different room.

Note in the Stanley Parable example they made the pillars thick, and put big obstacles to walk around to control your line of sight, so you can't actually see between the pillars/into the corridor until you're right in front of it, and from there you can't see the room behind that it would have to be cutting through. The filing cabinets form that "U-shaped corridor" so there's no way to spot where exactly they teleport you between copies of the room.

---

In trickier cases, we can actually see into one version of the space from the other, and can't hide the contradiction behind carefully placed props. So, we have to do a little extra magic:

1. We take the aperture through which we should see the other space (the doorway for example) and cover it with a special object that acts like a greenscreen in film special effects. When we render this part of the scene, the greenscreen object writes a mask into our stencil buffer, so we know which parts of the image need the other version composited-in.
2. Next, we work with a modified copy of the player's camera (in an engine like Unity, we'd literally copy the camera - in other environments we might just layer an extra transform onto our camera matrix), placing this copy in the alternate version of the room, in the exact position & orientation corresponding to the player camera's viewpoint in their version of the room.
3. We render the alternate room from this camera's perspective, writing only onto pixels of the framebuffer marked by our aperture greenscreen. This lets us selectively replace just that part of the image with whatever we want, and so we can show a corridor far too deep to actually fit into the space available in the first version of the room, or a twisting portal that leads back into the room it came from, from a different direction.

Here is a tutorial walking through how to implement such a portal system in Unity's Universal Render Pipeline (URP).

Now if the player can modify the space - say, taking/moving/dropping objects, painting or bullet-pitting walls, etc. - you'll need to exercise caution to update both copies, lest any area they share show a telltale *pop* as the player crosses the teleport threshold. Physics objects also need some special handling in case they interact with objects on both sides of a teleport. And any game with guns/lobbed/line of effect abilities needs to consider teleports in the path of such actions. Lighting & shadows crossing the threshold need careful attention too, to avoid showing the seam.

All of this gets a bit nitty-gritty. If you have an idea for a particular game scenario you want to create with impossible space, give it a try, and if you get stuck feel free to post a question describing in detail what you're trying to do & how - we'll be able to help fill in the missing pieces.
> 6 votes

# Answer
Stanley Parable runs on the Source engine, which is a portal-based engine.

In a portal-based engine, not all sections of the game exist in the same 3d space. Every zone (room) has its own 3d space and the zones are connected through portals. But these portals don't necessarily need to be on the outer wall of a zone and the two sides of a portal don't even need to have the same orientation. This allows some weird tricks. In the video above there is a portal between the two columns which leads to a completely different hallway. Usually map designers try to avoid doing this to not confuse the player and not break their suspension of disbelieve. In TSP, however, the developer intentionally wants to confuse the players and subvert their expectations, so he abuses it quite shamelessly.

Another Source-based game which showed what you can do with portals is the aptly-named Portal. They didn't actually need to do much to implement the portal physics. They just used what the engine was already able to do natively and built a game mechanic with it.

But the Unity engine doesn't work that way. The whole scene exists in the same 3d space. So when you want to create a non-Euclidean level in Unity, you need to cheat a bit. A possible option is to add and remove level geometry from the scene when the player isn't looking and literally switch out parts of the level depending on where the player is positioned.
> 3 votes

---
Tags: unity, level-design, portals, non-euclidean
---


title: What is the purpose of having lives?

text:
# Question
Title: What is the purpose of having lives?
I think in game design it is incredibly important to ask the question why about everything, especially something that has become so standard as lives. So I am asking, what is the purpose of a game having the concept of lives? Why have lives?

# Answer
Other than the arcade/profitability/limiting play factor, quite simply lives add tension.

If falling off a cliff doesn't mean anything (namely, there's no punishment), then you won't feel bad when you do it. But if you fall off too many times and can't proceed, then you want to make damn sure that you don't fall off the cliff. Harder games make you feel better when you beat them, it provides bragging rights, etc.

Of course, that kind of compulsion loop player punishment has gone by the wayside recently. Taking up the player's time is punishment enough. When most research shows that people don't finish games as it is, game designers are trying to find ways to make it less frustrating to go through the game but providing enough of a challenge that it's enjoyable. Basically, it's less about the game and more about the experience. Lives would be inappropriate in a game like Uncharted, for example.
> 56 votes

# Answer
**Profitability...**

Extra lives provides the player with additional "chances" to "try again." Particularly with traditional arcade games back in the 1980s, a player would insert a quarter (25 cents) to play the game, and with this payment they'd get a number of lives (usually 3 or 5).

With these extra lives, the gameplay is longer, and the player gets more "value" out of the game since they extra lives allowed them to automatically continue the gameplay. If the game provided only one life, they player might not enjoy the game as much (because the game would be a shorter duration), and consequently may not insert as many quarters to play again later (which would make it less profitable).

When enjoying video arcades in my younger years back in the 1980s, I noticed that the games that provided more lives tended to be more popular. I'm sure the arcade game vendors and operators all understood this well as some operators with the less popular arcades tended to set dip-switches on the games \[that supported this sort of customization\] to provide more lives for the payment.

Of course, the consumer almost always likes to have the benefit of "extra lives" as this equates to more entertainment. But, for games that are in very high demand (e.g., "Outrun," which imposes time-limits instead of number of lives, when it was new, was a big arcade machine that featured a seat shaped like a car that actually shook and tilted {if I recall correctly} and vibrated in concert with in-game events, for which I've included a few images below), many arcade operators set the dip-switches to severely limit the numbers of lives under the guise of "giving more people a chance to play" (although I suspect that this decision was more likely motivated by profit).

Pinball machines had exactly the same concept, except instead of lives the player got balls. Typically 3-5 balls per quarter.

One common factor as well was that once all the lives (or cars, or balls, etc.) where lost, the game provided an option to the player to insert another quarter to continue (and get another 3 or 5 lives, cars, balls, etc.).

**Measuring skill...**

As I alluded to in the comments, having lives can also aid the player in measuring their skill:

* What score did I achieve with 1 (or 3, or 5) lives?
* How much gold did I get before the evil dragon killed me?
* How many times did I play multi-ball mode on that pinball machine in one go?
* How many races was I win with just one car?

These can become "bragging rights" amongst a player's friends, especially if there were witnesses. I can remember back in the 1980s seeing people crowd around player who's been playing a particular game for a long time, and playing it well. Comments from onlookers would sometimes include "she \[that player\] is still on her first life and she's already completed seven levels" followed by "damn, I always have trouble with the umber-troll on level three, how did she do that?"

Such measurements can be an important tie into word-of-mouth marketing too.

**Player motivation...**

The "losing a character's life" factor also adds yet another quality to the gameplay that causes the player to put a little bit more effort into taking care of their character (e.g., feeding it so it doesn't starve to death, avoiding getting hit by weapons, circumventing dangerous traps, etc.). With the possibility of losing lives, the player will get more emotionally involved in the gameplay sessions which, in turn, makes the game more interesting.

If a character never dies, the game may never end and could become quite boring, at least in the case of an action game. For games like Chess, Ma-Jiang (incorrectly spelled by most authors as "Mah Jongg" or "Mahjjong" and so on), etc., there obviously is no need to have a concept of "lives," but for most action games where your character is at risk of dying it's beneficial. Ditto for pinball and other such games too.

Also, if the player makes some serious mistake in the first 10 seconds of gameplay, the additional lives are a wonderful feature. Not having this feature can be very discouraging, especially for new players.

The player knows that there is a limited number of lives available, and will work toward an unspoken goal to improve their gameplay abilities. Of course, this will require practice, and so the extra lives are also helpful here too.

**Pictures of Outrun...**

I've included a few pictures of the Outrun game I mentioned earlier. For those who remember playing this game in an arcade, I hope this will also bring back some fond memories.
> 25 votes

# Answer
Finite lives are a form of resource management for the player.

If you notice, most games that have a finite count of lives tend to be very binary about being alive or dead. Maybe the player gets a couple of HP, but if you get hit more than 3 times or so, you lose a life. And there will generally be a healthy supply of "insta-death" lurking around, whether it is pits, spikes, etc.

Because of that, lives function as resources in the same way that healing potions do in RPGs. The more you have, the more likely you are to be able to progress further. You don't have to push as hard, since you have more lives to try again. This is also why RPGs, even historically, almost never used multiple lives. There was no point, since they already had plenty of resource management.

One of the reasons why finite lives is going out of fashion for games these days is that running out of lives generally isn't fun for most players. While the *tension* created by having low lives is nice, if you ever actually run out, the game becomes a lot less fun. You lose a lot of progress.

One of the other reasons why finite lives aren't used often is because game developers tend to allow you to save anywhere. Or at least, at reasonably-space designated locations. Because of that, the only progress you can lose is back to the last save point. So, unless save points are significantly different from checkpoints, there's really no purpose to it. And if they are significantly different, players may not like that very much.

So the only way to make finite lives worthwhile is to punish the player significantly more for running out of lives than for simply losing a life.
> 14 votes

# Answer
Its an additional **difficulty control**. In addition, it **forces replay** of the first few levels, which both builds skills and essentially gives the *game* more play.

Consider a game that was easily beatable in one 3 hour sitting, without "dying" or having to start again. Probably you would then shelve the game and never play it again.

Or consider also a game that is incredibly difficult and only lets you die once ( vid: Double Dragon III ). You would likely shelve the game and never play it again.

Games that mix the right amount of challenge with the right number of lives produce a lot of fun replay. One of my favorite games was **Battletoads**. Replaying the first few levels in 2-player mode *is still* a lot of fun.

Basically the trade-off between life-meter and now-you-have-to-start-again. Its nice to not have to start again from the *very* beginning, which would be too challenging/discouraging and would *play-out the first few levels faster*.

Besides life you also have to consider *continue*/*password*. Password was an early alternative to savegame, but again, all of these are just means by which to **control the difficulty of the game** and make it winnable, without making the game too dry to keep starting over from world 1-1.

Its interesting to see how different games handled this though. Take TMNT I, where each *turtle* only had one life ("getting caught"), but you had 4 turtles, so effectively 4 lives. (They could be rescued as well, but that was really rare/difficult).
> 5 votes

# Answer
Lives are a way of tuning the feedback loop that players engage with the game through (reward/punishment for actions taken toward goals). A crucial part of gameplay is learning; a game design where punishments of lesser degree than termination of the game are available gives more opportunities for players to learn which behaviors earn rewards and which earn punishments, and so promotes engagement. Of course there are many ways to accomplish that, but since "death" is a common metaphor for game termination, a natural modification of that metaphor becomes "multiple lives".
> 4 votes

# Answer
In short. If you are giving player a challenge to get from Point (or objective) A to B and its somewhat long. You may not want to force the player to start over if he makes a mistake but you may want to limit the amount of mistakes he can make by using lives which spawn you at last checkpoint.

In a game like zelda (ocarina of time) if you die you start at the beginning of the level which isnt too much of a big deal. However if you accidentally fall in a hole you wouldn't want to start over again so instead of 'lives' (which you dont get) you get deducted hearts/health points instead which is a fair alternative.
> 4 votes

# Answer
Games are for playing purpose. Player play the game to win something, to have fun. Every time they fail to do that, they just ask for another chance. They think, this time, this time for sure I am gonna make it. That's the purpose of having life.
> 3 votes

# Answer
Humans are very risk-averse in terms of death. When a game designer adds the concept of lives to a game where the character in the game might die, they are essentially encouraging the player to take risks they wouldn't otherwise take.

Further, it helps draw players into the game, where the first time they play they might die with minutes of starting. Once they start the game, however, they feel the need to continue trying while they still have remaining game time, or lives, left. Ideally they will learn enough during this time period that they will desire to play the game again, even though they may have to start from the beginning again, having lost all their lives.
> 3 votes

# Answer
It is simple, the purpose of having lives is to allow the player to fail multiple times before total failure or having to restart the game. While games like traditional Arcade games give lives as a means of profit (1 coin, 1 life), the same Arcade games on consoles use lives as a means of trying to get the player to play carefully without having the higher difficulty of permadeath.

In other words: lives are there to help others despite their failures, and as an alternative to permadeath, given that feature's negative aspects. Yet it still retains a form of permadeath (after X lives are lost, you are gone for good!) which retains some of the POSITIVE aspects of that feature.
> 1 votes

# Answer
Several reasons for lives to exist/not exist:

1. Limited lives provide an additional challenge, but are clearer than "don't take more than 1000HP" -- which is what they eventually equate to.
2. In many games, dying provides a delay until you are permitted to revive. This provides both an opportunity for you to regroup and reconsider your approach, as well as for your enemies. In some games, bosses regain their health when you die, in PvP games your teammates might suddenly be outnumbered because you're dead for a few seconds. Death can be a tactical (dis)advantage.

But being dead is boring to a player, so there are also games (Call of Duty: Modern Warfare comes to mind), where, apart from respawning a distance away from the battle and having to run back, you revive immediately. Or WoW where you can run to your corpse immediately instead of waiting to revive, or SWTOR where you can revive in place if you're a subscriber or pay, instead of far away at the med droid.
3. In classic Arcade games, it was how they made money. You pay for reviving. Some games today also still do this, e.g. you lose credits when you die. This is less harsh, but encourages play on a higher level because you have more spending money left for gear, vanity items etc. OTOH it avoids locking out people who can't afford to pay for revives (e.g. the F2P players you need to keep the game populated so the actual customers - paid players, especially "whales" - can have fun).
4. The concept of death serves as a fixed cut-off point for player ability. If you die in this level, chances are you haven't mastered an ability you need to build on for higher levels. By making you die, a game can make you aware that you need more practice before you e.g. end up in a PvP session and cost your team a win. It can also just serve as the criterion whether you get to advance in rank in a game, or get rewards.

In short, it depends on what kind of game you are making whether the concept of lives, of penalizing bad performance, makes sense. LucasArts adventures famously don't have the concept of death. You can take hundreds of hours to finish a game, and apart from you maybe losing interest, there is no penaltly. There is no walking off a cliff or otherwise losing. Puzzle games don't have lives. You just don't win until you get it right.
> 0 votes

---
Tags: game-design
---


title: How do I shuffle cards for a card game?

text:
# Question
Title: How do I shuffle cards for a card game?
I am trying to develop an card game for Android Can anyone suggest me how to write code for effectively shuffling the playing cards?

# Answer
Card shuffling is an algorithm which is easy to write intuitively, and get entirely wrong by doing so. There's a good reference for implementing card shuffling correctly on Wikipedia. What I'm presenting here is a very slightly simplified version of the algorithm covered on that page under *The modern algorithm*.

Here's the basic idea, in plain english:

Consider a deck of cards. For this discussion, you can have any number of cards in the deck, and they may start in any order.

We're going to be talking about "position" in the deck, where "position" is how many cards are higher in the deck than the card in that position. For example, the card on top of the deck is at position 0, the card beneath that is at position 1 (because there is 1 card higher than it -- the top card), and in a standard 52-card deck, the bottom card is at position 51, as 51 cards are higher than it in the deck.

Now, we consider each position in the deck, one at a time, starting from the bottom, and working our way up to the top.

For each position, we randomly select one of the cards which is **at that position or at a lower-numbered position** (remember, the top of the deck is 0, and we're working our way up from the bottom of the deck, so for each position, you're effectively picking up all the cards at and above that position and randomly picking one of those cards).

When we have made the random selection, we swap the card at the position we're currently considering with the card we randomly selected. If we randomly selected the card which was already in that position, then no swap is performed.

After swapping (or not swapping, if we randomly selected the card which was already in the position we were considering), we move on to the next position in the deck and continue.

In pseudocode, with *n* being the number of cards in the deck, and *a* being an array representing the deck, the algorithm looks like this:

```
for each i in [n .. 1] do
     j ← random integer in [ 0 .. i ]
     exchange a[j] and a[i]

```
> 22 votes

# Answer
You first define a sequence of all the cards you want to shuffle:

```
List<Card> shuffled = new ArrayList<Card>();
shuffled.addAll(allCards);

```

Then you walk through every position in the sequence and assign it a card randomly.

```
Random random = new Random();
for (int i = shuffled.size() - 1; i >= 0; i--) {
    int j = random.nextInt(i + 1);

    /* swap cards i,j */
    Card card = shuffled.get(i);
    shuffled.set(i, shuffled.get(j));
    shufflet.set(j, card);
}

```

Now `shuffled` is a random sequence of all of your cards.
> 9 votes

# Answer
I'd like to chime in and mention "format preserving encryption" as a method for shuffling cards in a game.

Essentially what you'd have is an encryption algorithm that takes in a value 0 to 51, and a key (shuffle seed) and spits out a value 0 to 51. Since encryption is reversible by definition that means any 2 input numbers cannot encrypt to the same output number, which means if you encrypted 0 to 51, you'd get 0 to 51 as output in a different order. In other words you have your shuffle and don't even need to do any actual shuffling.

In this case you'd have to make or find an encryption algorithm that took in 6 bits and spit out 6 bits (0-63). To draw the next card from the deck you'd have an index variable which started at zero, you'd encrypt that index, increment the index and look at the value that came out of the cipher. If the value is \>= 52, you ignore it and generate a new number (and increment the index again of course). Since encrypting 0-63 will result in 0-63 as output, in a different order, you are just ignoring any value that comes out \>= 52 so that you have your algorithm that takes in 0-51 and spits out 0-51.

To reshuffle the deck, set the index back to zero and change the encryption key (shuffle seed).

Your algorithm doesn't need to be cryptographic quality (and it shouldn't be, cause that would be computationally expensive!). One really good way to come up with a custom sized encryption algorithm like this would be to use a feistel network, which lets you customize size and quality depending on your needs. For the round function of the feistel network, I'd recommend something like murmurhash3 because it's fast and has a good avalanche effect, which would make the shuffles appear well randomized.

Check out my blog post for even more detailed info and source code: http://blog.demofox.org/2013/07/06/fast-lightweight-random-shuffle-functionality-fixed/
> 2 votes

# Answer
The java 1.5 enum tutorial has a interesting way to implement a deck of cards, building up the deck, shuffling and dealing. All very simple using `enum`s and `Collections`

```
public class Card {
    public enum Rank { DEUCE, THREE, FOUR, FIVE, SIX,
        SEVEN, EIGHT, NINE, TEN, JACK, QUEEN, KING, ACE }

    public enum Suit { CLUBS, DIAMONDS, HEARTS, SPADES }

    private final Rank rank;
    private final Suit suit;
    private Card(Rank rank, Suit suit) {
        this.rank = rank;
        this.suit = suit;
    }

    public Rank rank() { return rank; }
    public Suit suit() { return suit; }
    public String toString() { return rank + " of " + suit; }

    private static final List<Card> protoDeck = new ArrayList<Card>();

    // Initialize prototype deck
    static {
        for (Suit suit : Suit.values())
            for (Rank rank : Rank.values())
                protoDeck.add(new Card(rank, suit));
    }

    public static ArrayList<Card> newDeck() {
        return new ArrayList<Card>(protoDeck); // Return copy of prototype deck
    }
}

```

And the class to manage the deck.

```
public class Deal {
    public static void main(String args[]) {
        int numHands = Integer.parseInt(args[0]);
        int cardsPerHand = Integer.parseInt(args[1]);
        List<Card> deck  = Card.newDeck();
        Collections.shuffle(deck);
        for (int i=0; i < numHands; i++)
            System.out.println(deal(deck, cardsPerHand));
    }

    public static ArrayList<Card> deal(List<Card> deck, int n) {
         int deckSize = deck.size();
         List<Card> handView = deck.subList(deckSize-n, deckSize);
         ArrayList<Card> hand = new ArrayList<Card>(handView);
         handView.clear();
         return hand;
     }
}

```
> 1 votes

# Answer
Simply use a function like itertools like there on Python . I am not aware of the name of the same function in Java try ".http://code.google.com/p/neoitertools/"

Find out all the permutations of the object called "cards"
> 0 votes

# Answer
```
    ArrayList deckCards = new ArrayList<Card>();
    //add your cards to the deck
    deckCards.add(card1);
    deckCards.add(card2);
    deckCards.add(card3);
    ....
    //shuffle the array list
    Collections.shuffle(deckCards);

```
> -2 votes

---
Tags: java, algorithm, random, card-game
---


# Question
Title: Monogame HLSL GBuffer Depth Mysteriously Colored Red
I was working through an older tutorial listed here, and got it to work for the most part. The RenderTarget for Depth is colored red for some reason, and I've been scratching my head trying to figure out why.

I tried clearing the screen another way, which at least painted the other render targets white instead of black. Also, this code uses the cross platform dlls (OpenGL), but the very same code fails with a strange error with windows only dlls.

Here are some screenshots: https://i.stack.imgur.com/BBMEo.jpg

Tutorial link: http://www.catalinzima.com/xna/tutorials/deferred-rendering-in-xna/creating-the-g-buffer/

Any help appreciated.

Below is the code I am using, which is almost exactly like the tutorial:

```
public class Game1 : Game
{
    private GraphicsDeviceManager graphics;
    private SpriteBatch spriteBatch;

    private Model model;
    private Texture2D texture;
    private float angle = 0f;

    private Vector3 FocusPoint;
    private Vector3 CameraOffset;
    private Matrix RotationMatrix;
    private Vector3 RotationOffset;

    private Matrix World;
    private Matrix View;
    private Matrix Projection;

    private Effect ClearGBufferEffect;
    private Effect GBufferEffect;
    private QuadRenderComponent QuadRenderer;
    private RenderTarget2D ColorRenderTarget;
    private RenderTarget2D NormalRenderTarget;
    private RenderTarget2D DepthRenderTarget;

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

    protected override void Initialize()
    {
        // quad renderer
        QuadRenderer = new QuadRenderComponent(this);
        Components.Add(QuadRenderer);

        // world view projection
        FocusPoint = Vector3.Zero;
        CameraOffset = new Vector3(0f, 2f, 2f);
        RotationMatrix = Matrix.CreateRotationY(MathHelper.PiOver4);
        RotationOffset = Vector3.Transform(CameraOffset, RotationMatrix);
        World = Matrix.CreateScale(new Vector3(1f, 1f, 1f)) * Matrix.CreateTranslation(new Vector3(0, 0, 0));
        View = Matrix.CreateLookAt(RotationOffset, FocusPoint, Vector3.Up);
        Projection = Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4, 480f / 480f, 0.1f, 1000f);

        // color normal depth
        int backBufferWidth = GraphicsDevice.PresentationParameters.BackBufferWidth;
        int backBufferHeight = GraphicsDevice.PresentationParameters.BackBufferHeight;
        ColorRenderTarget = new RenderTarget2D(GraphicsDevice, backBufferWidth, backBufferHeight, false, SurfaceFormat.Color, DepthFormat.Depth24);
        NormalRenderTarget = new RenderTarget2D(GraphicsDevice, backBufferWidth, backBufferHeight, false, SurfaceFormat.Color, DepthFormat.Depth24);
        DepthRenderTarget = new RenderTarget2D(GraphicsDevice, backBufferWidth, backBufferHeight, false, SurfaceFormat.Single, DepthFormat.Depth24Stencil8);

        base.Initialize();
    }

    protected override void LoadContent()
    {
        spriteBatch = new SpriteBatch(GraphicsDevice);

        // model texture gbuffer
        model = Content.Load<Model>("Tile5");
        texture = Content.Load<Texture2D>("Red");
        ClearGBufferEffect = Content.Load<Effect>("ClearGBuffer");
        GBufferEffect = Content.Load<Effect>("GBuffer");
    }

    protected override void UnloadContent() { }

    protected override void Update(GameTime gameTime)
    {
        if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape))
            Exit();

        // simple rotation update
        angle += 1f;
        RotationOffset = Vector3.Transform(CameraOffset, Matrix.CreateRotationY(MathHelper.ToRadians(angle)));
        View = Matrix.CreateLookAt(RotationOffset, FocusPoint, Vector3.Up);

        base.Update(gameTime);
    }

    protected override void Draw(GameTime gameTime)
    {
        // set render targets
        GraphicsDevice.SetRenderTargets(ColorRenderTarget, NormalRenderTarget, DepthRenderTarget);

        // clear everything
        // ClearGBufferEffect.CurrentTechnique.Passes[0].Apply();
        // QuadRenderer.Render(Vector2.One * -1, Vector2.One);
        GraphicsDevice.Clear(ClearOptions.Target | ClearOptions.DepthBuffer, Color.White, 1.0f, 0);

        // render options
        GraphicsDevice.DepthStencilState = DepthStencilState.Default;
        GraphicsDevice.BlendState = BlendState.Opaque;
        GraphicsDevice.RasterizerState = RasterizerState.CullCounterClockwise;

        // set gbuffer params
        GBufferEffect.Parameters["World"].SetValue(World);
        GBufferEffect.Parameters["View"].SetValue(View);
        GBufferEffect.Parameters["Projection"].SetValue(Projection);
        GBufferEffect.Parameters["Texture"].SetValue(texture);

        // render simple mesh
        GBufferEffect.CurrentTechnique.Passes[0].Apply();
        foreach (var mesh in model.Meshes)
        {
            foreach (var part in mesh.MeshParts)
            {
                GraphicsDevice.SetVertexBuffer(part.VertexBuffer);
                GraphicsDevice.Indices = part.IndexBuffer;
                GraphicsDevice.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, part.PrimitiveCount);
            }
        }

        // unset render targets
        GraphicsDevice.SetRenderTargets(null);

        // render each target to one 4th of the screen
        int hw = GraphicsDevice.Viewport.Width / 2;
        int hh = GraphicsDevice.Viewport.Height / 2;
        spriteBatch.Begin();
        spriteBatch.Draw(ColorRenderTarget, new Rectangle(0, 0, hw, hh), Color.White);
        spriteBatch.Draw(NormalRenderTarget, new Rectangle(0, hh, hw, hh), Color.White);
        spriteBatch.Draw(DepthRenderTarget, new Rectangle(hw, 0, hw, hh), Color.White);
        spriteBatch.End();

        base.Draw(gameTime);
    }
}

public class QuadRenderComponent : DrawableGameComponent
{
    //private VertexDeclaration vertexDecl = null;
    private VertexPositionTexture[] verts = null;
    private short[] ib = null;

    public QuadRenderComponent(Game game)
        : base(game) { }

    protected override void LoadContent()
    {
        IGraphicsDeviceService graphicsService =
            (IGraphicsDeviceService)Game.Services.GetService(
                                        typeof(IGraphicsDeviceService));

        verts = new VertexPositionTexture[]
                {
                        new VertexPositionTexture(
                            new Vector3(0,0,1),
                            new Vector2(1,1)),
                        new VertexPositionTexture(
                            new Vector3(0,0,1),
                            new Vector2(0,1)),
                        new VertexPositionTexture(
                            new Vector3(0,0,1),
                            new Vector2(0,0)),
                        new VertexPositionTexture(
                            new Vector3(0,0,1),
                            new Vector2(1,0))
                };

        ib = new short[] { 0, 1, 2, 2, 3, 0 };

    }

    public void Render(Vector2 v1, Vector2 v2)
    {
        IGraphicsDeviceService graphicsService = (IGraphicsDeviceService)
            base.Game.Services.GetService(typeof(IGraphicsDeviceService));

        GraphicsDevice device = graphicsService.GraphicsDevice;

        verts[0].Position.X = v2.X;
        verts[0].Position.Y = v1.Y;

        verts[1].Position.X = v1.X;
        verts[1].Position.Y = v1.Y;

        verts[2].Position.X = v1.X;
        verts[2].Position.Y = v2.Y;

        verts[3].Position.X = v2.X;
        verts[3].Position.Y = v2.Y;

        device.DrawUserIndexedPrimitives(PrimitiveType.TriangleList, verts, 0, 4, ib, 0, 2);
    }
}

```

Here is the ClearGBufferEffect:

```
    #if OPENGL
    #define SV_POSITION POSITION
    #define VS_SHADERMODEL vs_3_0
    #define PS_SHADERMODEL ps_3_0
#else
    #define VS_SHADERMODEL vs_4_0_level_9_1
    #define PS_SHADERMODEL ps_4_0_level_9_1
#endif

struct VertexShaderInput
{
    float3 Position : SV_POSITION;
};

struct VertexShaderOutput
{
    float4 Position : SV_POSITION;
};

struct PixelShaderOutput
{
    float4 Color : COLOR0;
    float4 Normal : COLOR1;
    float4 Depth : COLOR2;
};

VertexShaderOutput MainVS(in VertexShaderInput input)
{
    VertexShaderOutput output = (VertexShaderOutput)0;

    output.Position = float4(input.Position, 1);

    return output;
}

PixelShaderOutput MainPS(VertexShaderOutput input)
{
    PixelShaderOutput output = (PixelShaderOutput)0;

    output.Color.rgb = 0.0f;
    output.Color.a = 0.0f;

    output.Normal.rgb = 0.5f;
    output.Normal.a = 0.0f;

    output.Depth = 1.0f;

    return output;
}

technique T0
{
    pass P0
    {
        VertexShader = compile VS_SHADERMODEL MainVS();
        PixelShader = compile PS_SHADERMODEL MainPS();
    }
};

```

Here is the GBufferEffect:

```
    #if OPENGL
#define SV_POSITION POSITION
#define VS_SHADERMODEL vs_3_0
#define PS_SHADERMODEL ps_3_0
#else
#define VS_SHADERMODEL vs_4_0_level_9_1
#define PS_SHADERMODEL ps_4_0_level_9_1
#endif

matrix World;
matrix View;
matrix Projection;
float SpecularIntensity = 0.8f;
float SpecularPower = 0.5f;

texture Texture;
sampler DiffuseSampler = sampler_state
{
    Texture = (Texture);
    MAGFILTER = LINEAR;
    MINFILTER = LINEAR;
    MIPFILTER = LINEAR;
    AddressU = Wrap;
    AddressV = Wrap;
};

struct VertexShaderInput
{
    float4 Position : SV_POSITION;
    float3 Normal : NORMAL0;
    float2 TexCoord : TEXCOORD0;
};

struct VertexShaderOutput
{
    float4 Position : SV_POSITION;
    float2 TexCoord : TEXCOORD0;
    float3 Normal : TEXCOORD1;
    float2 Depth : TEXCOORD2;
};

struct PixelShaderOutput
{
    half4 Color : COLOR0;
    half4 Normal : COLOR1;
    half4 Depth : COLOR2;
};

VertexShaderOutput MainVS(in VertexShaderInput input)
{
    VertexShaderOutput output = (VertexShaderOutput)0;

    float4 worldPosition = mul(input.Position, World);
    float4 viewPosition = mul(worldPosition, View);
    output.Position = mul(viewPosition, Projection);

    output.TexCoord = input.TexCoord;

    output.Normal = mul(input.Normal, World);

    output.Depth = output.Position.zw;

    return output;
}

PixelShaderOutput MainPS(VertexShaderOutput input)
{
    PixelShaderOutput output = (PixelShaderOutput)0;

    output.Color.rgb = tex2D(DiffuseSampler, input.TexCoord);
    output.Color.a = SpecularIntensity;

    output.Normal.rgb = 0.5f * (normalize(input.Normal) + 1.0f);
    output.Normal.a = SpecularPower;

    output.Depth = input.Depth.x / input.Depth.y;

    return output;
}

technique T0
{
    pass P0
    {
        VertexShader = compile VS_SHADERMODEL MainVS();
        PixelShader = compile PS_SHADERMODEL MainPS();
    }
};

```

# Answer
> 2 votes
You use a `SurfaceFormat.Single` type. This means your texture holds only one value per pixel instead of 4 (rgba). This is perfectly fine for a depth buffer as you only need to record the depth value.

When you render that texture, the `spriteBatch` expects a Texture2D: the RenderTarget is cast to the Texture2D. With only one value it converts to 1,0,0 hence it shows up as red.

---
Tags: monogame, hlsl
---


# Question
Title: Making Buildings Transparent When the Player is Behind Them
I am making a 3D twin stick shooter in Unity and this is a question I need to have answered while I am still in early development. The map my player is in will have very tall buildings that will easily block the player from the view of the camera. There will be no way to change the camera angle to look behind the building so how do I make the building transparent when my player goes behind it?

Any help is appreciated. Thank you.

# Answer
I suggest casting a raycast from your camera to your player. Make sure your buildings have colliders so the raycast hit info can return it. From there you can change the material/texture to something transparent to hide the building obscuring your view.
> 1 votes

---
Tags: unity, transparency, layers
---


title: Multiplayer game servers architecture

text:
# Question
Title: Multiplayer game servers architecture
I'm trying to create MMORPG with huge world divided by chunks. I was thinking a lot about servers architecture. I don't want my main game server to have direct access from clients and I do want to have some abilities for load balancing and for expanding whole system.

Finally I came up with this architecture:

1. The Game Server - which store game state and trigger events and so on. This server does not communicate with clients. It will be connected to database to store game state from time to time.
2. Streaming Servers - servers that handle client connections and stream game state to them as far as players actions to server. I suppose them to work through UDP. With this approach I will have some benefits:
    * I can put then in different countries to lower pings.
    * I can have as many then as my budget allows me to. Adding more streaming servers would allow to handle more client online.
    * if something happens with one of streaming servers (due to hacker attacks or server hardware/software failure) this will not effect whole systems and other players experience. Players from this server can be routed to another.
3. Physics Servers - they would handle chunk physics and maybe some other heavy stuff. With adding new physics servers I can extend my system so that it would able to proceed more and more data, if needed.

What are the pitfalls of such an architecture? How good is it?

How would clients know to which streaming server they should connect? I suspect that here I should have one more - routing server that would do something like load balancing stuff and route user to one of the working streaming servers.

Would I have some problems with data synchronization?

# Answer
> 2 votes
No. Don't do it that way, it won't work.

* The latency is about as bad as any architecture can offer, due to the high number of hops.
* Scaling is incredibly poor due to a single game server.
* Complexity is very high, due to 3 server side layers which all operate at different times and need to extrapolate data from each other.

What you really need are multiple virtual game servers one per "chunk" of your world. Depending on load, you can move these virtual servers to a single machine, one machine per chunk, or anything in between.

# Answer
> 0 votes
When the purpose of those streaming servers is to reduce latency, then you might shoot yourself in the knee with that separation. Sure, the latency will be lower for everything the streaming servers can handle on their own. But how much will that really be?

Most player actions will need to be processed on the game-server or even the physics servers in your backend. The overall perceived latency between action and effect can only become worse through those layers of indirection.

It's also questionable if the stream server will even take much burden from the gameserver. The gameserver still needs to send updates to all the streamservers, and any input on a streamserver will need to be forwarded to the gameserver. You will only have a benefit when you can find gameplay features you can move to the streamserver which do not concern the gameserver. Possible things could be input validation (have the streamservers only forward input after validating that the player can actually do that right now) and visibility calculation (only forward events concerning game objects in sight-range).

Many MMORPG architectures rather try to scale horizontally than vertically. That means there is one server process which handles almost everything, but different servers are responsible for handling different zones of the game world. There is usually also one master-server which handles things which affect multiple zones and is used to tell players which zone-server to connect to.

# Answer
> 0 votes
Do you really need to have a physics server? The MMORPG architecture I have seen doesn't have any kind of formal physics server / code. Unless the characters will be dodge arrows and swords real-time. I guess you just have to look at what the game mechanics will be like and decide if you truly need a physics engine.

---
Tags: architecture, multiplayer, mmo, client-server
---


# Question
Title: Unity - Static Camera Perspective, Walls Obscure Player
Pretty simple and common problem here. The world I'm designing is fully explorable, no invisible walls or tricks. It's presented as a single seamless area, a School complex with 9 buildings, some of which have 2 or 3 floors and contain many rooms.

The perspective I've chosen is simple, inspired by topdown RPGs:

A problem arises with walls. They obscure the player.

I've tried some shaders which draw a silhouette of the player ontop but I don't like this approach, other objects and decoration remains obscured behind the wall. Some kind of dissolve effect allowing you to see through the walls would be preferable, but writing my own shaders is not my forté...

Another problem is with large buildings outside. The camera is at a fixed distance, about 14 metre's away. If the player walks behind a large building (over ~10 metres tall) then the camera cuts off the top of it as it is now within the building.

The only way I can think of fixing this is to adjust the distance between player and camera, but some of the buildings are so tall the zoom-out looks very unusual and impractical.

I suppose this is why you don't see this simplistic camera setup in large explorable games...

While I've been developing games for some years now, I've only come to 3D and Unity fairly recently, so there might be a jaw-droppingly simple solution which I'm not seeing.

Anyway, I'd like to hear some interesting or novel approaches towards fixing these problems, besides the simple ones I've suggested.

I hope that's not asking too much.

# Answer
There are 3 options I have seen:

1. Draw a placeholder, usually a silhouette of the player in a highlight color (orange, red, or maybe blue or neon green), in just the screen area where the body is obscured.
2. Partial or complete transparency of walls or objects that hide the player.
3. Change the camera position and/or angle.

---

The disadvantage of 1. is, as you said, that you still can't see anything but the player, unless you draw placeholders for other objects too.

The disadvantage of 1+2 is that it allows the player to look through walls.

The disadvantage of 3 is that it's near impossible to get right, and there will almost always be cases where the camera behaves erratically.
> 1 votes

---
Tags: unity, 3d, game-design, camera, perspective
---


# Question
Title: How to randomly place entities that don't overlap?
I am creating a randomly-generated environment for a game I'm developing. I am using `OpenGL` and coding in `Java`.

I am trying to randomly place trees in my world (to create a forest), but I don't want the models to overlap (which happens when two trees are placed too close to each other). Here's a picture of what I'm talking about:

I can provide more code if necessary, but here's the essential snippets. I am storing my objects in an `ArrayList` with `List<Entity> entities = new ArrayList<Entity>();`. I am then adding to that list using:

```
Random random = new Random();
for (int i = 0; i < 500; i++) {
    entities.add(new Entity(tree, new Vector3f(random.nextFloat() * 800 - 400,
    0, random.nextFloat() * -600), 0, random.nextFloat() * 360, 0, 3, 3, 3);
}

```

where each `Entity` follows the following syntax:

```
new Entity(modelName, positionVector(x, y, z), rotX, rotY, rotZ, scaleX, scaleY, scaleZ);

```

`rotX` is the rotation along the x-axis, and `scaleX` is the scale in the x-direction, etc.

You can see that I am placing these trees randomly with `random.nextFloat()` for the `x` and `z` positions, and bounding the range so the trees will appear in the desired location. However, I would like to somehow control these positions, so that if it tries to place a tree too close to a previously placed tree, it will recalculate a new random position. I was thinking that each tree `Entity` could have another field, such as `treeTrunkGirth`, and if a tree is placed in the distance between another tree's location and it's `treeTrunkGirth`, then it will recalculate a new position. Is there a way to accomplish this?

I am happy to add more code snippets and details as necessary.

# Answer
A Poisson-Disk sampling distribution will allow you to select random points a minimum distance apart. Your situation is similar to this question, but since your trees aren't idealized points you'll need to change the distance checking as follows: the distance between a potential new tree & an existing tree, must be less than the sum of their radii.

Bridson's algorithm can efficiently solve the problem in O(n), but it can be a bit fiddly to tweak it for variable distances. If your parameters are lowish &/or you are precomputing your terrain, a brute force solution may serve you just as well. Here's some sample code that brute forces the problem by checking every potential new tree placement against all prior placed trees:

```
public static class SimpleTree{
    float x;
    float z;
    float r;

    public SimpleTree(Random rng, float xMax, float zMax, float rMin, float rMax){
        x = rng.nextFloat() * xMax;
        z = rng.nextFloat() * zMax;
        r = rng.nextFloat() * (rMax-rMin) + rMin;
    }
}

private static ArrayList<SimpleTree> buildTreeList(float xMax, float zMax,
        float rMin, float rMax, int maxAttempts, Random rng) {
    ArrayList<SimpleTree> result = new ArrayList<>();

    SimpleTree currentTree = new SimpleTree(rng, xMax, zMax, rMin, rMax);
    result.add(currentTree);

    boolean done = false;
    while(!done){
        int attemptCount = 0;
        boolean placedTree = false;
        Point nextPoint = new Point();
        SimpleTree nextTree = null;
        while(attemptCount < maxAttempts && !placedTree){
            attemptCount++;
            nextTree = new SimpleTree(rng, xMax, zMax, rMin, rMax);
            if(!tooClose(nextTree, result)){
                placedTree = true;
            }
        }
        if(placedTree){
            result.add(nextTree);
        }
        else{
            done = true;
        }
    }

    return result;
}

private static boolean tooClose(SimpleTree tree, ArrayList<SimpleTree> treeList) {
    for(SimpleTree otherTree : treeList) {
        float xDiff = tree.x - otherTree.x;
        float zDiff = tree.z - otherTree.z;

        float dist = (float)Math.sqrt((xDiff * xDiff) + (zDiff * zDiff));
        if(dist < tree.r + otherTree.r){
            return true;
        }
    }
    return false;
}

```

With the following parameters:

```
 maxAttempts = 500;
 width = 300;
 height = 200;
 minSize = 2;
 maxSize = 15;

```

I was able to randomly place & render between 400-450 trees in under a second. Here's an example:
> 15 votes

---
Tags: opengl, java, objects
---


title: No assets in CryEngine V?

text:
# Question
Title: No assets in CryEngine V?
I just downloaded and installed CryEngine 5.0.1. I am trying to follow the Island tutorial but I don't have the assets the tutor has. I have installing CryEngine Game SDK but I still don't see any assets or materials except the default ones. So my question is how do I install the assets I need to follow the tutorials?

# Answer
> 4 votes
CryEngine V does not actually come with the default project and assets that came with its predecessors. As a result, you will need to download, and then import the assets into your current project. The SDK, itself, can also be run as its own project.

### Downloading the SDK and other assets

Before you download the SDK, you first need to register them to your account. You can do this for free, once you have logged in to the marketplace. You will find the SDK listed under CRYENGINE GameSDK Sample Project.

While you are there, it might be worth having a look at registering the other assets provided by Crytek, as this makes it easier to acquire them from you launcher, later. Included in the list is a CryEngine V Beginner's Pack and an elephant.

Once you have gone through the process of registering the assets, you can download them from the CryEngine Launcher. Once open, go to *Library \> My Assets* to view all the assets registered to your account. You can download or update your assets from in here.

### Importing assets into your project

Unfortunately, CryEngine V does not provide automated functionality to import assets into your project. Fortunately, assets can still be moved between projects fairly easily. All you need to do is find the assets *.pak* files, and drop them into the assets folder for your project.

Downloaded asset folders should be placed in the same "Crytek" directory as the base CryEngine editor. That said, you can find them easily from the launcher. Go to *Library \> My Assets*, and ensure that the assets are downloaded. Once the status is *Installed*, you should have an arrow you can click on for a drop down menu. From this menu, select *Reveal in Explorer*.

Your own projects should be placed in *Documents \> CRYENGINE Projects*, but you can locate the directories directly from the launcher, by clicking on the cog button next to your project name and selecting *Reveal in Explorer*. You want to be copying your new assets to the internal *Assets* folder.

### Loading the SDK as its own project

It might be easier or more manageable to simply open the SDK, itself. Once located, you can open *GameSDK.cryproject* in its root directory to open the scene into CryEngine.

You may also want to save this reference to your CryEngine Launcher, so the SDK project comes up in your list of available projects. From the CryEngine Launcher, select *Import*, and locate the root directory of the SDK. This will be the same folder where its *.cryproject* can be found. Once selected and confirmed, *CRYENGINE SDK* should appear as an option in your projects view.

# Answer
> 1 votes
Cryengine V starts as a blank slate unlike Cryengine 3. If you've downloaded the GameSDK from the marketplace you still have to create a project that include assets. I would "Add Existing" project and navigate to and select the GameSDK folder.

---
Tags: cryengine
---


# Question
Title: Making icons for a Google Play Store game
I'm a little confused.

I've created a game using the Unreal Engine and I plan to publish in about a month. I knew my app needed an icon, but I was on Google's developer site yesterday and I saw a whole BUNCH of guidelines for icons, and there are several kinds. They say something about placing different versions of the icon in my 'resources' directory, but I didn't develop in Android Studio. I thought I would just be making one 512x512 icon, and uploading my APK (plus the other info).

Could someone who has used Unreal and published to the Play Store please help me :) Do I really have to make so many icons?

# Answer
No. Android will always pick the best match being available.

The basic idea is to provide multiple sizes of your icon (and other resources) so the device can pick the best fit without having to downscale (or visually worse: upscale) everything all the time.

Just remember a bigger icon will take more resources and scaling might not always result in the image quality you want.
> 1 votes

---
Tags: unreal-4, publishing, google-play
---


# Question
Title: Servers are never available to download CryENGINE
I have been having some trouble downloading the CryENGINE. I am directed to log in and download the engine through the CryENGINE Launcher, but whenever I try to log in, I get the error "Login failed. Server unreachable."

I can not find any reports of server malfunction, and others seem to be using it perfectly fine. This has gone on for over a week now. Whats going on?

# Answer
> 1 votes
"Server unreachable" is actually a poorly-worded error that *appears* to be associated with trying to log in with an unconfirmed account.

When you first create the account, Crytek will send you an email to confirm the account. Until you actually confirm the account, attempting to log in through the CryENGINE Launcher will give you the error "Server unreachable".

### Unfortunately, confirming your account may *also* be bugged.

Sometimes, confirming your account may be harder than you would think. Crytek send you the email, and you click on the link to confirm the account. This takes you to a page that acknowledges your confirmation, but the launcher still gives you the "server unreachable" error.

Sometimes, the link takes you to a page asking you to log in. When you attempt to log in, you are asked to confirm your account. If you follow the link provided via email, it takes you back to the same page, and the vicious cycle repeats itself. Attempting to resend the confirmation email may, instead, send you a thank you for confirming your email. Despite this apparent acknowledgement, you still can not log in to the CryENGINE Launcher.

This appears to be a known, yet uncommon, problem. Unfortunately, the only direct solution I have found is to contact Crytek, directly. The only times I have seen this solved is through direct communication on the forums, ~~which in turn requires you to have a confirmed account to access, giving you a painful Catch-22~~ not being able to contact Crytek was especially relevant to my question and answer, but I have since found contact through email at *cryengine@crytek.com*. This may be a helpful point of contact, if anybody runs into the same problem, and *really* wants to keep their original username or associated email.

***By far, the easiest solution is to make a new account with a different email***.

After several weeks of frustration, this solved the problem, for me. If you signed up with a particular email or username you really must have, use your new account to communicate with Crytek, who can directly toggle the "confirmed" switch on your original account.

---
Tags: cryengine
---


# Question
Title: Moving platforms left and right between two walls
I'm currently working on a rocket game where the player needs to collect parts from each level and in the main menu they can upgrade their own rocket with the parts found. But now I'm trying to add platforms that the player can land on, these platforms need to move left and right randomly until they hit the side of the screen then they reverse in the opposite direction and repeat.

Problem is now I spawn the platforms in randomly on the X axis and I need them to move in a random direction(on the x axis) from the start. As the level moves up the screen I have a collider that generates more platforms further up.

Any Idea what I should try to achieve the desired result?

here is my current code to move the platforms into random directions.

```
public class MovingPlatform : MonoBehaviour
{
    private float platformMin = -6.5f;
    private float platformMax = 6.5f;

    void Start()
    {
        RadomizePlatforms();
    }

    public void RadomizePlatforms()
    {
        GameObject[] platforms = GameObject.FindGameObjectsWithTag("Platform");

        foreach (GameObject platform in platforms)
        {
            Vector3 pos = platform.transform.position;
            pos.x = Random.Range(platformMin, platformMax);
            platform.transform.position = pos;
        }
    }
}

```

# Answer
> 1 votes
We will assume you have the basics of a platform the player can physically land on. You need to move it back and

## Keeping Direction

Use a single integer to keep direction, restricting it to the values of `1` and `-1`. That way, you can always tell your platform to "move by the product of 'Right' and 'Direction'". If `Direction = 1`, your multiplying by 1, which gives no difference. If `Direction = -1`, your simply inverting your original value, giving you the opposite direction.

```
int direction = 1;
float speed = 5;

gameObject.Translate(Vector3.Right * direction * speed * Time.deltaTime);
// move object by ((1,0,0) * 1 * 5) units per second
//  = (5, 0, 0) units per second

direction = -1;

gameObject.Translate(Vector3.Right * direction * speed * Time.deltaTime);
// move object by ((1,0,0) * -1 * 5) units per second
//  = (-5, 0, 0) units per second

```

You can then randomise the initial value of `direction` on creation of each platform, just as you randomise the initial x position.

## When to Change Direction

You can trigger direction change in one of two ways: by checking position at each `Update()` or by checking for direction change at each `OnCollisionEnter()`.

### via Update

During each `Update()`, you want to be moving your platforms. After each movement, simply check if they have reached the minimum or maximum distance, and toggle a direction change if they have. *Note*: This is a basic implementation, and it has its problems. For example, `minDistance` and `maxDistance` act as world-coordinates for the maximum border of the platform movement. Correcting movement past the borders is also a bit messier, but it gives you a rough idea of how to go.

```
float maxDistance = 10;
float minDistance = -10
int direction = 1;
float speed = 5;

void Update()
{
    transform.Translate(Vector3.Right * direction * speed * time.deltaTime);

    if(transform.position.x >= maxDistance)
    {
        transform.position = new Vector3(maxDistance,
                transform.position.y, transform.position.z);
        ChangeDirection();
    }
    else if(transform.position.x <= minDistance)
    {
        transform.position = new Vector3(minDistance,
                transform.position.y, transform.position.z);
        ChangeDirection();
    }

}

```

### via Collision

Since the player can stand on the platforms, we assume they already have colliders on them. We can assume the walls also have colliders, to stop the player from moving through. One option you have is to detect the platform colliding with the wall, in order to change direction. This might complicate your game more than needed, due to at-least one party in the collision event requiring a rigidbody. This can lead to other undesirable effects, in turn, but the option is always there.

```
public void OnCollisionEnter(Collision other)
{
    if(other.transform.tag == "Wall")
    {
        ChangeDirection();
    }
}

```

## How to Change Direction

With everything else in place, changing direction should be quite easy. Best practice suggests you limit direct manipulation of `direction` to a single method, which you call whenever you wish to change direction. From here, you can check the current direction to determine the new direction, or use a simple math hack to ensure the switch.

### Checking Directly

```
ChangeDirection
{
    if(direction == 1)
    {
        direction = -1;
    }
    else
    {
        direction = 1;
    }
}

```

### Checking with Maths

```
ChangeDirection
{
    direction *= -1;
}

```

---
Tags: c#, unity
---


# Question
Title: What is the correct way to use GameObject.Find in Unity?
I have been following along with a Lynda.com video course to familiarize with Unity. I am currently attempting to grab a reference to a scene's First Person Controller's transform as follows:

```
Transform targetObject;

// Use this for initialization
void Start ()
{
    targetObject = gameObject.Find("First Person Controller").transform;
}

```

And this is within a script/class that inherits from `MonoBehaviour`. However, this gives the error:

```
 Static member `UnityEngine.GameObject.Find(string)' cannot be accessed with an instance reference, qualify it with a type name instead

```

I am sure there is a way to just change the logic and get the desired affect with a different approach. But I do not understand why this results in an error. It is the same code used by the instructor of the course, and from the Unity Script Reference, I can see that `MonoBehaviour` inherits a `gameObject` member which has the `Find()` method. So this error is saying there is only one `GameObject` instance for all `MonoBehaviour` classes right? But shouldn't I still be able to call it's methods?

I am using Unity 4.1 with C# while the instructor is using 3.5 (with JS) if that helps any.

# Answer
> 8 votes
You actually just made a simple typo. `gameObject` is the current `GameObject` that your script is attached to. `GameObject` is the type. The error message is saying that the `Find(string)` function only works when it is called on the type (`GameObject`) not an instance of the type (`gameObject`).

Simply put, use `GameObject.Find("First Person Controller")` instead of `gameObject.Find("First Person Controller")`.

# Answer
> -3 votes
Transform targetObject;

```
// Use this for initialization
void Start ()
{
    targetObject = GameObject.Find("First Person Controller").GetComponent<Transform>();
}

```

---
Tags: unity, c#
---


title: Random scene manager in Unity

text:
# Question
Title: Random scene manager in Unity
*This may be hard to understand because this is hard to explain*

I have 6 scenes and one 'start' scene.

The start scene will be where my scene manager is.

So I want function where when the player clicks on the the start scene it goes to a random scene (from the 6 scenes) and then it goes to start. Then when you click again it goes to random scene, but this time these random scenes will be between the remaining 5 (excluding the scene the player just went on) and then it goes back to start. Then it goes to a random scene time, this time these random scene will be between the remaining 4. And so one.

*I already know how to go a random scene and back but I don't know how to do the remaining*

# Answer
you can use simple a simple list in C# to accomplish that

Suppose you are using the SceneManager.LoadScene() with the scene name overload, you can just store the six scene names in a C# list in a controller on your main scene

```
List<String> list = new List<String>();
list.Add(\name of your scene\);

```

And then on detection of a mouse click you could just do

```
int i = Random.Range(0,list.count-1);
SceneManager.LoadScene(list[i]);
list.RemoveAt(i);

```

this will ensure that no scene will be loaded twice
> 2 votes

---
Tags: unity, c#
---


# Question
Title: Unity 2D: Destroy object with dynamic collider after exiting object with static collider
I'm using the Unity5 game engine and am programming a 2D shooter in bird's eye view.

I have a static Box Collider 2D which covers the entire game area.

It has "Is Trigger" checked and contains a very simple script which should destroy every object that exits it.

```
 using UnityEngine;
 using System.Collections;

 public class DestroyByBoundary : MonoBehaviour {
     void OnTriggerExit(Collider other) {
         Debug.Log ("OnTriggerExit");
         Destroy (other.gameObject);
     }
 }

```

The player character shoots bullets which have a dynamic Circle Collider 2D.

However, the bullets are never destroyed when they leave the game area and just fly on indefinitely. The debug statement never gets executed either, of course. I have tried the same thing with OnTriggerEnter, which yields the same result.

If any more information should be needed, I'll be happy to provide it.

# Answer
As DMGregory has pointed out in a comment, I was using 3D objects and methods in a 2D environment.

I had to change the parameter of the script to a `Collider2D` object and use the `OnTriggerExit2D` method.

```
 using UnityEngine;
 using System.Collections;

 public class DestroyByBoundary : MonoBehaviour {
     void OnTriggerExit2D(Collider2D other) {
         Destroy (other.gameObject);
     }
 }

```
> 3 votes

---
Tags: unity, c#, 2d, collision-detection
---


# Question
Title: Point Sprite Size and Coloring OpenGL ES 2.0
I am trying to render point sprites with with variable color, but they are all black. Before I added `gl_PointSize = 5.0` they had color.

The environment is Android with C++, I believe OpenGL ES 2.0.

I have tried to work from point sprite size and applying color to point sprite, but have had no luck.

Vertex Shader:

```
precision mediump float;
precision mediump int;
attribute vec4 vertex;
uniform mat4 mvp;
varying vec4 v_color;
void main() {
  gl_Position = mvp*vertex;
  v_color = vertex;
  gl_PointSize = 5.0;
}

```

Fragment Shader:

```
precision mediump float;
precision mediump int;
varying vec4 v_color;
uniform sampler2D tex;
void main() {
  //gl_FragColor = vec4(v_color);
  //gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);
  //gl_FragColor = texture2D(tex, gl_PointCoord);
  gl_FragColor = vec4(v_color.rgb, texture2D(tex, gl_PointCoord).a);
}

```

All of the `gl_FragColor` assignments both commented and active lead to black points.

How do I give these points color?

# Answer
> 0 votes
Well this is embarasing; due to a unreliable build system I had the correct answer all along. For other running into this here is what the working shader looks like.

Vertex Shader:

```
precision mediump float;
precision mediump int;
attribute vec4 vertex;
uniform mat4 mvp;
varying vec4 v_color;
void main() {
  gl_Position = mvp*vertex;
  v_color = vertex;
  gl_PointSize = 5.0;
}

```

Fragment Shader:

```
precision mediump float;
precision mediump int;
varying vec4 v_color;
uniform sampler2D tex;
void main() {
  gl_FragColor = vec4(v_color.rgb, texture2D(tex, gl_PointCoord).a);
}

```

---
Tags: opengl, android, glsl, opengl-es2
---


# Question
Title: Components accessing Game state and other global data
I have the following example component:

```
public class DoStuff : MonoBehaviour
{

    public GameManager Data; // data to be shared among components and scenes,

    public bool Predicate()
    {
        return Data.State == Idle;
    }

    public void Execute()
    {
        if (!Predicate()) return;
        //Do stuff
    }
}

```

It needs to access data that I have in a data class (not a component) called GameInfo, which the GameManager creates on start. What is the 'best practice' for accessing data like that in a unity component.

1. Make GameInfo static (or Unity equivalent)
2. Drag the GameManager GameObject from my Scene on this component from the Editor
3. Use FindObjectOfType(typeof(GameManager)) to find the data on Awake/Start
4. Turn GameInfo into a component and attach to empty GameObject in my scene, then follow #2.
5. Some other method?

Thoughts:

1. Having come from working on Internal tools and webservices, making things Static is rarely a good idea, but maybe for Game development making my global game state data static is the exact thing to do.
2. I don't have any problems with this other than it just feels strange, but that's probably just due to being new to this mindset.
3. I believe this uses reflection to search, which if only done once at start would be no big deal, but I feel this option is less nice than #2.

# Answer
> 1 votes
I would recommend 4, Attaching your Component to a GameObject, but I would give it a unique tag as well. This would allow you to easily retrieve it with `GameObject.FindGameObjectsWithTag("UniqueTag").GetComponent<GameManager>(`.

Also, be aware that `static` classes don't actually keep their data between level transitions (which I assume you want to).
To do this you'll have to call `Object.DontDestroyOnLoad()` on the GameInfo object. Full tutorial here.

---
Tags: unity, c#
---


title: Why is my texture skewed?

text:
# Question
Title: Why is my texture skewed?
I'm creating hexagonal prisms from code and am having a difficult time understanding how UV mapping works, as the texture I apply to the hexagonal face comes out skewed:

Forgetting the sides for now, here is how I'm creating the hexagonal face:

```
    meshData.vertices.Add(new Vector3(x, y + 0.5f, z + 0.5f)); // N
    meshData.vertices.Add(new Vector3(x + 0.5f * (Mathf.Sqrt(3) / 2), y + 0.5f, z + 0.5f / 2)); // NE
    meshData.vertices.Add(new Vector3(x + 0.5f * (Mathf.Sqrt(3) / 2), y + 0.5f, z - 0.5f / 2)); // SE
    meshData.vertices.Add(new Vector3(x, y + 0.5f, z - 0.5f)); // S
    meshData.vertices.Add(new Vector3(x - 0.5f * (Mathf.Sqrt(3) / 2), y + 0.5f, z - 0.5f / 2)); // SW
    meshData.vertices.Add(new Vector3(x - 0.5f * (Mathf.Sqrt(3) / 2), y + 0.5f, z + 0.5f / 2)); // NW

```

This creates a regular hexagon. My texture is also a regular hexagon. So why does it get textured at an angle?

Here is my UV code:

```
    meshData.uv.Add(new Vector2(0.5f, 1));
    meshData.uv.Add(new Vector2(1, 0.75f));
    meshData.uv.Add(new Vector2(1, 0.25f));
    meshData.uv.Add(new Vector2(0.5f, 0));
    meshData.uv.Add(new Vector2(0, 0.25f));
    meshData.uv.Add(new Vector2(0, 0.75f));

```

# Answer
> 1 votes
Well, it turns out I misspoke--my hexagon texture was not, in fact, regular. I create most of my 2D programmer art in PowerPoint and mistakenly assumed that holding `Shift` while drawing a hexagon would make it regular. It turns out that this only creates an arbitrarily shaped six-sided polygon that scales proportionally.

Anyone who happens to be seeking a method for producing regular hexagons in PowerPoint can utilize the solution I found on SuperUser

---
Tags: unity, textures, vertex, uv-mapping
---


title: Get the object that triggered the event

text:
# Question
Title: Get the object that triggered the event
I am trying to make a simple tooltip for my game. I added event trigger to object that I want to trigger an event on mouse hover (PointerEnter).

And I want to get the game object that triggered the event in ShowTooltip(). I tried requiring BaseEventData in the void but it gave me error.

```
void ShowTooltip(BaseEventData baseEvent)
{
    Debug.Log(baseEvent.selectedObject.name);
}

```

**The error**: Failed to call function ShowTooltip of class UIManager

Calling function ShowTooltip with no parameters but the function requires 1.

# Answer
> 2 votes
By default, the Event Trigger only supports method calls that take 0 or 1 parameters. Since you are invoking `SendMessage()` through your event, your only invoking the method `SendMessage(string)`, as opposed to the overloaded option of `SendMessage(string, object)`. As such, you are not able to send the required parameters through to `ShowTooltip(BaseEventData)`, and are receiving an error because there is no `ShowTooltip()`.

## Providing reference to the calling object via Event Trigger

An easy solution I would suggest is simply creating a *public* tool tip method that takes an "identifier" variable, and invoking it directly, without the use of `SendMessage()`. If your original `ShowTooltip()` method does not need to be private, I would suggest just making it public, changing it, and directly triggering it from the Event Trigger. If it needs to be private, you can create an overload to call, which may still be public.

```
public void ShowTooltip(Object object)
{
    Debug.Log(object.name);
}

```

By accessing it directly, through the Event Trigger, you give yourself the allowance of providing an additional parameter. Simply drag the main object onto this field to create a contextual "self-reference".

## Providing additional parameters in a method, and Overloading

It is important to understand why your original method call did not work, as it is a core mechanic in programming.

When you create a method, adding extra parameters in the signature *does not* automatically provide those parameters in the function. You still have to provide the parameters during the *method call*. If you do not provide the minimum required parameters, when you call your method, it is not going to work.

Consider the following code fragment:

```
void ShowTooltip(BaseEventData baseEvent)
{
    Debug.Log(baseEvent.selectedObject.name);
}

void OnMouseHover()
{
    ShowTooltip();
}

```

When you call `OnMouseHover()`, it is going to call `ShowTooltip()`. This causes errors, because in this context, there *is* no `ShowTooltip()`. We have a `ShowTooltip(BaseEventData)`, but this does not match the exact method call we are using.

Ignoring the fact that fixing the error would not really solve your problem, it might be useful to understand the options you have for providing matching method calls, given the possible context. You have two options that would allow you to still call `ShowTooltip()`: providing default parameters, and overloading.

### Default parameters

When you list parameters in a method signature, you can often provide default values. These values need to be runtime-ready; You can not use a value that is not readily available, such as deriving a value from a differant function call. In this case, we are using `BaseEventData`. We do not have a default value readily available, but we *can* default it to `null`.

```
void ShowTooltip(BaseEventData baseEvent = null)
{
    if(baseEvent != null)
    {
        Debug.Log(baseEvent.selectedObject.name);
    }
}

```

We can now use this method signature to call either `ShowTooltip()` or `ShowTooltip(BaseEventData)`. If we do not provide a value for `BaseEventData`, it will default to `null`. It is important that you check that `BaseEventData != null` before using it in any way, to ensure you will not trigger null exceptions when you call this method as `ShowTooltip()`.

### Overloading

Another option you have is to simply write an additional method with the required signature.

```
void ShowTooltip()
{
    ...
    BaseEventData baseEvent;
    ShowTooltip(baseEvent);
}

void ShowTooltip(BaseEventData baseEvent)
{
    Debug.Log(baseEvent.selectedObject.name);
}

```

This way, you provide separate functionality, depending on wether you submit `BaseEventData` or not. You can also call alternate methods of the same name, so you have the option of working out `baseEvent` in `ShowTooltip()`, before calling `ShowTooltip(baseEvent)` from within.

Overloads do not have to be of the same protection level, either. You will have no problem with `public void ShowTooltip()` and `private void ShowTooltip(BaseEventData baseEvent)`. This makes it useful if you do not wish to have public access to your original method, as you can expose a 'weaker' variant for public access.

Overloading is also popular for supporting multiple formats. For example, you may wish to accept a value as either a `float` or an `int`. You could have `void DoStuff(float value)` and `void DoStuff(int value)`, to manually handle either option. ***You cannot have differant return types***, so keep that in mind, as well. `float DoStuff(float value)` and `int DoStuff(int value` will *not* work as I have described.

---
Tags: unity, c#
---


title: SmileBASIC sample programs source

text:
# Question
Title: SmileBASIC sample programs source
SmileBASIC (for Nintendo 3DS) comes with some sample programs.

I assume these are stored somewhere on the Micro SD card, but I cannot find them. Where are they? I would like to view the source on a PC.

# Answer
> 2 votes
The programs are not stored individually as files on the SD Card, they are stored in the game's extended save data.

---
Tags: nintendo
---


# Question
Title: Right click a location and move towards it (C# Monogame)
I would like the player to move towards the mouse when the player right clicks. The player does move, but doesn't stop when the player reaches the point. Here is the code.

```
void playerUpdate(GameTime gameTime)
    {
        float dT = (float)gameTime.ElapsedGameTime.TotalSeconds;
        player.pos.X += player.vel.X * dT;
        player.pos.Y += player.vel.Y * dT;

        player.checkDest(x2y2, player.pos);

        if ((mouse.RightButton == ButtonState.Pressed) && (player.moving == false))
        {
            x2y2.X = mouse.X;
            x2y2.Y = mouse.Y;

            player.move(x2y2, player.pos);

        }
    }

```

The player's file,

```
        public void move(Vector2 dest, Vector2 pos)
    {
        dist.X = pos.X - dest.X;
        dist.Y = pos.Y - dest.Y;

        vel.X -= dist.X;
        vel.Y -= dist.Y;

        moving = true;
    }

    public void checkDest(Vector2 dest, Vector2 pos)
    {
        if (pos == dest)
        {
            vel.X = 0;
            vel.Y = 0;
            moving = false;
        }
    }

```

I assume it is because of the player's position and its use of decimals and the mouse position being integers. How could I work around that?

# Answer
> 1 votes
You could compare player's distance to the destination and if it's small enough, stop. So replace this line:

```
if (pos == dest)

```

with

```
if (Vector2.Distance( pos, dest ) < 0.1f) // Adjust the value if it's not good

```

---
Tags: c#, movement, monogame
---


# Question
Title: How to change a class's variables at runtime without knowing in advance which class's variables to change?
I am creating a nuclear war simulation game a bit like Defcon if any of you have played that. In the game you can chose one of several regions to play as and in my game I want each region to have different stats for their weapons and I want these stats to be changeable throughout the game if a region decides to develop a particular weapon for instance.

So I have a generic Weapon class that has a damage, a cost, a range etc. I then have different types of Weapon all stored in a WeaponArsenal class (ICBM, MRBM etc). Each region has different values for each of these and it needs to be possible to change them when the player or AI decides to upgrade a weapon.

Of course I can't predict which region the player will pick and therefore can't determine which regions will be AI controlled and which will be the player region. At the moment each available region is a class which has its own values for its weapons through an object but I don't know how I can chose which class to use for the player at run time without very repetitive if statements.

How can I therefore allow the player to upgrade their selected region's weapons without knowing their chosen region and calling a function explicitly?

Should I make a pointer to an object and point it to a different class's object depending on input at the start and then use this object pointer to change a region's variables throughout the game, and is having each region be its own class the best way of setting the game up? I have heard that making each region a map might make things easier but do not now how I would implement this. Which data structure should I use and how should I implement it?

The weapon class:

```
class Weapon
{
private:
    int count;
    int damage;
    float cost;
    int range;

public:
    void upgradeRange(Weapon wep, float p) {
        float percentDecimal = p / 100;
        float modifier = percentDecimal + 1;
        wep.range * modifier;
    }
    // more functions for upgrading each stat
    // more functions for setting and getting each stat

}

```

The WeaponArsenal class:

```
class WeaponArsenal
{ /* Weapon Types */
public:
    Weapon icbm;
    Weapon mrbm;
    Weapon srbm;
    Weapon bomb;

    WeaponArsenal() {

        // DEFAULT ICBM VALUES
        icbm.setCount(0);
        icbm.setCost(120);
        icbm.setRange(8000);
        icbm.setDamage(80);

        // DEFAULT MRBM VALUES
        mrbm.setCount(0);
        mrbm.setCost(100);
        mrbm.setRange(2000);
        mrbm.setDamage(70);

        // DEFAULT SRBM VALUES
        srbm.setCount(0);
        srbm.setCost(80);
        srbm.setRange(800);
        srbm.setDamage(55);
    }
};

```

A region class:

```
class Europe
{
private:
    WeaponArsenal arsenal;

public:

    Europe() {
    }
};

```

Full main.cpp file so far is on Github:

# Answer
> 1 votes
There are many ways to build an object hierarchy. There is no one "right" way. Just methods which don't work at all, and you seem to have implemented one, because it doesn't allow you to easily do what you want to do. But this is how I would do it:

1. Make `Region` a class. All the regions should be instances of that class. **If** the different regions have different game mechanics which need to be expressed with code (and that's a big IF), you could have some regions be classes inheriting from `Region`.
2. Have each `Region` own a list of `Weapon`s. The additional class `WeaponArsenal` doesn't seem to add much value at this point of development. I would place that functionality directly in `Region`. When the game becomes more complex and the class `Region` too large, it might make sense to outsource parts of its functionality into different classes. But IMO it's too early to make that call.
3. Add a method to `Region` which is used to upgrade the weapons it owns. Also add methods for everything else a Region can do (fire weapons, surrender etc.)
4. Create a class `PlayerController` which holds a reference to a `Region`. Assign that reference to the region the player selected. The `PlayerController`'s purpose is to process the players input and translate it into method-calls of the Region-object assigned to it.
5. Create a class `AiController`. Just as the PlayerController you assign a Region to it. The difference is that it decides for itself when to call which method on Region.

---
Tags: data-structure, c++
---