# Question
Title: What games benefit strongly from using motion controls?
A lot of games use motion controls, be it Wii, Kinect or otherwise, but for most of them, this control scheme seems forced. What are the games that benefited the most from using motion controls (as in, if they were to be controlled by a traditional controller, it would detract from the experience)? Having such examples could help one make the decision of whether those controls are beneficial for what they are developing

For example, Super Mario Galaxy is a great game, but its use of shaking the remote to jump is quite arbitrary and does not add to the experience. On the other hand, Flower uses sixaxis in such a way as to make it part of a great experience.

(I know this question borderlines Gaming SE, but their FAQ prohibits "Catalogues". I decided to put it on this SE, as having good examples of how to do things well is a valuable resource for anyone hoping to achieve similar greatness.)

# Answer
In order to understand what motion controls might be good for, one should look at the way one uses the motion controller:

* Endurance - motion controls require more movement than using traditional controllers. This limits the length of the interaction with the game to the amount of time in which one gets physically tired from moving. This requires a motion controlled game to either require short periods of high activity (like a sports game that one can play and finish in under a minute), or longer periods of smaller activity (like being able to rest one's hands and controller on the lap and control the game with gentle movements).
* Precision - motion controls are less precise as a traditional controller. Simply put - one's hands shake, body sways, and one can't hold a still position for long, not to mention lack of force feedback for controller-less controls (like Kinect). A good motion-control game thus needs to be more forgiving in that department (pixel accuracy is impossible, unlike using mouse for example). This constrain favours more stylized games, where often movement is exaggerated and cartoonish.
* Speed, a finger is faster than a hand - if one has the option of performing an action with a button, or a gesture, the first should be chosen. First off, this allows the players to get quicker response time from the game, and second, it allows them to time their events better. If motion control is to be a gimmick and not add anything to the gameplay, then it should be avoided.
* Gestures - a motion controller can allow a player to perform gestures faster, than one would be able with a controller (comparison with a mouse might not be so clear). If one is to use only one gesture in a game (say, a shake), it might as well be replaced with a button, unless the way the gesture is performed affects its outcome. Similarly, if there are multiple gestures one can perform all with a different output, motion controls might be preferred.
* Design limitations - using a motion controller requires the player to adjust him or herself to accommodate for the way to use the controller, and the game design needs to take all the aspects of controller use into consideration. For example, a game on Kinect requires a spacial room, whereas use of Move means that there is a constant colourful light in player's hand. One would not want to make a very dark and serious survival horror using the second one for example, as having a glowing pink controller makes it very hard for the player to get immersed in the game.

Here are some examples of the above I encountered during my experience as a gamer:

* Endurance, short bursts of activity - Wii Sports Resort, WarioWare Smooth Moves - both of them consist of short periods of high activity broken up by small cutscenes and animations. One can take a byte out of those games and be done in a minute, or however much time before one gets tired.
* Endurance, long and gentle activity - Flower - One can rest in a couch and slowly move the controller without much effort to control the game.
* Precision - Boom Blox - before making each throw, the player can aim and "grab onto" a point on the screen. The grab can be released and reattached multiple times, so there is no penalty for error and one can try over and over until a satisfactory result is reached.
* Speed - Super Mario Galaxy - in order to double jump, one needs to shake a remote. The same could be accomplished by using a button (if it was mapped), so the use of motion control is detrimental.
* Gestures - Okami (Wii version) - one of the central elements of the game is drawing of various shapes. Most common ones are straight horizontal lines that a player can whip out in a split of a second by a quick jerk of a hand to the side. The same could not be accomplished in the PS2 version, where the brush speed was limited by the use of analogue stick.
* Design limitations - (luckily) I had no experience with a game that would be either good or bad in this regard.

And a short list of notable games that use motion control well:

* Flower - perfect game in this category
* WarioWare Smooth Moves - a pretty good game relying a lot on motion controls
* Okami - very good execution of motion controls for drawing, less so for combat
* Trauma Team - pretty tight motion controls, although a bit unforgiving at times (time-slowing gesture for example)
* Boom blox - a pretty good game (although somewhat repetitive at times) with good motion controls

And some notable bad uses of motion control:

* Super Mario Galaxy, Kirby's Epic Yarn, New Super Mario Bros. Wii - arbitrary usage of controller shaking that could be easily replaced at least in most occasions with a button
* No More Heroes - Most if not all of the game could work without motion control and could even be better for it
> 4 votes

# Answer
I think the most obvious point is that motion controls are analogs.

Using an analog controllers as a digital controller is possible. But it's also less efficient : digital controllers are more responsive and less prone to failures. Unresponsive controllers are bad. Try playing a game like street fighter with an analog gamepad : it's terrible.

I would say that game who benefits strongly from motion controls are analogs, whatever does that mean. Use a lot of floating points numbers. Don't rely on pixel collisions. Don't lock the player on an axis (like most tps). Don't make a RPG based on skill points and formulaes. Rely on simple emergent rules rather than complicated and well defined rules.

Roguelike and tile-based tower defense seems like a bad choice for a Wii game.
> 1 votes

# Answer
Games that have real life counter parts benefit the most from motion controls. Sports for example but also racing games and shooters - though this one is more because the controls are were designed with aiming in mind.

I honestly can not think of any game I've played that did not fit into the previous category that I would say really benefited from motion controls. It is really about the dominant strategy when it comes to controls. No one is really going to love motion controls if normal controls (gamepad for example) are superior.
> 0 votes

# Answer
I know this is an old question, but it could use a modern answer. The motion sensors in PS4 and Switch controllers are precise and responsive when used correctly. This is an area of expertise for me, as the creator of accessibility tools that focus on what's possible with good gyro controls.

The simplest rule of thumb for considering what games benefit from gyro controls specifically is:

> If it plays better with a mouse, it plays better with gyro.

For an in-depth how-to on implementing gyro controls that are precise and responsive, see here: Good Gyro Controls Part 1: The Gyro is a Mouse.

Games like Super Mario Galaxy (from your example) wouldn't obviously benefit from a mouse except in isolated ways (aiming at star bits), and (conveniently for my answer) doesn't actually benefit from its motion controls except in isolated ways (aiming at star bits). Using motions like shakes and swings to replace inputs that only require a button press is usually going to make for a worse experience, as explored in other answers.

But I do want to get past the idea that motion controls are imprecise. This is a symptom of the way they've been used and implemented. This is not an intrinsic property of motion sensors in modern hardware (PS4 and Switch controllers).

Shooters favour a mouse over aiming with a thumbstick. And, when done right, gyro aiming is actually much easier to learn and much more precise than thumbstick aiming: example on YouTube.

This benefit extends to other games that are virtually unplayable without a mouse: top-down MOBAs like Dota 2 and LoL, some puzzle games like Opus Magnum, management games like Cities Skylines, even RTS games like Age of Empires, though the gap between gyro and mouse remains an obstacle in that case, as well as the limited number of buttons on a controller.

Comparing it with a mouse doesn't cover every case, of course. Many players prefer gyro and accelerometer controls for steering cars over using a tiny joystick on a controller. It's easy to imagine how a mouse could be used for analog steering, but for whatever reason it doesn't appear to be as widely pursued.

The gyro is on balance not better than a mouse for most games designed with a mouse in mind. But it's a lot closer than a thumbstick, even with all the incredible amount of work that goes into modern aim assist.
> 0 votes

---
Tags: game-design, game-mechanics, motion-control
---


# Question
Title: Why are there no in game time subscription options?
Many games employ a monthly subscription to play a game. However, this makes coming back to a game pretty difficult, as you are most likely unsure of whether you will be playing the game for a few months or a few days.

Why are there no games where you subscribe for in game time (or why is it not common practise)? That would allow returning players to either have some game time left when they return, or not feel so bad for buying more game time in the case they end up playing the game for only a couple of days. I believe a monthly subscription could exist alongside an in game time subscription. Currently, this is stopping me from playing a couple of games.

# Answer
> 3 votes
I suspect one of the main reasons is that you would get charged if you left your screen and left it running by accident. Imagine you were playing your phone game while waiting for the microwave to finish. You hear a pop, quickly put down your phone to make sure your oatmeal didn't explode. You see that your oatmeal is done, so you sit down on the couch and eat it, getting sucked into a good show. 2 hours later, you pick up your phone, only to realize that all your game time is done.

This would not be a good situation as a customer. With a monthly subscription, you are putting an upper cap on how much money you'll be paying, and you don't have to closely monitor your playtime. Customers who aren't closely monitoring their playtime tend to get more involved in the game, and will likely spend much more money on other game-related purchases like DLC or items.

Furthermore, paying for playtime makes you feel like each second spent in game needs to be worthwhile, so small annoyances or farm-ey gameplay would seem extra tedious, and be actually costing you directly. It would make this downtime seem absolutely unbearable.

For games with any form of strategy, one of the joys (at least for me) is to stare at the screen in-between action and plot how to maximize my power, or plan my next acquisitions or upgrades. If I was paying per minute, this would probably never happen.

For multiplayer games, waiting for other players, although already very annoying, would be absolutely unbearable if you were paying for that time.

# Answer
> 2 votes
Mobile games actually do something pretty similar sometimes, with energy meter mechanics. You get some number of matches you can play for free, and then if you want to play more you either have to wait a long time or pay a bit of money to buy more energy. There's often some way to get a monthly subscription if you want to play a lot, too. It avoids most of the problems Adam B mentioned since you pay for matches (which usually have pretty consistent lengths, but in turn-based games still let you think for as long as you want) rather than for individual minutes.

If you forget to buy the subscription, or the game doesn't offer one, you may be surprised by how quickly buying more energy can slurp up all of your real life cash.

# Answer
> 1 votes
Due to Sunk Cost Fallacy, a person will feel that if they already paid for a month worth of game, they might as well spend that month playing, while if they payed daily, they can quit any day.

Since subscription based games rely, at least to some extent, on the addictive nature of the game, making the player keep playing for more than a few days will increase the chance to "hook" them.

It's not the only reason, but I believe it is a big part of it.

---
Tags: game-industry, payment
---


title: Issues with 3dsmax and Unity3d scale

text:
# Question
Title: Issues with 3dsmax and Unity3d scale
I changed the units in Blender so they are identical to Unity 3d. If I make a 1m^3 box in Blender, it will import into unity as exactly the same size as the standard cube.

With 3ds max, I changed the unit setup to metric and made sure it was centimeters in the system unit setup tab. However, when I import an obj file made in Blender and used in Unity, it is absolutely tiny. I have to convert the model to meters on import and then, when exporting, I have to set the model scale to .01 otherwise it is enormous in the unity scene.

I've tried changing the max units to meters and nothing changed.

How do you change the max unit/grid setup so one grid unit is 1m^2 and exactly equivalent to unity's grid?

# Answer
> 1 votes
Obj files don't save what measuring unit you are using, only coordinates. If you used meters and made a 1m3 cube, it would save something like:

> (0,0,0) (1,0,0) (0,1,0) (0,0,1) (1,1,0) (0,1,1) (1,0,1) (1,1,1)

There would be no mention of meters or centimeters in that file. If you were to open that file in a program that uses centimeters, it would see it as a 1cm3 cube instead of a 1m3 cube, and vice versa.

---

I'm not proficient with 3ds Max, but from what I've seen, there are a few possible reasons why yours works the way it does:

* First problem could be scaling. 3ds Max could be scaling your models to 0.01, you have to set that to 1 and I'm not sure how you do this, but this is most likely not the problem you have (see this link).
* Second problem could be that you are using the wrong units as your export. You said you were using centimeters, where you need to use meters (see this link). You can change this from the interface menu (see this link).

# Answer
> 0 votes
For importing 3D max objects correctly in Unity (by same Scale and Pivot) you need to do the following:

**1- Scale issue**

1-1: In 3D max go to Customize -\> Units Setup

1-2: Click on System Unit Setup

1-3: Select 1 Unit = 1 Meter and select ok

1-4: Also in Units Setup select Meters for Metric in Display Unit Scale

**2- Pivot/ Coordinate issue**

2-1: In 3D Max Select any object and go to Hierarchy and select Pivot and Affect Pivot Only

2-2: Then select the Rotating tool from the toolbar and add 90 in x Axis.

2-3: unclick "Affect Pivot Only" in Hierarchy

----Done----

You can open 3D max files in Unity totally fine now :)

---
Tags: unity, grid, 3dsmax, scale
---


# Question
Title: I accidently changed the cursor image in Unity
In the Unity Editor I accidently changed the image for the mouse cursor in project settings \> player

How can I restore it to the default, preferably not through programming?

# Answer
Click on the "Default Cursor" texture again and select "None"
> 1 votes

---
Tags: unity, mouse, editors
---


title: Force Immediate Button Update in Unity

text:
# Question
Title: Force Immediate Button Update in Unity
I am working in unity and I have a group of buttons that I activate/deactivate at various times in the game. However, I have noticed that when I call `button.SetActive(true)` the button doesn't appear in the scene right away. In one particular circumstance, I need the button the appear before the next line of code is run. Is there a way to force the button/scene to update immediately?

Edit: To give some context, I am working on a card game similar to Magic the Gathering where there are different types of mana and there are some cards with a neutral cost. When a player plays one of these cards I activate 5 buttons (one for each mana type), and I want the player to click a button to spend one mana of that color, and to repeat that process until the neutral cost is met.

When I try to use a while loop or a coroutine to essentially pause execution until a user clicks a button (or multiple, depending on the card's cost), I cause an infinite loop because even though I set the buttons to active before the loop/coroutine, they don't actually activate by the time the loop starts.

# Answer
> 2 votes
> I try to use a while loop or a coroutine to essentially pause execution until a user clicks a button

This approach won't work. If you pause the execution of your game, you also pause the renderer, UI system and everything else the engine does. Even if you could force the engine to immediately render the button (it will only want to do that for the next frame), the player couldn't click on the button because the event system won't have an opportunity to process the click until your update has finished.

What you should do instead is use the concept of different game states.

* During the "select a card" state, the player can click on any card in their hand attempting to play it. All other controls are inactive or disabled. When the player selected a card to play, the game switches to the "spend mana" state.
* During the "spend mana" state, the 5 mana buttons activate for the player to click them. When the player spent enough mana, the game switches to the "execute card" state. You might also want to add some way to cancel the process and return to the "select a card" state without paying mana. All other controls are inactive or disabled.
* During the "execute card" state, you play the animation to play the card and the resolution of its effects. All controls are disabled. When the card has finished, you return to the "select a card" state.

A good way to implement this in Unity is to put everything you need to be active for each state into a separate game object. This includes game mechanics scripts, spatial game objects and a separate UI canvas for any UI controls you want to be visible during that state. When you switch from one state to another, set all state game objects to inactive and set the object for that specific state to active.

---
Tags: unity, scene
---


title: How to remove jitter from motion input?

text:
# Question
Title: How to remove jitter from motion input?
I am writing a Minecraft mod that supports input from the Razer Hydra. It is a pair of motion controllers (one for each hand) that provide incredibly accurate position and rotation information.

For the purpose of this question, rotating the right controller on the Y-axis cause the player's character to look left or right (yaw), and rotating on the X-axis makes the player look up and down (pitch).

The input from the controller is mapped directly to the character's heading. If the controller is rotated 30 degrees left, the character turns 30 degrees to the left.

The problem is that the input "jitters". If I try to hold the controller perfectly still, the character's heading moves erratically within a very small cone (maybe 1 degree).

This is probably due to my shaky hands, as the controller's data is seemingly exact.

I tried filtering input by averaging data from the last X frames, but this makes input seem buttery.

My question is: How can I filter the rotational data to remove jitter without loosing precision?

# Answer
This lag-vs-responsiveness issue is the situation with virtually all motion controllers, whether something like the Hydra, the Wii Remote, the Kinect, or the PlayStation Move.

The problem is this:

When an input stream is coming in, you're making a decision on a frame-by-frame basis about whether or not to trust the input data; whether the trends you're seeing now will have continued in the data you receive a dozen milliseconds from now. For example, if there's a sudden shift to the right this frame, you don't know whether it's a real bit of input data (and so you should act on it) or whether it's merely jitter (and so you should ignore it). Whichever you pick, if you later discover that you were wrong, you've either allowed the input jitter to make it into your game (in the first case), or introduced lag into your game (in the latter case).

There is no good solution to this. A "correct" solution to determining whether input is real or jitter requires knowing what the input stream is going to do in the future, as well as what it did in the past. We can't do that in games, for obvious reasons. **So no, there is no way to filter rotational data to remove jitter without losing precision, in the context of a game which is working with input data in real-time.**

I've seen a major manufacturer recommend that developers deal with this problem by having players hold down a button while rotating the control, so that the game can turn off its anti-jitter code at that point, so it's non-laggy. (I don't recommend this, but it's one approach).

I've seen a few motion input middleware libraries which deal with this problem by introducing an artificial delay in the input -- there's a quarter-second buffer that input data goes into, and your game only hears about the input a quarter second later, so that the library can smooth out the jitter for you, by knowing what happens both before and after the "present" from the game's point of view. That works great, apart from introducing a quarter second of lag to everything. But it's one way to solve the problem, and it can do an awesome job of accurately representing a motion with jitter removed, at the expense of constant lag.

But without going to that extreme, there are still some things we can do to give vastly improved behaviour, even though we know that there will always be "worst case scenarios" which behave in a non-ideal fashion.

The core insight is that we only really care about jitter when the controller is mostly stationary, and we only really care about lag when the controller is being moved. So our strategy should be to try to deal with things so that we have lag when the controller is stationary, and have jitter when the controller is in motion.

Here are two possible ways to do that:

One common approach is a "locked/unlocked" system, in which you keep track of the device's orientation, and if it doesn't change for a short while (half a second or so), you 'lock' that orientation, taking no action based upon the device's reported orientation until it differs enough to 'unlock' again. This can completely squelch orientation-based jitter, without introducing lag when the orientation is actively changing. There might be a hint of lag before the code decides it needs to switch into "unlocked" mode, but it'll be a lot better than having lag everywhere.

Another approach is to average together input data from frames. The important point here is to only average together the input data from frames where the input data was vaguely similar -- This meant that small jitters will get blurred together and softened, but larger changes don't get blurred, because their data isn't similar enough to the data from previous frames.

There are other ways to get a similar effect as well. The core insight is that you can't have both non-jitter and non-lag in your real-time game at the same time, because to do that would require knowledge of the future. So you need to pick when to bias your control's behaviour toward accepting jitter and when to bias it toward accepting lag, in order to make the overall experience as non-bad as possible.
> 8 votes

# Answer
I develop software that converts motion input to responsive and precise mouse input, as well as maintain a website that tries to help developers implement equally good solutions themselves. I generally advise against movement thresholds, although it depends how much responsiveness and precision players want, I'm glad that's working for you in your situation. But here I'll offer a different solution:

I use something called Soft Tiered Smoothing. The idea is that we divert input through different smoothing algorithms depending on the current magnitude of the gyro velocity (in practice, one of those smoothing algorithms is just "no smoothing"). That's the "tiered" part. The "soft" part is that we can actually smoothly split the input between different smoothing algorithms depending on how it compares to 2 thresholds.

It preserves displacement correctly and adds no lag whatsoever to quick movements.

In practice, you have two thresholds. When the magnitude of the input velocity is less than the lower threshold, we're using a simple smoothing algorithm (average across multiple frames). When it's greater than the other threshold, we use no smoothing algorithm at all. But in this case, we're still passing zeros to the lower-threshold smoothing algorithm.

When the input velocity is between the two thresholds, we split the input between the two algorithms accordingly.

Here's a snippet from the article above:

```
GetSoftTieredSmoothedInput(Vec2 input, float threshold1, float threshold2) {
    // this will be length(input) for vectors
    float inputMagnitude = Abs(input);

    float directWeight = (inputMagnitude - threshold1) / (threshold2 - threshold1);
    directWeight = clamp(directWeight, 0, 1);

    return GetDirectInput(input * directWeight) +
        GetSmoothedInput(input * (1.0 - directWeight));
}

```

GetDirectInput just returns what's given to it, but it's to show that another smoothing algorithm could be used here. GetSmoothedInput takes a velocity and returns a smoothed velocity.

With Soft Tiered Smoothing there is no smoothing applied to obviously intentional movements (above the greater threshold), there is smoothing applied to cover up small amounts of jitter, which will also affect very small movements, but when you get your thresholds right it's not very noticeable. And there's a very smooth transition between the two (without which, jitter can actually be amplified).

While the other answers are right to say that it's difficult to recognise jitter the instant an input is received, it's also true that jitter is almost always very low velocity, and the input lag that comes with smoothing is far less noticeable for low-velocity inputs.

As the article mentions, this is used in a couple of places in my open source tool JoyShockMapper, an input mapper that turns gyro input into mouse input. Even for people using other remapping tools like Steam or reWASD, some use JoyShockMapper at the same time just for its gyro controls.

This answer assumes the input is given in angular velocity (which is common with controllers that have motion controls), not absolute orientation (which it sounds like the Razer Hydra is giving you). With absolute orientation, my hope is you can use the difference between the current orientation and the previously reported orientation to get a velocity, but I don't know for sure if it'll work as well as with controllers that self-report angular velocity.

A common smoothing solution when you're dealing with an absolute position/orientation rather than velocities is to interpolate towards your goal orientation over time -- this is described in very helpful detail in this Gamasutra article. This can work with Soft Tiered Smoothing, too. You'll calculate the velocity magnitude using the difference between this input and the previous reported input. You'll apply the difference in orientation between this frame and last frame multiplied by your "directWeight" value as calculated in the snippet above. The last step is adding the smoothed input, but because of the way the interpolated orientation smoothing works, you just apply the interpolated orientation change as per normal -- it doesn't need to consider "directWeight" at all. Just set your target orientation (this is what you're interpolating towards with the smoothing described in that Gamasutra article) to whatever orientation you're getting from the device, and interpolate your orientation towards it as described in that article.
> 2 votes

# Answer
It feels weird to answer my own question, but I think I've found my solution.

```
//Pseudo-Java

update()
{
    //deltaYaw is the change in yaw of the controller since last update
    //yawBuffer is initialized to zero, and only modified here
    //coneAngle is the stabilizing cone

    deltaYaw = getData().yaw;

    yawBuffer += deltaYaw;
    if (abs(yawBuffer) >= coneAngle)
    {
        player.yaw += (abs(yawBuffer)-coneAngle) * sign(yawBuffer);
        yawBuffer = coneAngle * sign(yawBuffer);
    }
}

```

Instead of modifying the player's heading directly, I simply "push" a cone of a given angle (in my case, 2.5 degrees). I made a small HTML5 demo of this technique.

Once you start pushing the cone, there is *zero* delay and full precision. However, if you push the cone left, and then want to aim right, you have to move across the full angle of the cone to see an effect.

So it solves the issues of temporal delay and horrible smoothing, but introduces the new problem of a movement threshold. However, if the stabilizing cone is tuned correctly, the threshold is unnoticeable.
> 1 votes

---
Tags: minecraft-modding, motion-control
---


title: Material is flickering in Unity

text:
# Question
Title: Material is flickering in Unity
I'm trying to make a grid like, light up floor using Unity's Shader Graph. However, I am having an issue where the lines are flicking after a really short distance when the camera is moving.

The shader graph is below.

How can this issue be prevented and what is causing it?

# Answer
> 9 votes
As Foxwarrior says, this issue is due to spatial aliasing. At a certain distance away, the stripes on your plane pack together closer than you have pixels/samples to display them: so whether the sample point lands in a bright or a dark patch depends sensitively on the position of the camera. A tiny offset can make a distant pixel jump suddenly from light to dark or dark to light, creating a noticeable flicker as your camera moves.

You can fix this by changing your shader graph to analytically integrate the brightness of your grid over the full square the pixel covers - so rather than sampling just the point at the center of the pixel, you get an averaged-out value that changes more gradually under small camera movements, or blurs the grid toward an average colour when it becomes too fine to sample accurately.

> On the right, a grid rendered with your current technique, showing severe aliasing in the distance, dissolving into static as pixels hit lines or holes almost at random.
>
> On the left, a box-filtered grid, where the white lines fade into the distance as they get finer (instead of maintaining the same full brightness even when they account for only a fraction of a pixel).

Inigo Quilez has shared a number of analytical integration formulas here. We can use the "Box Filtered Grid" example:

```
float filteredSquares( in vec2 p, in vec2 dpdx, in vec2 dpdy )
{
    const float N = 3.0;
    vec2 w = max(abs(dpdx), abs(dpdy));
    vec2 a = p + 0.5*w;
    vec2 b = p - 0.5*w;
    vec2 i = (floor(a)+min(fract(a)*N,1.0)-
              floor(b)-min(fract(b)*N,1.0))/(N*w);
    return 1.0-i.x*i.y;
}

```

And convert it to a shader graph like so:

# Answer
> 4 votes
When the renderer draws something to the screen, it takes one or a few samples of each pixel and puts the average color there. Light gray to dark gray could be that the pixel has been sampled at 3 white, 1 black in one frame, and 1 white, 3 black in the next. Moiré patterns are the related physical phenomenon.

You can increase the number of samples with Anti-Aliasing settings (it's resource-intensive though) or try messing around with mip-mapping settings or Shader Graph depth effects to have it blur the far away parts so the lines end up being a more consistent gray instead of flickering so much.

A completely different approach to drawing the grid using vector art instead of 3D rendering may also work.

---
Tags: unity, unity-shader-graph
---


# Question
Title: How to control which path a unit will take?
**This might be a really easy solution that I probably just do not know due to lack of experience so thanks for any and all the help. TLDR at bottom of post.**

I'm still learning Unity / C# and I am following Brackey's Tower Defense tutorial series while adding my own twist. The tutorials use levels with only 1 available path for units to walk along. However, the game I am currently developing has 3 separate paths that units can walk along.

Essentially, the game is similar to the mobile game Clash Royale with 3 lanes except it is also a tower defense.

Here is the current layout:

The different lanes are empty gameObject labeled as Path1 (red), Path2 (blue), and Path3 (green). The nodes laid out in each path are all children objects of their respective path.

Each of the parent path objects contain the following script:

```
public class Waypoints : MonoBehaviour
{
    public static Transform[] points;

    private void Awake()
    {
        points = new Transform[transform.childCount];
        for (int i = 0; i < points.Length; i++)
        {
            points[i] = transform.GetChild(i);
        }
    }
}

```

Now, following the tutorial, I have also successfully added an enemy that contains this EnemyMovement script:

```
public class EnemyMovement : MonoBehaviour
{
    public float speed = 10f;

    private Transform target;
    private int waypointIndex = 7;

    void Start()
    {
        target = Waypoints.points[7];
    }

    void Update()
    {
        Vector3 dir = target.position - transform.position;
        transform.Translate(dir.normalized * speed * Time.deltaTime);

        if(Vector3.Distance(transform.position, target.position) <= 0.2f)
        {
            GetNextWaypoint();
        }
    }

    void GetNextWaypoint()
    {
        if(waypointIndex <= 0)
        {
            Destroy(gameObject);
            return;
        }

        waypointIndex--;
        target = Waypoints.points[waypointIndex];
    }
}

```

Now, as it currently stands, whenever I have an enemy present on the field, it will successfully run down path2 (blue nodes). However, it will ONLY run down path2. I would like to be able to decide which path the enemy will take. Eventually, the enemy's actions will be decided by an Enemy AI.

The player will also be able to spawn units and will be able to decide which path the unit will travel.

So to reiterate:

**TL;DR:** Following Brackey's Tower Defense tutorial. Currently, enemy will always default to path2. I need to figure out how to have control over which path, out of 3 options, an enemy or friendly unit will take.

# Answer
There are many possible solutions to your problem. Some will be more reusable and flexible but for now, let's keep it simple and go with only few changes:

The problem with your current waypoint solution is that the `Transform[] points` array is static, which means all enemies see the same waypoints and the other two paths' waypoints are overwritten by the points your enemy script is seeing (each Waypoints gameobject creates a new array, thus overwriting the array created previously by a different waypoints gameobject).

For now I assume it is ok for the enemy to just pick one of the three paths randomly.

First, store all paths' waypoints in an unique `Transform[]` array within a list:

```
public class Waypoints : MonoBehaviour
{

    public static List<Transform[]> pathPoints = new List<Transform[]>();

    private void Awake()
    {
        Transform[] points = new Transform[transform.childCount];
        for (int i = 0; i < points.Length; i++)
        {
            points[i] = transform.GetChild(i);
        }
        pathPoints.Add(points);
    }
}

```

Each Waypoint will now add it's points array to the list instead of overwriting the existing pat

Next, modify your enemy script to randomly pick one of the available paths and then use the points of the picked path:

```
public class EnemyMovement : MonoBehaviour
{
    public float speed = 10f;

    private Transform target;
    private int waypointIndex = 7;
    private int selectedPath = 0;  // New

    void Start()
    {
        // Select between 0 and max path, currently 3 paths so this selects a random number between 0 and 2 (zero-based index)
        selectedPath = Random.Range(0, Waypoints.pathPoints.Count);
        waypointIndex = Waypoints.pathPoints[selectedPath].Length - 1;
        // Select the points array depending on selected path, and from there the waypoint
        target = Waypoints.pathPoints[selectedPath][waypointIndex];
    }

    void Update()
    {
        Vector3 dir = target.position - transform.position;
        transform.Translate(dir.normalized * speed * Time.deltaTime);

        if(Vector3.Distance(transform.position, target.position) <= 0.2f)
        {
            GetNextWaypoint();
        }
    }

    void GetNextWaypoint()
    {
        if(waypointIndex <= 0)
        {
            Destroy(gameObject);
            return;
        }

        waypointIndex--;
        target = Waypoints.pathPoints[selectedPath][waypointIndex];
    }
}

```

Here the `Waypoints.pathPoints[selectedPath]` gets the points array of the selected path form which we then can select the next waypoint. A good improvement would be to store the `Waypoints.pathPoints[selectedPath]` array inside the enemy for easier access.

**Note** that the number `7` should not be hardcoded in your script since the number of waypoints can change. Therefore I use the waypoint arrays `Length-1` to get the last waypoint in the path array. This is also dependant on the order of your waypoints in the Gameobject hierarchy.

Regarding the `Random.Range()`: As stated in the documentation **for integers** this returns a random integer number between min \[inclusive\] and max \[exclusive\] (not so for floats). So we can use it to select an existing path from our pathPoints list.

---

In a different approach (much more changes) you could make the `Transform[] points` non-static. Then in your game manager / enemy spawner assign references to each of the waypoints in your scene. The manager can then tell the newly spawned enemy which path to take.
> 3 votes

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


# Question
Title: How to calculate normal from normal map in world space? (OpenGL)
I'm trying to do normal mapping in a deferred renderer and I'm stuck on how to implement normal maps. I have a bool that passes whether or not to use a normal mapped value and thus, whether to calculate the TBN matrix. My vertex code for the geometry pass looks as follows:

```
#version 410 core

layout (location = 0) in vec3 aPos;
layout (location = 1) in vec3 aNormal;
layout (location = 2) in vec2 aTexCoords;
layout (location = 3) in vec3 aTangent; // Optional Texture coordinates
layout (location = 4) in vec3 aBitangent; // Optional Texture coordinates

out vec3 FragPos;
out vec2 TexCoords;
out vec3 Normal;
out mat3 TBN;

uniform mat4 model;
uniform mat4 view;
uniform mat4 projection;

uniform bool hasNormalMap;

void main()
{
    vec4 worldPos = model * vec4(aPos, 1.0);
    FragPos = worldPos.xyz;
    TexCoords = aTexCoords;
    Normal = transpose(inverse(mat3(model))) * aNormal;

    if(hasNormalMap)
    {
        vec3 T = normalize(vec3(model * vec4(aTangent, 0.0)));
        vec3 N = normalize(vec3(model * vec4(aNormal, 0.0)));
        // re-orthogonalize T with respect to N
        T = normalize(T - dot(T, N) * N);
        // then retrieve perpendicular vector B with the cross product of T and N
        vec3 B = cross(N, T);
        mat3 TBN = mat3(T, B, N);
    }

    gl_Position = projection * view * worldPos;
}

```

Here is where I am confused:

In my calculation, I multiplied T and N by the model matrix which should have moved it into world space. Now transposing (T,B,N) should move me back into model space (I think, I'm not sure). In the fragment shader how do I use the TBN to calculate the normal in world space?

If there are better approaches, they are welcome. Thank you.

Update: I removed the transposing of the TBN as there's no reason to transform into tangent space if we want to pass it in world space. Now that we have the TBN matrix in the fragment shader, how do we apply it so that the normal is the correct value for lighting? Currently I've done:

```
#version 410 core

layout (location = 0) out vec3 gPosition;
layout (location = 1) out vec3 gNormal;
layout (location = 2) out vec4 gAlbedoSpec;

in vec2 TexCoords;
in vec3 FragPos;
in vec3 Normal;
in mat3 TBN;

struct Material {
    sampler2D diffuseMap;
    sampler2D specularMap;
    sampler2D normalMap;
    float shininess;
};

uniform Material material;
uniform bool hasNormalMap;

void main()
{
    // store the fragment position vector in the first gbuffer texture
    gPosition = FragPos;

    // also store the per-fragment normals into the gbuffer
    gNormal = normalize(Normal);

    if(hasNormalMap)
    {
        gNormal = texture(material.normalMap, TexCoords).rgb * TBN;
        gNormal = normalize(gNormal);
    }

    // and the diffuse per-fragment color
    gAlbedoSpec.rgb = texture(material.diffuseMap, TexCoords).rgb;

    // store specular intensity in gAlbedoSpec's alpha component
    gAlbedoSpec.a = texture(material.specularMap, TexCoords).r;
}

```

but that doesn't feel right. I imagine that I would transform the sampled value from the normal map by the TBN matrix to get it in world space. Am I missing something?

# Answer
When using a deferred rendering pipeline, your normal-mapping workflow is as follows:

Writing to GBuffer:

Vertex shader:

Compute T, B, and N vertex properties. Multiply by normal matrix. Construct the TBN matrix. Pass it to the fragment shader.

```
vec3 T = normalize(vec3(normalMat * ModelSpaceTangent));
vec3 B = normalize(vec3(normalMat * ModelSpaceBiTangent));
vec3 N = normalize(vec3(normalMat * ModelSpaceNormal));
mat3 tbn = mat3(T, B, N);
outdata.TBN = tbn;

```

Fragment shader Sample the normal map. Convert the normal map sample to something usable. Transform from texture space, to world space. Store the world space normal in the GBuffer texture

```
vec3 normal_rgb = texture(normalMap,txc).rgb;
normal_rgb = normalize(normal_rgb * 2.0 - 1.0);
normal_rgb = normalize(indata.TBN * normal_rgb);
normal_buffer_out = vec4(normal_rgb,1.0);

```

Then use it as you see fit for lighting/reflection/refraction calculations in the lighting/shading stage of your renderer.
> 1 votes

---
Tags: opengl, deferred-rendering, normal-mapping
---


# Question
Title: Close objects are only partially rendered - LWJGL
I'm working on a LWJGL project and I'm experiencing a weird problem: close objects stop being fully rendered as I move slightly away. I'm not very expert in OpenGL so I can't figure out what is causing this.

Here two photos of what I'm talking about: Pic1, Pic2

And here's a photo to prove that the objects are fully loaded: http://prntscr.com/r7joyc

Code used to load a texture

Code used to initialize the window

I think the error is somewhere here

```
@Override
    public Texture loadTexture(String filename) {
        try (MemoryStack stack = MemoryStack.stackPush()) {
            //Height, width and colour channels are 1 byte each
            IntBuffer w = stack.mallocInt(1);
            IntBuffer h = stack.mallocInt(1);
            IntBuffer channels = stack.mallocInt(1);

            //Load image into the ByteBuffer
            this.byteBuffer = stbi_load(filename, w, h, channels, 4);
            if (this.byteBuffer == null) {
                throw new FileNotFoundException("Texture file [" + filename + "] not loaded. Reason: " + stbi_failure_reason());
            }

            //Get width and height of image
            this.width = w.get();
            this.height = h.get();

            int textureID = this.generateTexture();
            this.generateMipMap();
            this.clean();
            return new Texture(textureID, this.width, this.height);
        } catch (Exception e) {
            logger.error(e.getMessage());
            e.printStackTrace();
            return null;
        }
    }

    //For scaled textures
    private void generateMipMap() {
        glGenerateMipmap(GL_TEXTURE_2D);
    }

    private int generateTexture() {
        int textureId = glGenTextures();
        // Bind the texture
        glBindTexture(GL_TEXTURE_2D, textureId);
        //Tell OpenGL how to unpack RGBA. 1 byte for pixel
        glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
         /*Args:
              1. Type of texture;
              2. Number of colour components in the texture;
              3. Colour components in texture;
              4. Texture width;
              5. Texture height;
              6. Texture border size;
              7. Format of the pixel data (RGBA);
              8. Each pixel is represented by an unsigned int;
              9. Data to load is stored in a ByteBuffer
         */
        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, this.width, this.height,
                0, GL_RGBA, GL_UNSIGNED_BYTE, this.byteBuffer);
        return textureId;
    }

    private void clean() {
        //Free ByteBuffer
        stbi_image_free(this.byteBuffer);
    }

```

Or here

public void init() {
        // Setup an error callback. The default implementation
        // will print the error message in System.err.
        GLFWErrorCallback.createPrint(System.err).set();

        // Initialize GLFW. Most GLFW functions will not work before doing this.
        if (!glfwInit()) {
            throw new IllegalStateException("Unable to initialize GLFW");
        }

        glfwDefaultWindowHints(); // optional, the current window hints are already the default
        glfwWindowHint(GLFW_VISIBLE, GL_FALSE); // the window will stay hidden after creation
        glfwWindowHint(GLFW_RESIZABLE, GL_TRUE); // the window will be resizable
        glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
        glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2);
        glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
        glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);

        boolean maximized = false;
        // If no size has been specified set it to maximized state
        if (width == 0 || height == 0) {
            // Set up a fixed width and height so window initialization does not fail
            width = 100;
            height = 100;
            glfwWindowHint(GLFW_MAXIMIZED, GLFW_TRUE);
            maximized = true;
        }

        windowHandle = glfwCreateWindow(width, height, title, NULL, NULL);
        // Create the window
        if (windowHandle == NULL) {
            throw new RuntimeException("Failed to create the GLFW window");
        }
        logger.trace("Window handle: " + windowHandle);
        // Setup resize callback
        glfwSetFramebufferSizeCallback(windowHandle, (window, width, height) -> {
            this.width = width;
            this.height = height;
            this.setResized(true);
        });

        // Setup a key callback. It will be called every time a key is pressed, repeated or released.
        glfwSetKeyCallback(windowHandle, (window, key, scancode, action, mods) -> {
            if (key == GLFW_KEY_ESCAPE && action == GLFW_RELEASE) {
                glfwSetWindowShouldClose(window, true); // We will detect this in the rendering loop
            }
        });

        if (maximized) {
            glfwMaximizeWindow(windowHandle);
        } else {
            // Get the resolution of the primary monitor
            GLFWVidMode vidmode = glfwGetVideoMode(glfwGetPrimaryMonitor());
            // Center our window
            glfwSetWindowPos(
                    windowHandle,
                    (vidmode.width() - width) / 2,
                    (vidmode.height() - height) / 2
            );
        }

        // Make the OpenGL context current
        glfwMakeContextCurrent(windowHandle);

        if (isvSync()) {
            // Enable v-sync
            glfwSwapInterval(1);
        }

        // Make the window visible
        glfwShowWindow(windowHandle);

        GL.createCapabilities();

        // Set the clear color
        setClearColor(clearColor.x, clearColor.y, clearColor.z, clearColor.w);

        glEnable(GL_DEPTH_TEST);

        // Support for transparencies
        glEnable(GL_BLEND);
        glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

        glEnable(GL_CULL_FACE);
        glCullFace(GL_BACK);

        if(debug){
            glPolygonMode( GL_FRONT_AND_BACK, GL_LINE );
        }
    }
```

# Answer
> 1 votes
This solved my problem

> First render your skybox, then clear the depth bit after rendering the skybox, and finally render everything else. That way the depth of the skybox won't affect the scene.

---
Tags: opengl, java, lwjgl
---


# Question
Title: How to select top most gameObject in a stack of gameObjects?
I'm stuck trying to figure out how I can select the top most GameObject in a stack of GameObjects. In the picture below, I have a Green and Yellow circle stacked on top of each other. If I try to select the top most gameobject (the green one), it selects the yellow circle. Is there a way that I can make sure that when I go to select a circle, it selects the top most one? I'm currently using the OnMouseDown() function built into unity.

*Update* Sorting the colors on the z axis did not solve the problem. I'm still trying to figure out a solution

# Answer
Instead of putting a script with an `OnMouseDown` method on every single game object, create **one** game object with an update-function which

1. uses `Input.GetMouseButtonDown(0)`, `Input.GetAxis("Mouse X")` and `Input.GetAxis("Mouse Y")` to read the mouse state
2. converts the mouse position on the screen into a ray from the camera positon into the scene using `Camera.ScreenPointToRay`.
3. Detects the first collider which touches that ray using `Physics.Raycast` or `Physics2D.Raycast` depending on whether your objects have 3d or 2d colliders.

This, of course, requires that the render order of your SpriteRenderers is managed by their z-position, not by render layers or orders in those render layers.

Code example (untested!)

```
void Update() {

      if (Input.GetMouseButtonDown(0)) {
            Vector3 mousePosition = new Vector3(Input.GetAxis("Mouse X"),
                                                Input.GetAxis("Mouse Y"),
                                                0.0f);
            Ray mouseRay = Camera.main.ScreenPointToRay(mousePosition);
            RaycastHit hit;
            if(Physics.Raycast(mouseRay, out hit)) {
                  GameObject clickedObject = hit.collider.gameObject;
                  // do what you want to do with clickedObject
            };
      }
}

```

One advantage of this architecture over OnMouseDown is that you decouple the input logic from the game mechanics. If you later want to add different ways to select objects, you don't need to implement that logic in the scripts which handle the game mechanics of selectable objects. You can contain these selection methods in separate scripts. The clicked object might know it is selected, but doesn't need to know how exactly it was selected.
> 2 votes

---
Tags: unity, 2d, picking
---


title: Messed up meshes

text:
# Question
Title: Messed up meshes
I had this blender model imported to unity. And then export to android studio as library.

The exported model meshes messed up in emulator while in game player everything look great. Can anyone help to find where the problem is.

Thank you.

# Answer
This looks like an artifact called "Z-Fighting" — especially if you see these patterns flicker and shimmer when the camera makes small movements.

It occurs when you don't have enough precision in your depth buffer to reliably distinguish which of two close-together polygons is in front. So, depending on which way each pixel's depth value gets rounded, you get alternating speckles/stripes/triangles of one surface poking through another.

This is usually because your camera's near plane and far plane are too far apart. The available bits in your depth buffer need to be stretched out to fill the whole gap from near to far, which means each pattern "bucket" ends up spanning a wider range of depths.

Since you seem to have a very up-close view in this part of your game, try bringing your far plane in very close — just far away enough that it doesn't clip your character. You should see the precision improve greatly and the Z-Fighting should be replaced with correctly-sorted surfaces.

Other things you can do include editing the model so there's a bigger gap between parallel surfaces, so they're less likely to get rounded to the same depth, or editing your shader/material to add a depth bias or always-on-top rendering behaviour to the overlaid item.
> 3 votes

---
Tags: unity
---


# Question
Title: How to make shadows softer as distance increases?
I'm trying to make shadows become more blurry as the distance between the caster and receiver, so they look a little more realistic.

What method can I use to achieve this?

# Answer
The method I was looking after is called "Soft Shadows with Contact Hardening".
> 1 votes

---
Tags: opengl, 3d, glsl, lwjgl, shadows
---


# Question
Title: How to detect aging signs with ARkit / AR foundation?
How Do I approach the matter of detecting skin color, wrinkles, age estimation using ARkit / AR foundation in unity ? I haven't found any tutorials online that can help on this.

# Answer
> 1 votes
# You don't, and can't.

Although ARKit/ARFoundation has face detection algorithms employed, it is only used for detecting landmarks and converting that into virtual space coordinates, of which you can scale/whatever your objects around.

ARKit/ARFoundation is a high-level API used for generating points; landmarks to map the virtual world space onto the real world.

You'll need to employ your own algorithm onto the image in order to do this.

---
Tags: unity, augmented-reality
---


# Question
Title: Procedural vs Event Driven Paradigm Clash in HTML5
I've been writing some console-based games in `python` and got in the habit of having a "mainloop" that looks something like this (if it were `JS`):

```
// mainLoop would be
function mainLoop() {
    while ( state === "playing" ) {
        if ( turn === "player" ) {
            playerTurn(table, board);
            turn = "computer";
        } else {
            computerTurn(table, board);
            turn = "player";
        }
    }
}

```

This is great as I can easily swap out `computer` for `player2` so the basic structure doesn't change much for AI vs 2-player games.

However, in `HTML5` things get really confusing. Part of me wants to hold onto the simplicity of my `mainloop` structure, but since I need the listen for events in JS, it looks like I need to completely shift paradigm.

I did actually get what I want happening using

```
document.addEventListener( "click", function ( event ) {
    if ( event.target.matches( "#reset" ) ) {
        init( );
    } else if ( event.target.matches( ".cell" ) && turn === "player" ) {
        playerTurn( event, table, board );
        if ( hasFreeSpot( board ) ) { // don't switch player if board full (or win position?)
            computerTurn( table, board );
        }
    }
}, false );

```

and updating `turn` to `player` or `computer` within `playerTurn()` and `computerTurn()`

It's hard to reproduce a working example of what I'm trying to do as the program is quite long. what I'm looking for here if possible is some big-picture advice on how to implement player vs computer games in `HTML5` where the player move comprises of clicking on some element.

Is there a basic template I can use for this kind of thing? Is the idea of a `mainloop` relevant in this context?

Is seems my current approach is a very confusing hybrid of procedural code for the computer turn and even-driven code for the player turn.

I will be happy to edit my question an include a full example if that is what you guys want here.

Thanks in advance.

# Answer
In a HTML5 game, your rendering should be enqueued with `window.requestAnimationFrame`. This ensures that your graphics updates are synchronized with those of the browser's rendering engine. You usually have a construct like this somewhere in your architecture:

```
function render() {
      // do your rendering stuff
      window.requestAnimationFrame(render);
}
window.requestAnimationFrame(render);

```

As you can see, this function enques itself recursively. So it gets executed in an infinite loop. That means when you want to work with a variable time step, then you can put your game update code right into this loop:

```
let lastUpdate = performance.now();

function mainLoop() {
      let now = performance.now();
      let deltaTime = now - lastUpdate;
      // do your game state updating stuff taking deltaTime into account
      lastUpdate = now;
      // do your rendering stuff
      window.requestAnimationFrame(mainLoop);
}
window.requestAnimationFrame(mainLoop);

```

On the other hand, if you want to work with a fixed time step, you can use `window.setInterval` to have the browser execute your main loop in regular intervals:

```
function mainLoop() {
     //update your game mechanics
}
window.setInterval(mainLoop, 100); // 100 updates per second

function render() {
    // do your rendering stuff
    window.requestAnimationFrame(render);
}
window.requestAnimationFrame(render);

```

By the way: If your game doesn't have much "rendering" per-se and only does visualization by occasionally manipulating DOM nodes, then a render-loop with window.requestAnimationFrame might not be necessary. In that case, you should just do your main game loop with window.setInterval and let the browser decide when to re-render the DOM nodes you changed during that loop. It will usually do that automatically in a timely manner. But if you update a lot of DOM nodes during every main loop iteration, then moving those DOM manipulations into requestAnimationFrame can have performance benefits.
> 1 votes

---
Tags: html5, events
---


# Question
Title: Box Collider 2Ds float just above each other in Unity
I'm learning 2D Unity and am experiencing a very strange problem. When I have 2 objects both with Box Collider 2D and a RigidBody2D, and one of them is set to be static so it doesn't move, the other one floats just above it. Here's a screenshot so it makes sense

The red box is the one that is not static, the black one is. The red one should sit atop the black one but is floating above it for some reason. I have no idea why. The hitboxes should be right, here are images of them

What can be done?

# Answer
This looks like the default contact offset:

> Colliders whose distance is less than the sum of their contactOffset values will generate contacts. The contact offset must be positive. Contact offset allows the collision detection system to predictively enforce the contact constraint even when the objects are slightly separated.

This contact offset is important, because it gives the physics system a little buffer zone to do its work efficiently.

If the offset is visible at the scale you're working at and proving distracting in play, you can slightly reduce the size of the colliders to compensate.
> 1 votes

---
Tags: unity, 2d, physics
---


title: Multiplayer Game Server Input vs Tick

text:
# Question
Title: Multiplayer Game Server Input vs Tick
I'm building a game server for a turn-based RPG game, where the players control their characters through a web interface ( think kind of like a Jackbox Party Pack game, where there's a screen that shows shared info and the players devices let them send their inputs ).

I've got most of the foundation set up: clients can connect, create a game, additional players can join the game using a code, the game server is doing real basic game loop stuff.

I'm starting to work on the actual input & tick handling. Because this is in Go, there's a goroutine that handles the input which is separate from the goroutine that handles the game updating every tick. I've basically got a for loop with multiple selects ( so that a new client doesn't prevent a server tick from getting processed ), kind of like this:

```
func (g *Game )listen(){
    ticker := time.NewTicker(time.Millisecond * 200)

    for {
        select {
        case nc := <-g.newClients:
            g.acceptNewClient(nc)

        case lc := <-g.closingClients:
            g.unregisterClient(lc)

        default:
        }

        select {
        case u := <-g.output:
            if len(g.players) > 0 {
                for c := range g.players {
                    c.out <- u
                }
            }

        case in := <-g.input:
            g.handleInput(in)

        default:
        }

        select {
        case t := <-ticker.C:
            g.tick(t)

        default:
        }
    }
}

```

What I'm trying to figure out right now is the best way to handle that player input and how it should update the game state.

For example, the first state the game starts in is character select. All players are able to select one of four character classes, but can't double up ( ie, can't have two fighters -- first come first serve ). The VIP also has the option to start the game, which will randomly assign classes to players who haven't selected, and create AI players if there are fewer than 4 players.

Should the input handler be able to directly modify the game state -- ie, when it gets a message from player 1 saying they want to select a fighter, it modifies the game state to do the right thing, or should it be throwing messages into a queue? For example saying "hey, the VIP says to start the game" or "player 2 selected fighter" and then the tick handler does the appropriate thing?

# Answer
so ... I can probably speak to your example, since I'm the primary author of the Jackbox Games multiplayer server, which as it turns out ... is written entirely in Go!

Since there's no simulation to run, there's no need for a tick since the game state does not update without user action. I do have a ticker for some other thing. You want to keep all of this in one select statement. Right now your ticker is blocking receiving input. You don't want to do that. If you want to batch all requests and then only process them at intervals, you'd still just use one big select.

The run loop that I use looks ... something like this:

```
// a Call is anything that update's the game's state.
// Calls are updated in series, so the Exec function does
// not need to be threadsafe, but the Exec function may not
// cause the room pointer to persist beyond its own invocation.
type Call interface {
    // Exec does NOT return an error. This is because an error ...
    // is expressed as a Response! If the server fails to process a
    // request, I have a response type that will render to the client
    // as an error message. Every request gets some sort of reply.
    Exec(*Room) Response
}

// a Request is a data structure from a client that has an Exec
// method that updates the game state.
type Request struct {
    // the client that sent the request
    From Conn

    // clients tag their requests with an ID; the client uses
    // this to match replies to their originating requests in
    // the client.
    ID int

    // call is polymorphic, it does the actual updating of the game state.
    Call
}

// a Response is any event that happens on the server.
type Response struct {
    // the Reply value is sent to the client that sent the
    // original request that caused this response to happen.
    Reply struct {
        Re int           // the ID of the request we're responding to
        Body interface{} // oversimplification lol
    }

    // the Notification value is sent to all of the other clients.
    // If an action doesn't notify other clients, this is nil.
    // I filter the messages before they go out but that's not shown here.
    Notification interface{}
}

// Room is the state of our game. There's a lot more here in
// the prod implementation and this is just an abbreviation.
type Room struct {
    // clients all have a reference to this channel. They send their
    // requests onto this channel.
    inbox chan Request

    // the room has a table of connected clients.
    clients map[int]Conn

    // there's a container object that contains the
    // entities in the game. It doesn't actually look
    // like this in prod :D
    entities map[string]interface{}
}

// the run loop just reads off of a channel and processes requests one at a time.
func (r *Room) run() {
    t := time.NewTicker(d)
    for pc := 0; true; pc++ {
        select {
        case req := <-r.inbox:
            res := c.Exec(r)
            for id, conn := range r.clients {
                if conn == req.From {
                    conn.send(pc, req.ID, res.Reply)
                } else {
                    conn.send(pc, 0, res.Notification)
                }
            }
        case <-t.C:
            // do something periodic here. Maybe your inbox
            // changes are actually put into a buffer and you
            // apply the buffer here if you want to simulate
            // turns. I use a periodic ticker for reporting observability
            // metrics here.
        }
    }
}

```

This is an oversimplification, but essentially what I do is:

* every client has a read goroutine and a write goroutine
* every room has just one run goroutine
* every client has a reference to the room's inbox channel (but not its state otherwise) in its read goroutine
* the clients' read goroutines read messages off of their respective websocket, parse them, and turns them into a request object
* the request object goes onto the room's inbox queue
* the room applies the requests one at a time
* the room enqueues messages with the client, and the client's write goroutine actually sends them. The `send` method in the example wraps a statement that will disconnect the client if they're not actually reading their messages.
* some surprising things like the client initially joining the room are requests. I had a separate join channel for a long time but it didn't actually do anything, it just made the code more tedious. The request has to be polymorphic anyway; updating the table of connected clients is updating the game state, it doesn't actually need a special case.

It's actually pretty simple, it just takes a few wrapper objects to make it all work. It's really just using Go's standard concurrency facilities and the command pattern to put commands in a queue. I also have things like another channel of calls that's not from users to do admin things, other tickers to do other periodic work, much more complex logic to do our audience functionality, etc, etc, etc. But this is the core of it: the i/o is highly multithreaded, but the actual game state updates are single-threaded.
> 5 votes

---
Tags: software-engineering, server
---


title: How to manage network spawning?

text:
# Question
Title: How to manage network spawning?
I'm developing an multiplayer game "from scratch" (not using a big Engine-Suite like Unity but the lower-level libgdx).

Currently I've got a NetworkManager which handles the sending of messages on server side and receiving those with subsequently calling methods on client site.

At the moment the sync between figures works already once they are correct configured and spawned on both ends. Now I'm currently think about the spawning of those objects.

---

**Approach No.1:** My first approach was that every time the Server spawned a new (e.g.) player, it will subsequently send a "SpawnObjectMessage"-Object (holding all necessary type and configuration values) to all clients. Clients will than spawn a new player-figure. Now the synchronization works.

*Concerns:*

* I have concerns with this solution that individual messages could be lost (due to network problems, for example),
* or what happens if a client closes the program in the middle of the game and then starts again and all figures have to be reloaded (as already said : The server only sends the message once as soon as it spawns a player itself).

---

**Approach No.2:** The server hold a "model" of all figures (he does this anyway due to some other functionality) and sync this with all clients. The "model" here is a list of objects each one describing values of a figure: The

* prefab/class/type the object is
* if it is spawned of or just created on server side
* is it controlled by a player and possibly the PlayerID
* ... The server will send the complete List (or only the changed entries) to all clients every time some changes occur. The clients will override their local list and subsequently iterate over it and spawn objects if they could not find a corresponding counterpart. If a new Player enters the game or a client restarts the game, the server will resend the complete list to the new client.

*Concerns:*

* This solution seems a little bit "reactive"
* It maybe not very intuitive
* Maybe I'm overseeing something what will bring problems

---

*Which approach is more common or what concerns are you aware of in such projects?*

---

**edit/additional informations:**

Since @milk asked how Updates works here is an additional explanation how this will work: The server will send continously update messages (e.g. "UpdatePositionMessage") for every Player-Objects exiting/spawned on server side. Server will keep doing so no matter if clients has successfully spawnend the corresponding counterpart object or not. Clients will simply ignore updating objects which can't be found. This update-mechanism is used in both approaches described above.

# Answer
> 1 votes
You can do something in-between.

For example, players request the *full state* when they reconnect, or if it's determined that something is wrong. During normal gameplay, you just send the relevant data. Of course, this requires that you also make sure that everyone has received the messages properly as well. Message Acknowledgement is one way to do this.

In Unity Photon for example, every networked object had it's own ID. As such, if the server sends a message and the client doesn't have an object with that ID, you know something is wrong. At that point, the client can request the full model from the master or owner.

Photon has a lot more options--I'd suggest playing around with it a little bit and implementing the functionality you feel you need.

---
Tags: architecture, networking, spawning
---


title: A two player game with a split screen

text:
# Question
Title: A two player game with a split screen
In the antique game spy vs. spy, two players play on a single computer. The screen is split, with each half showing the viewpoint of one player.

Is it possible to create such an effect in Unity? The main problem is that Camera.main is a global variable, so it is not clear how to have two cameras.

# Answer
> 2 votes
Yes, it's possible

Good answers linked above, but to bring the answer here (I didn't see a duplicate on SE):

You put a camera for each player in the scene. In your case, 2 cameras.

You then set each camera's "viewport" to your desired value: set Y to half (0~0.5 for P1, 0.5~1 for P2) for vertical, or X to half for horizontal. You can set it to a little less if you want a black border between the screens.

# Answer
> 2 votes
The viewport solution in the answer by Mars isn't bad, but I would do it a bit differently. My solution would be to use an UI canvas with two render textures:

1. Add a UI canvas to your scene.
2. Configure the main camera to render only the UI canvas by setting its culling mask to "UI" (the default layer of canvases and UI elements).
3. Add two render textures to your project (one for each player)
4. Add two additional cameras to the scene
5. Make each of these two cameras a child of the player game objects, so they follow them around (for now - in the long run, you might want to develop a more sophisticated camera controller script)
6. Set each of these cameras to render to one of these render textures.
7. Add two RawImages to the UI canvas
8. Assign the two render textures to these raw images

You can now freely design the layout of your game screen by moving the two player viewports around on your canvas and by adding other UI elements to it.

---
Tags: unity, camera
---


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

My current attempt is as follows:

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

```

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

# Answer
Thanks to anyone that took the time to answer my question, but I wanted to answer it myself for future people interested in a potential solution - I replaced each instance of `rand() % 200 + (-200)` In my question code (for the randomized `x` and `z` values of the `Vector3f` object) with the following:

```
-200 + static_cast <float> (rand()) /( static_cast <float> (RAND_MAX/(200-(-200))))

```

And now this code correctly generates floats between -200 and 200.
> 1 votes

# Answer
`rand() % 200` yields a random number between 0 & 200.

`rand() % 200 + (-200)` takes the range above and shifts; think of it as adding -200 to both the min possible outcome & the max possible outcome.

Thus, 0 to 200 becomes -200 to 0.

To get a -200 to 200, first, note the size of the range is 400 units. So you start with `rand() % 400`. Next shift it so that half the outcomes are negative: `(rand() % 400) - 200`
> 1 votes

---
Tags: c++, random
---


# Question
Title: Can I test for containment of convex polyhedra with the separating axis theorem?
I would like to refine the output of the separating axis test to not only tell me whether convex polyhedron A intersects convex polyhedron B, but also whether A is completely inside B. Is it safe to say that if A's corner points' projections (onto the separating axes) are always inside B's corner points' projections, A is inside B?

Also, is this the standard way to do combined intersection + containment tests?

# Answer
Yes:

1. If all of A's corner points are inside B, A is completely inside B
2. A point is inside a convex polyhedron iff it is on the correct side of each face
3. If any point, projected onto a face normal of B, is inside the interval formed by B's corner points projected onto the same face normal, it is on the correct side with respect to that face
4. The face normals are part of the separating axes

I don't know whether there is a more straightforward or efficient way to do it.
> 0 votes

---
Tags: collision-detection, separating-axis-theorem
---


# Question
Title: How can I design the environments in my game to be memorable and unique?
I've always been a fan of the Metroid series, and more generally nowadays, the metroidvania genre. One thing that I've loved, and most others have praised highly, are the unique and diverse environments and levels you can find in such games. Being able to tell exactly what room someone is in from a simple screenshot is a prime staple to such things.

I have been working on a 2D metroidvania game that's intended to be kind of my personal tribute to the genre, but I feel like I may have put myself in a bit of a corner conceptually. The game takes place on a barren, lifeless planet that's being harvested for resources by a sprawling autonomous mining/factory complex. Throughout the game, you travel throughout the complex, visiting each of the sites that make it up and gaining upgrades to become powerful enough to take down the AI at the center of it all (yeah, original, I know).

So, the conceptual corner... I'll be blunt. As you can probably tell from the title, and the setup in the first paragraph, I'm seriously worried that the areas in my game are going to feel too "same-y" and repetitive. I mean, and it's justified too: my selections of environments are "lifeless, rocky landscape", "lifeless, rocky caves", and "industrial metal corridors", and my selection of enemies consists of "robots", "more robots", and "different, bigger robots". I mean, it's hard to have different environments when the setting you're in has no life to support an "environment". But, I know it can be pulled off. Just look at Hero Core. It manages to pull off distinct and unique areas with much of the same restrictions I have, and with only just two colors to boot!

In closing, and yes, this is just basically an expanded restatement of the title, **what are some things I can do to make the areas in my game feel markedly distinct from eachother, despite most of them having a common overarching aesthetic?**

# Answer
A very simple method to add an unique look and feel to an area without spending a lot of development effort on asset creation is to **use a different color palette for each area of the game**.

In a 2d game, you can achieve that effect by doing a palette swap of your graphic assets. Just slightly change the colors in your preferred image editor. Or if you want to keep the asset size small, see if your game engine can do that for you at runtime.

In a 3d game, this is easily achieved by using different light colors or a different color-grading post-processing effect for each area.

Don't be afraid of being brave in your color selection. Caves don't need to be brown and metal corridors don't need to be grey. The classic Super Metroid on the SNES is actually a great example of this. If you compare screenshots from different areas of the game, then you can see that many use the same tiles but with different color palettes. They were very bold in their color selection. The effect of the unusual colors makes the caves of the alien world of Ceres look, well, alien. But you also see a couple tiles which are unique to specific areas. This can also be used to give individual areas an individual aesthetic.

In addition to changing the visual aesthetic of each area, you can also try to aim for different **aesthetics of play** for each area. Try to have each area focus on a particular challenge of your game. Some examples of gameplay themes you could give to an area are:

* Precise jumps
* Well-timed jumps
* Well-timed running
* Lots of weak enemies
* Few but powerful enemies
* Enemies encountered at close range
* Enemies encountered at long range
* Enemies which surprise the player by appearing when the player wouldn't expect it
* Moving hazards
* Traps
* Predominantly vertical traversal
* Predominantly horizontal traversal
* Lots of secret passages
* Lots of puzzles, preferably of the same general theme
* Focus on one specific special ability of the player (very useful if the player just obtained that ability)
* ...and more...

I am looking forward to playing through all the different areas of your game.
> 42 votes

# Answer
Aside from Philipp's suggestions, you can also push your environments in different conceptual directions, and maybe imply a bit of history too.

Lifeless, Rocky Landscape/Caves: Dusty rocks can make one area, sure, but you can also have crystal caves, areas with lots of geysers and islands floating precariously on alkaline lakes, areas that have already been strip-mined, places that are currently experiencing powerful storms.

Robots, Metal Corridors: If the AI has been here for a while, there can be a whole history to the AI's continual development and refinement of its minions. Broken-down robots and corridors in the areas where it originally landed, sleek new robots and corridors in some of the newer parts, and robots that incorporate crystals into their designs after the AI started getting corrupted by the planet (or whatever).
> 21 votes

# Answer
> The game takes place on a barren, lifeless planet that's being harvested for resources by a sprawling autonomous mining/factory complex.

**Every building has a background and a history that should be reflected in the design of your environment.** Think about castles in video games. Good castles don't look like a generic video game castle and stick in players' memory. The same goes for every classic environment: town, forest,...

For example,

* your factory has a main mining area for resources
* resources need to be refined and/or transformed
* there should be a maintenance area to repair the robots
* a place where robots that can't be repaired are destroyed (imagine a long conveyor belt where drop hammers regularly crush defective robots)
* transportation area where resources are sent out of the factory
* maybe a refrigerated area, or furnaces

Also, **events that happened in the complex can change the aspect of an area.** For example, most of Metal Gear 2 happens on an oil platform that consists of two hexagonal parts, each made of 6 rooms. Pretty boring premise. But, since each room has a different purpose (arsenal, storage, computer room, lounge, entrance,...) in the platform, and events occur in there (one is flooded, one has hostages,...), it gives new challenges and experiences to the player. In your factory,

* an area could be flooded
* robots in one area could have gone rogue
* your character infiltrating the complex will not go unnoticed for long. After some time, more security robots (think emergency task force) will be activated and put your player under a new threat.
* the factory is under alert! Some doors are locked, forcing the player to explore the same areas under different conditions.

To sum up, you can flesh out the history of your environment to give it more depth.
> 16 votes

# Answer
Foxwarrior had a good idea about history of the place. Unfortunately they didn't go where I thought they would with it.

One thing that people like are "quirks" that come up unexpectedly, in a good way. Not enemies, but mysterious (and sometimes completely unexplained in game) ruins, artwork, geological formations, and things that seem out of place, but not necessarily out of character for the game.

It could be an easter egg in the form of an Easter Island stone head in the middle of your barren desert. Why is it there? Maybe there's a plaque to be found buried in the sand at the foot of it that explains it, maybe not. Maybe there's rock band style posters all over one hallway of your base. Why? IDK, but all of them are fake, except the Motley Crue poster that's a side quest to find. Maybe there's a mirror that never shows the player, even though it shows what's behind them and any weapons they carry.

Or it could be something completely normal, but extremely out of place, which is explained later to be completely normal. Maybe a baby stroller with a skeleton in it in an abandoned and contaminated nuclear facility happens to be left there by a family that was taking a tour right before the accident and they had to leave it behind, but everyone made it out safe, and the skeleton turns out to be a raccoon. The player can find a body found half embedded in a trash compactor, which turns out to be a mannequin.

You can even turn one of these things in to a major quest. The player has to figure out the code on the plaque next to the Easter Island statue, press a hidden button the code explains, and the statue opens it's mouth to reveal a door, a required gem, a "god weapon", or something silly like a pool noodle.

Maybe you make a geological formation look like a famous building or skyline. In the hazy/foggy distance, it looks like the Seattle Space Needle, but up close it's just a weird rock spire that simply looks nothing like it except for the 2D outline. Sort of like those shadow sculptures that don't look anything like the silhouette shadow they leave on a wall from a specific angle.

It's the attention to detail that often comes out to make a game memorable. Having a great cause, a great story, great game play, awesome weapons, and an amazing character all run towards a memorable game, but take a lot of time, which is why big corps are usually behind those games. But you can get into the "cult classic" category simply by having a great set of quirks.
> 2 votes

# Answer
A textured background might do it. Think desert, ocean, and forest backgrounds from Afterburner. Of course, you're not dealing with deserts or oceans, but you should be able to design unique backgrounds for each level. And because of the repeated nature of background images, it shouldn't take an unreasonable amount of work.
> 1 votes

# Answer
Some variations to distinguish different areas (some of these have been listed in other answers):

* Clear skies / Dust storm / Night time / Strong winds
* Underground / High up on some cliffs or crags / plains
* Natural Rock formations / Abandoned tech buildings / The inside of a fallen spaceship or large robot
* Horizontally laid out / vertical (like Phillip said)
* Wide open spaces / Tight corridors
* A level on a moving object (think of how old school beat-em-ups always have a level on a moving train or elevator or something)
* If the player controls a person most of the time, have a level where they temporarily control a tank/mech/other person.
* a dark level where you need to turn on lights (or use a flashlight)
* since water would be habitable, maybe tar or some other liquids could mark an area?
> 1 votes

---
Tags: game-design, level-design
---


# Question
Title: Access helper script already attached to current gameObject
I currently have an object in my scene that needs to do many things (move, sleep, reproduce, etc..). I thought it would be good practice to refactor my code and extract each type of action my agent can do into its own scripts which I could then call in a main script. I have done this for movement code and it works when there is just one Agent in the scene however, when creating multiple agent objects in my scene and pressing play I've been getting undesired behavior, only one agent moves while all the other idle. I was wondering if there was a way to access an instance of a script already attached to a gameObject, instead of using Component.FindObjectOfType\<\>();

Here's the movement script

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

//This class contains methods for moving an agent throughout the space, and searching for food when hungry.
//Every method in this class is made public as it will be used in the Agent.cs file.
public class MoveAgent : MonoBehaviour
{
    [SerializeField] public gridScript gs;
    public Vector2 pos;
    public float searchRadius;
    public DayNightCycle dy;
    private GameObject foodTarget = null;
    private bool inRotation = false;
    public float rotateSpeed = 5f;
    private Quaternion direction;

   List<GameObject> nearbyFood = new List<GameObject>();
   Vector2 prevPos;

    public void getStartPos(){
        pos = new Vector2(Random.Range(0,gs.grid.GetLength(1)),Random.Range(0,gs.grid.GetLength(0)));
         this.transform.position = gs.getGridPosition(pos);
        gs.occupySpace(pos);
        rotateSpeed *= Random.Range(0.5f,1f);
        getNewPos();
    }

    public void getNewPos(){
        float f = Random.Range(0.0f,1.0f);
        int newX = 0,newY = 0;
        if(f < 0.25){
            newX =  1;
            direction = Quaternion.AngleAxis(-90,Vector3.up);
            }else if(f <= 0.5 && f >= 0.25){
            newX = -1;
            direction = Quaternion.AngleAxis(90,Vector3.up);
        } else if(f <= 0.75 && f >= 0.5){
            newY =  1;
            direction = Quaternion.AngleAxis(180,Vector3.up);
        }else if(f <= 1 && f >= 0.75){
            newY = - 1;
            direction = Quaternion.AngleAxis(0,Vector3.up);
        }
        prevPos = pos;
        pos.x += (float)newX;
        pos.y += (float)newY;
    }

    public bool rotating(){
        this.transform.rotation = Quaternion.Lerp (transform.rotation, direction, Time.deltaTime * rotateSpeed);
        //Currently getting odd behaviour due to floating point values, so just set the new rotation direction explicitly if the distance between them is minimal
        if(Quaternion.Angle(transform.rotation,direction) < 0.00000001)this.transform.rotation = direction;
        if(transform.rotation.eulerAngles == direction.eulerAngles){
            return true;
        }
        return false;
    }

    public void moveToNextPos(){
        gs.leaveSpace(prevPos);
      if(!gs.isOccupied(pos)){
            gs.occupySpace(pos);
            this.transform.position = gs.getGridPosition(pos);
      }
    }

    //if theres food nearby then search for it
    public void searchForFood(){
        int x=0,y=0;
        //constantly selecting a new foodTarget leads to undesired behaviours,
        //so only find a target if the current foodTarget gameObject is null
        if(foodTarget == null ){
            GameObject[] food = nearbyFood.ToArray();
            GameObject foodToFind = new GameObject();
            foodToFind.transform.position = new Vector3(-999,-999,-999);
            if(food.Length > 0){
                for(int i = 0; i < food.Length; i++){
                    if(Vector3.Distance(this.transform.position,food[i].transform.position) < Vector3.Distance(this.transform.position,foodToFind.transform.position)){
                        foodToFind = food[i];
                    }
                    foodTarget = foodToFind;
                }
            }
            Destroy(foodToFind);
        }

        if(this.transform.position.x > foodTarget.transform.position.x){
            x = -1;
            direction = Quaternion.AngleAxis(90,Vector3.up);

        }else if(this.transform.position.x < foodTarget.transform.position.x){
            x = 1;
            direction = Quaternion.AngleAxis(-90,Vector3.up);
        }else if(this.transform.position.z > foodTarget.transform.position.z && this.transform.position.x == foodTarget.transform.position.x){
            y = -1;
            direction = Quaternion.AngleAxis(0,Vector3.up);
        }else if(this.transform.position.z < foodTarget.transform.position.z && this.transform.position.x == foodTarget.transform.position.x){
            y = 1;
            direction = Quaternion.AngleAxis(180,Vector3.up);
        }

        //leaving this here because its useful for debugging
        //foodTarget.GetComponent<Renderer>().material.color = Color.white;
        prevPos = pos;
        pos.x += (float)x;
        pos.y += (float)y;
    }

    //Check the map for all food sources, create a list of all food nearby to an agent
    //if the list is empty then theres no food nearby, so just random walk
    public bool checkArea(){
        nearbyFood = new List<GameObject>();
        GameObject[] food =  GameObject.FindGameObjectsWithTag("Food");
        for(int i = 0; i < food.Length; i++){
            if(Vector3.Distance(transform.position, food[i].transform.position) < this.searchRadius){
                nearbyFood.Add(food[i].gameObject);
            }
        }
        return nearbyFood.Count != 0;
    }

    bool V3Equal(Vector3 a, Vector3 b){
        return Vector3.SqrMagnitude(a - b) < 9.99999944E-11f;
    }
    void OnDrawGizmos(){
        if(Application.isPlaying){
            Gizmos.color = Color.white;
            Gizmos.DrawWireSphere(this.transform.position, searchRadius);
            GameObject[] food = GameObject.FindGameObjectsWithTag("Food");
            Gizmos.DrawLine(this.transform.position,foodTarget.transform.position);
            // for(int i = 0; i < food.Length; i++){
            //     if(Vector3.Distance(this.transform.position,food[i].transform.position) < this.searchRadius)Gizmos.DrawLine(this.transform.position,food[i].transform.position);
            // }
        }
    }

}

```

And here's my scripts that accesses those methods:

```
public class Agent : MonoBehaviour
{
    [SerializeField, Range(350,500)]  int energy;
    [SerializeField]private int timeTillNextMove;
    private int counter;
    MoveAgent moveAgent;
    private bool isMoving;

    void Awake(){
        moveAgent = Component.FindObjectOfType<MoveAgent>();
        timeTillNextMove = (int)Random.Range(0,100);
        GetComponent<Renderer>().material.color = Random.ColorHSV(0f, 1f, 1f, 1f, 0.5f, 1f);
        isMoving = true;
    }
    void Start(){
        timeTillNextMove += (int)Random.Range(0,35);
        counter = timeTillNextMove;
        moveAgent.getStartPos();
    }

    void Update(){
        counter--;
        if(counter <= 0){
           move();
        }
        if(energy == 0){
                Component.FindObjectOfType<gridScript>().leaveSpace(moveAgent.pos);
                DestroyAgentInstance();
        }
    }
        void move(){
         if(energy < 500 && moveAgent.checkArea()){
                if(moveAgent.rotating() == true){
                    moveAgent.moveToNextPos();
                    counter = timeTillNextMove;
                    energy -= 5;
                    isMoving = false;
                    if(energy < 500 && moveAgent.checkArea() == true)  moveAgent.searchForFood(); else moveAgent.getNewPos();
                }
            }else{
                 if(moveAgent.rotating() == true){
                    moveAgent.moveToNextPos();
                    counter = timeTillNextMove;
                    energy -= 5;
                    isMoving = false;
                    moveAgent.getNewPos();
                 }
            }
        }

    public void DestroyAgentInstance(){
        Destroy(gameObject);
    }
        void OnTriggerEnter(Collider target){
            if(target.gameObject.tag.Equals("Food") == true ){
                    Destroy(target.gameObject);
                    this.energy+=50;
                }
            }
    }

```

Is there a way to somehow only search the gameobject `Agent.cs` is attached to for `moveAgent.cs`

# Answer
> 1 votes
I'm an idiot! You can just use `this.getComponent<Name_of_Script>();`

# Answer
> 1 votes
Component.FindObjectOfType\<\> is a heavy function and you should avoid using it (https://stackoverflow.com/questions/30310847/gameobject-findobjectoftype-vs-getcomponent). FindObjectOfType\<\> returns the first loaded component it can get of specified type. https://docs.unity3d.com/ScriptReference/Object.FindObjectOfType.html

what you want to use is from the level of agent component invoke `gameObject.getComponent<>`https://docs.unity3d.com/ScriptReference/Component-gameObject.html

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