title: Raycast Masks not working Unity3D

text:
# Question
Title: Raycast Masks not working Unity3D
I'm having a problem with filters/masks when raycasting.

I've created a LayerMask and then in the inspector selected the layer I want to ignore when Raycasting. however then I print out the name of the object hit by the raycast I am still getting hits on objects on the layer masked out, as well as on other layers.

```
public LayerMask rayMask;

RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast (ray, out hit,rayMask)){
    Debug.Log (hit.collider.name);
}

```

I have paused the Game and checked that the object I'm getting a hit on is indeed on the layer in the mask.

# Answer
Sorry folks. First Post here on Stack Exchange. Thought maybe after a while I could just mark one of your comments as an answer guess not.

So my solution was:

Physics.Raycast () needs 4 veriables in order to use a Layermask. So i had to add a distance to the ray. i.e.

```
Physics.Raycast (ray, out hit,mathf.infinity,rayMask)

```

that got the layermask working Although it was the Inverse of what i thought, the ray hit only what was on the mask. So i added

```
rayMask = ~rayMask;

```

to invert the Layermask.
> 1 votes

---
Tags: unity, raycasting
---


title: render/draw or input first?

text:
# Question
Title: render/draw or input first?
When creating the main game loop, what order should things generally happen? That is, should I be getting input, doing logic and then rendering, or something else? does this even matter? when I was coding with Python and Pygame the tutorial I was using pointed me towards the aforementioned method. however, this tutorial for LWJGL2 does it like this:

```
while (!Display.isCloseRequested()) {
// While no attempt to close the display is made..
// Put render code here.
// Put input handling code here.
Display.update();
// Refresh the display and poll input.
Display.sync(60);
// Wait until 16.67 milliseconds have passed. (Maintain 60 frames-per-second)

```

and (so far) doesn't seem to have hinted at logic (though I assume it will later on, and looks like it might put it last).

So which should I be using? Does it matter at all? I'm using LWJGL2.

# Answer
> 6 votes
When writing your main loop and updating logic, you've got two basic strategies, which you're probably aware of: fixed time steps and dynamic time steps. Either way your updates will happen at some time.

There are basically two ways to write this - both which you identified already:

Version 1:

```
while (running) {
    update();
    draw();
}

```

Version 2:

```
while (running) {
    draw();
    update();
}

```

Note that `update()` can act as a real black box here. It doesn't matter how the updates happen, i.e. whether there's some fixed time step or not.

Now let's unwind 3 iterations of that main loop and you'll get...

Version 1:

```
// iteration 1
update();
draw();
// iteration 2
update();
draw();
// iteration 3
update();
draw();

```

Version 2:

```
// iteration 1
draw();
update();
// iteration 2
draw();
update();
// iteration 3
draw();
update();

```

Skip the comments and you'll notice that both implementations are essentially the same.

However, there are two tiny tidbits to mention:

* When you run the main loop for the **first time**, if there's no `update()` call before the first `draw()`, you might end up with **one drawn frame** you don't want to be there or with some **undefined behavior** (depends on your overall design).
* If you're using **vertical synchronization** (or it's forced), it will typically happen at the end of `draw()`, when the current scene/back buffer is presented. This means that if you're drawing first, your input will always **lag behind by one (display) frame**. Depending on your frame rate this might be very noticeable to the user.

Due to this (and probably due to simple logic, i.e. you have to setup what you want to draw first), I think pretty much any game will usually update first, draw second.

# Answer
> 3 votes
The typical implementation is Update first, then Render. I guess this is because it reduces input latency. In Update-First you see changes on the current frame (U - update, R - render, F - frame, \[wait\] - wait for V-Sync):

`U1->R1->[wait]->F1 => U2->R2->[wait]->F2`

In Update-Last you see changes on the next frame (F1 is two \[wait\] later of U1):

`R0->U1->[wait]->F0 => R1->U2->[wait]->F1`

Also update-first gives you a chance to drop render in case it took more time than expected, so you could catch-up. I don't really see any possible benefits in render-first approach.

# Answer
> 1 votes
One call to Render() usually equates to many calls to Update() and Render() is usually called about 60 times per second.

That usually equates to:

```
void Frame(float elapsedTime)
{
    static float accumulatedElapsedTime = 0;
    accumulatedElapsedTime += elapsedTime;
    while (accumulatedElapsedTime >= fixedTimeStep)
    {
        Update(fixedTimeStep);
        accumulatedElapsedTime -= fixedTimeStep;
    }
    Render();
}

```

This also implies a distinct separation between render-code and state-code.

Update() should, ideally, only modify data in buffers. Render() uploads that data (preferably only changed data) and tells the GPU how to use it.

---
Tags: lwjgl, game-loop, pygame
---


# Question
Title: unable to use two gestures simultaneously
I have a class implementing gesture listener in libgdx. I want to use longpress gesture in one half of the screen and fling gesture in other part of the screen simultaneously.

public class FlingHandler implements GestureDetector.GestureListener{

```
GameWorld world;
Bmw bmw;
private float  w,h,xunit, yunit;
private float spd = 1;
private float xtouch = 0, ytouch = 0;
private float xVel = 0, yVel = 0;
private int p = 0;

public FlingHandler(GameWorld world) {
    this.world = world;
    w = SS.WIDTH;
    h = SS.HEIGHT;
    xunit = SS.x;
    yunit = SS.y;
    bmw = world.getBmw();

}
public void update(float delta){
    updateLongpress(delta);
}

public void updateLongpress(float delta){

    if(longPress(xtouch,ytouch)==true && world.getBmw().isDead()==false) {
        if(spd <1600 && Gdx.input.isTouched()){
            spd += 0.9f*delta;
            Gdx.app.log("speed ","increasing"+spd);
        }
    }

    else if(longPress(xtouch,ytouch)==false && world.getBmw().isDead()==false){

            if(spd > 1 ){
                spd -= 8f*delta;
                Gdx.app.log("speed ","decreasing"+spd);
            }
    }
    else{

    }
}

@Override
public boolean fling(float velocityX, float velocityY, int button) {
    xVel = velocityX;
    yVel = velocityY;
    xtouch=Gdx.input.getX();
    ytouch=Gdx.input.getY();
    p = button;

    if(xtouch > SS.WIDTH/2 && world.getBmw().isDead()==false) {
        if (Math.abs(xVel) > Math.abs(yVel)) {
            if (xVel > 0) {
                if (world.getBmw().getPosition().x < 8 * xunit) {
                    world.getBmw().getPosition().x += 4 * xunit;
                }
            } else if (xVel < 0) {

                if (world.getBmw().getPosition().x > 7 * xunit) {
                    world.getBmw().getPosition().x -= 4 * xunit;
                }

            } else {}

        }
        return true;
    }
    else
    return false;
}

@Override
public boolean longPress(float x, float y) {
    xtouch = Gdx.input.getX();
    ytouch = Gdx.input.getY();

    if(xtouch < SS.WIDTH/2 && world.getBmw().isDead()==false){
        return true;
    }
    else if (xtouch > SS.WIDTH/2){
        return false;
    }
    else
    return false;
}

```

# Answer
The `GestureListener` is something that should be passed to a detector, and the detector (which is an `InputListener`) will read touch events and amalgamate them into higher order events such as pan, fling or long press.

So I would expect your code to have something like this somewhere; `Gdx.input.setInputProcessor(new GestureDetector(new FlingHandler()));`

Since the `GestureDetector` is the one capturing the events and forwarding them to your `FlingHandler` it doesn't really make any sense to do things like this;

```
if(longPress(xtouch,ytouch)==true && world.getBmw().isDead()==false) {
  if(spd <1600 && Gdx.input.isTouched()){
    spd += 0.9f*delta;
    Gdx.app.log("speed ","increasing"+spd);
  }
}

```

You don't call longPress, the `GestureDetector` does that for you when a long press has been detected, you override the method to take action when it has happened. Also, galling `Gdx.input.isTouched()` is also weird, as you expect complete gestures to be delivered to your gesture listener.

As for detecting the gestures simultaneous; that might be a bit difficult with the `GestureDetector`/`GestureListener` as they will report events based on individual touches for *down*, *tap*, *fling* and *pan stop*, but not for *long press*. Because of this you'll probably have to hook in at GestureDetector level rather than `GestureListener` (or possibly a combination of both).
> 2 votes

---
Tags: android, libgdx, multitouch
---


# Question
Title: Relationship between Camera's view size, screen resolution and objects scale
I've had this question since a long time ago and wanted to know the relationship between how an object is viewed through the camera depending on the resolution of the device, the camera's view size and the object scale, so for example:

let's say i have a 100x100 square in the middle of the screen, the camera is looking directly at it and let's say the square takes 10% of a specific screen, if i wanted it to keep that relationship with the screen do i have to change the square size depending on the screen size?, change the camera's width and height? or change the resolution of the game?

in short, how does the resolution and the camera's widht and height affect the scale and proportions of the objects of the screen?

# Answer
> 0 votes
The World/Model matrix moves objects from object-space to world-space.
World coordinates have no software-defined min/max values.

The View matrix re-centers the scene on the camera.
It is the anti-world-matrix for the entire scene. Since the camera's View-space location is (0,0), objects are either left/right or down/up, corresponding to -/+ coordinate values but the coordinates are not scaled or normalized.

The Projection matrix defines the viewable frustum.
After projection, the center of the rendertarget becomes (0,0) and coordinate X and Y values are scaled into the range of -1 to +1 (Z is represented differently by different systems).
+1 corresponds to the right and top edges, regardless of texture dimension.
-1 corresponds to the left and bottom edges, regardless of texture dimension.
This is how you define "how much" 3D space to extract and compress into the same set of screen coordinates and where resolution, FOV, and aspect ratio come into play.

http://http.developer.nvidia.com/CgTutorial/cg\_tutorial\_chapter04.html
4.1.9 addresses your specific questions regarding devices.

---
Tags: camera, resolution, screen, viewport, scale
---


# Question
Title: 2D physics on game object made up of components
Say you want to let your users create a 2D airship (side view) made up of components. One component could be a floating balloon, another could be a storage room, etc.

And say you want this airship to have physics applied to it as a whole, with each component playing a part in this. For example, balloons would take away from its down force and other compartments would apply down force to it.

At the same time, the whole airship works as a whole (or at least the only physical separation would be between floater components and the others, which apply weight), so physics are applied to it as if it was one body.

Now, how can this be managed? How can I customize a game object via a script, giving it different components with different weights, and have it behave like it was a single premade object?

I'm sorry if the question is simple, but I'm only getting started with unity. Thank you very much!

**TL;DR:** Customizable airship gameobject with different components that have different weights. How to make it behave as a single physics entity and manage its different components?

# Answer
One approach to handling the composite objects (collections of components that will move as a single object) would be:

**Create a script to store the weight of a component.**

```
    public class AirShipComponent : MonoBehaviour {
        private float weight;
    }

```

**Create a script to total the weights of any child objects and apply the total to a Rigidbody.**

```
    public class AirShipComposite : MonoBehaviour {

        public new RigidBody2D rigidbody2d;

        public void Awake() {
            rigidbody2d = GetComponent<Rigidbody2D>();
        }

        public void UpdateTotalWeight(){
            float totalWeight = 0f;
            var childComponents = GetComponentsInChildren<AirShipComponent>();
            foreach (AirShipComponent airShipComponent in childComponents) {
                totalWeight += airShipComponent .weight;
            }
            rigidbody2d.mass = totalWeight;
        }
    }

```

**Object hierarchy**

Then place your `GameObjects` holding `AirShipComponent` as children of the `GameObject` with `AirShipComposite` and call `UpdateTotalWeight()`. You can then call `UpdateTotalWeight()` whenever the total should be updated.
> 1 votes

# Answer
i think one answer is in Distance Joint 2D : "The Distance Joint 2D component allows two Sprite objects controlled by rigidbody physics to be attached together to keep them a certain distance apart." Or Fixed Joint in unity 3d
> 1 votes

---
Tags: unity
---


# Question
Title: Is it better to make a cpp and hpp file for every new object or is it better to make one parent class and define types in there?
Let's say we make a game. The game has items, enemies, allies, etc and there are multiple of them, like zombies and robots as enemies. Do you think it would be better to make one parent class called "Enemy" (and the corresponding cpp/hpp files) and making a class for each enemy (zombie or robot in this example) and making 2 files per enemy or would it be better to make an `enum`called "type" in the Enemy class and having all child objects in that one class?

Thank you for your help!

# Answer
On this matter, you really have to think a couple of steps further.

* What differentiate an enemy Zombie from an enemy Robot?
* What is common to both of them?
* Can a Zombie be not an enemy but a friend?
    + If so, what would be common to an enemy Zombie and a friendly Zombie?
    + What would be different from an enemy Zombie and a friendly Zombie?
* Can a Robot be a friend?

If you use an enum, how will you describe the other differences between a Robot and a Zombie? Will you have a variable to hold a reference to the graphics representation and another to hold a reference to the behaviour? If so, do you really need an enum and hard code all your enemies?

If you use a parent class and inheritance, what is so common to them now that there is the need for a parent class? And if you use that, and you turn out needing a friend Zombie, how will you hack your way to avoid code duplication *and* have your zombie act as a friend *and* as a zombie? And if you decide to have a *hoover* enemy Zombie, will it inherit from Enemy \<- Zombie? If so, how many inheritance levels are you ready to have before you consider you're really entangled in your architecture?

---

Your question shows lack of experience. Which is not a bad thing, because we've all been there and you're taking steps to improve your situation by asking around and trying stuff. Kudos on that!

**My answer to your question is this:**

When programming, there is rarely a single best way to do something. It always depends on the situation, on the requirements and and the implementation.

Plan a bit more what you want from your game, with all the edge cases, then try to implement it with what you're most comfortable at first. Then take a look at what went wrong with the way you chose, and figure out a way to improve it for your next game.

And after you're done with your first implementation, you should take a look at the concepts of *entity-component* design. Maybe you don't need all of what's in there, but it could help you figure out ways to design your next game!
> 1 votes

---
Tags: c++, oop
---


# Question
Title: Why I need a backend for a mobile social game?
I'm developing a mobile social game, it's a puzzle with a social layer similar to the one in Candy Crush Saga (limited lives, can send life requests to friends, facebook leaderboards, etc). I know all top mobile social games have a backend, but I don't understand what's the purpose of it, is it only to persist game data? Assuming I'm not interested in persist game data online, do I need a backend server?

My idea was to handle all players' interactions through facebook (life request, leaderboards, etc). Is this possible without my own backend?

Any information on what are the benefits of having a backend for a mobile game is welcome.

# Answer
> 5 votes
There are several reasons why to use a backend. Without backend, you can't really have states in your game. That means players start all over when they refresh the web page. The facebook API stuff that you mentioned also comes from backend. You can do lots with facebook API, but it's not even pretending to cover all the cases. Facebook recommends Parse.com for your backend needs.

Backend is used:

* To not give all the code to your users
* To run some game logic at backend, so cheating is harder
* In App purchase item ownership data that should be kept out of players' reach
* To port the game to multiple devices. Logic running at backend makes it easier
* To fine tune game without shipping new client all the time
* To collect data about user behaviour
* To store player progression

This is just what comes from top of my head, I'm sure there are more reasons. It depends on your game if it really needs backend, but most likely it does. There are multiple web services that offer backend as a service (BAAS) if you lack the knowledge or will to make your own.

# Answer
> 1 votes
You should see the back-end as a centralized component for storage and processing. This structural component is used for various reasons.

* Storage: the state of your game will be stored on the back-end. "State" refers to all parameters that need to be stored persistently. For example, you need to store the level progression of the player. You have two options here: either you store the state on the user's device, or on a centralized back-end. The back-end offers various advantages. First, the user will be able to resume the game from any device (eg. he could start playing on his computer and switch to mobile device the next day). Second, other players can see the player's score. This is a requirement for leaderboards ... etc.
* Communication: your game might require a form of inter-player communication. You mentioned messages to friends. Sending lives to other players, playing with or against them, ... are also often available in games. When it comes to messaging, the devices of you and your friend don't communicate directly. Instead, your message is sent to the server, so that your friend can receive it once he is online. This means that you don't both need to be online in order to be able to communicate. Furthermore, by passing messages via the server you could apply filtering for spam ... etc.
* Security: code that is stored on a back-end server is "safer" from hacking than an all-client application. The back-end serves as a black box. This means, your game client sends messages to the back-end, and the back-end sends a reply. How the request is actually processed in the back-end is not visible from the outside world. This could be useful if you, for example, want to give players a limited amount of lives per hour. Using app purchases to give them more lives. By storing the number of lives left on the back-end server, hackers can not simple spawn in extra lives by tinkering with the save file on their device. An option for hackers would be to write a server emulator, but this is far more complex than client-side hacking.

There are numerous other advantages, but overall using a back-end component in mobile game architectures has proven to be advantageous (if not essential). Not that you referred to using Facebook instead of a custom back-end. Technically, facebook would be your back-end component in this case, aka. a centralized platform for storage and processing. A custom back-end is prefered as you can incorporate all funcitonality your app requires. The facebook API is a more general purpose back-end, not tailored to fit your application.

To summarize, a back-end component has so many benefits, that it is almost impossible to avoid using one in mobile games. While using the facebook API is possible for general-purpose operations, a custom back-end is recommended to tailor it to fit the needs of your application.

# Answer
> 1 votes
I recommend you look as some of the many BaaS available for mobile game developers. Some are free for non-commercial use or pre-launch development. Here's a few (there are many more):

* brainCloud
* Gamedonia
* GameSparks
* Gamua Flox
* PlayFab

# Answer
> 0 votes
Most use an established back-end to abstract over the boring stuff and the long term overhead of building and running your own back-end stack. Pass it off to someone else, pay them a few cents a day, so you can focus on monetizing your game instead of busywork (OS patching, capacity planning, etc.).

I don't understand why anyone would consider building their own back-end when so many good and affordable mBaaS solutions exist. We have been using such a service at our company for about 3 years; it removed lots hassle pretty much overnight. All our techs are now focused on good stuff rather than up to their armpits in DevOps.

---
Tags: server, mobile, facebook, social
---


title: Orthographic viewport zooming

text:
# Question
Title: Orthographic viewport zooming
I'm a bit new in opengl so please bear with me. I have a viewport window like this

I have implemented zoom in/out features using the arrow keys. The problem is it zooms in and out with the whole image. Can anyone point me in the right direction as to how I can make the GUI on the sides stay in place while making my viewport (the white rectangle) zoom in and out?

Thank you!

# Answer
You need to use separate projection matrices for the viewport and GUI.

E.g:

```
SetupViewportProjection();
DrawViewport();
SetupGUIProjection();
DrawGUI();

```
> 2 votes

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


title: MMORPG design for time-limited players

text:
# Question
Title: MMORPG design for time-limited players
I believe that there is a significant market of players who would enjoy the exploration and interaction aspects of MMORPGs, but simply don't have the time for the endless grinding marathons which are part of the average MMORPG.

MMORPGs are all about interaction between players. But when different players have different amounts of time to invest into a game, those with less time to spend will soon lack behind their power-leveling friends and won't be able to interact with them anymore.

One way to solve this would be to limit the progress a player can achieve per day, so that it simply doesn't make sense to play more than one or two hours a day. But even the busiest casual players sometimes like to spend a whole sunday afternoon playing a video game. Just stopping them after two hours would be really frustrating. It also creates a pressure to use the daily progress limit every day, because otherwise the player would feel like wasting something. This pressure would be detrimental for casual gamers.

What else could be done to level the playing field between those players who play 40+ hours a week and those who can't play more than 10?

**Edit:** Thanks for all of your answers. They all were very inspiring and gave me some interesting ideas. I decided that the first thing I will do will be a rest mechanic, so I accepted the answer by Orin MacGregor. But I upvoted a lot of other answers, too. When you are interested in my first draft for the rest mechanic, you can read about it on my development blog: http://ontraindevelopment.blogspot.com/2012/10/rest-system.html

# Answer
Any sort of resource generated while logged out. WoW and similar games have rested experience that helps those with less time to catch up. There could be other things generated that would help others to catch up, such as a rested currency used to buy items that can buff the player, but they must be implemented carefully to not be abused by those who don't really need it.

A more complex implementation could be temporary level boosts. If a player wants to play with a friend 10 levels ahead of them they could be boosted ~10 levels. This would require a balance of implementation, like do they temporarily get the skills associated with the skipped levels? (Later generations of Pokemon have this where stats scale up but they don't get any new skills, but that's not truly an MMORPG.) Should stats on items scale linearly? Should they earn experience toward their base level, and if so should it be scaled down to their base level? Can they earn money and items?

Expanding on your mention of limiting progress per day (which Final Fantasy 14 initially did with terrible results) is to implement it like the rested experience system. Still limit people to a reasonable amount per day, and have the leftover be rolled over into the next day (eventually capping out to curb some abuse). So while a player with time every day can get 1 million experience per day, his friend that can only play on the weekend can get 5 million on Friday (assuming resting started at monday and they don't play until friday). They don't use all 5 mil, say only 3 mil, then the rest carries over into Saturday so they can get the daily 1 million plus the leftover 2 million.
> 18 votes

# Answer
> What else could be done to level the playing field between those players who play 40+ hours a week and those who can't play more than 10?

A simple way to avoid turning off players who don't have the time available to invest in grinding is to remove grinding from the game as much as is reasonable; keep progression curves linear or shallow.

But, I think you're conflating "casual players" and players with players who simply don't have as much time as they'd like to play. There's an overlap, certainly, but fundamentally they are different demographics.

Casual players tend not to care that other players have invested more time, except if those other players are their friends and such they feel like they "can't play together." You can help reclaim their good will by including mechanics that make it worthwhile for higher-leveled players to return to previously-visited or otherwise under-levelled content and play with their low-level casual friend.

You can also include mechanical benefits for activities casual players are more likely to do, such as explore the world. Simply providing experience for discovering areas or engaging in social activities can go a long way.

In Guild Wars 2 we did both of these things (downleveled players to content so it was always at least marginally challenging, and reward non-combat gameplay), and it worked rather well.

The other market you're looking at are those who would love to invest entire weekends or more into your game, but can't. Maybe they have a family or other responsibilities, for example -- a very common method for appealing to these players is to offer microtransactions allowing them to catch up to players with more time. This also has the advantage of providing residual income; income via microtransactions can often dwarf that of subscription fees if implemented in a fashion that does not offend the majority of your player base.

Of course that last part is the tricky one. When considering a microtransaction that is designed to catch up players without as much gaming time, you have to make sure you're offering them an acceleration of some progress and not a direct *purchase* of that process -- in other words, sell experience boosters that increase XP gain rate, but don't sell levels or experience directly. This reduces the likelyhood that it will be used by both the time-constrained and extremely hard-core players, which in turn reduces the likelyhood you'll have to field a slew of "pay-to-win" complaints.

Allowing progress to be gained in some limited fashion while not active in-game is something else you could look at -- EVE Online does this, allowing skills to be trained regardless of whether or not a player is logged in, but requiring you to log in to change what is trained.
> 38 votes

# Answer
I think the inherent difficulty here is that RPG's are generally about investing time in exchange for character progress. People who invest large amounts of time should, almost by definition, have a further progressed character. Speaking as a person who falls quite squarely into the 'casual' label, I don't see this as a problem until it limits interaction between characters with different power/progress levels. As such, I would focus on ways of eliminating large power differentials that are the barrier to character interaction. It's possible that the 'hardcore' players require this power differential to enjoy the game, and in that case it becomes very difficult to balance.

I would do two major things different than MMORPGs I've played. I would put the bulk of the content in the leveling game rather than in the end game, and I would make some sort of power scaling system (such as seen in Guild Wars 2). I would do this in the hope that some players could play the same character through multiple parallel story lines, and some could start a new character each time, and they would be able to play together whenever they wanted.

The remaining issue is then why would a full level character play lower level content. I would try to solve this with distinct flavours or themes per area. This would make it interesting to explore the whole breadth of the game. I would also try to solve this by spreading out the best-in-slot equipment over as much of the game as possible, so that a min/max-er would have incentive to play the whole breadth of the game.

There are many other techniques that can be supplemented, such as rested XP for time logged off, micro-transaction purchases, and per-day XP caps. I wouldn't put too much focus on them because I've seen them implemented and haven't been impressed.
> 7 votes

# Answer
Make the lower level characters still useful somehow and also take up less "space". In a game like PoxNora or Magic, characters have a "casting cost" or whatever. So imagine a dungeon which only allows say 100 levels in, and whether thats a level 90 and a level 10 or 50 level 2s could be up to the players. Or you could even actually abstract it into some kind of summoning points based on more than level. There are probably tremendous balancing requirements for this and it might only make sense in things like "instances" where you can control entry.

Lower level players can still be useful in the world maps. In Eve, for example, lower level players can make "tackling frigates" which do some fun and useful stuff early on. You could make meta-game balancing effects as well to take this to another level. For example, make the higher level players physically bigger and easier to target and make the lower level players even possibly invisible. Lower level spells go unnoticed and higher level spells show up on the radar or something. Make it actually harder and different to play a higher level character, not just bigger numbers in the damage reports.

There could even be classes that are designed to stay at lower levels, and take on support roles while evading player detection or just not having much casting cost.

There could even be an upkeep cost which could happen on world maps. Maybe your team looses some points or something when you die and have to be reincarnated. The cost could be higher for the higher level character.

I've always wanted to take it a step further and make the super amazing items also have some "casting cost".
> 7 votes

# Answer
## Let's analyze the problem.

Here is a funny definition of a Casual Gamer. If we consider it true, then there's simply no solution to your problem. That's why I'll define a casual player as: *A player who doesn't spend a lot of time playing*.

You want a system that lets casual players interact well with hardcore gamers (*players who spend a lot of time playing*, opposite to casuals). By interaction you can mean one of either:

* **friendly interaction** \- healing, building guild cities together, trading etc.
* **hostile interaction** \- fighting, blocking a quest (like in Lineage 2 by guarding an NPC), capturing a flag or a different object etc.
* technically **neutral interaction** \- chatting, guiding someone in a quest (like showing where some important object is located) etc.

or all of them. In most MMORPGs a casual player doesn't have a disadvantage only in third option - he can chat with others, role-play with them with a success, and guide a pro player on a low-level area that he already forgot. As for PVP, he has no chance to defeat a hardcore gamer 1vs1 and is likely not to be taken into a group PVP where he will weaken his party. I will focus on how to fix the hostile interaction, as it's easiest to compare possibilities of two players (a hardcore gamer and casual player) by letting them fight and see who won.

You can choose your target balance as one of these:

1. A casual player has **no chance** to defeat a hardcore gamer. The chance may be not an absolute 0, but below 1% for sure. A good example is OGame.
2. A casual player has a **small chance** to defeat a hardcore gamer. All agility and luck based games fit well here. You can shoot down Quake master. Even when you play for 1st time, you can win with a world champion in a Battleship game.
3. A casual player has a nearly **equal chance** to defeat a hardcore gamer as to lose with him. This is possible to achieve by completely eliminating grinding (giving a player more strength as a reward for time spent in game), and basing player's efficiency on general attributes like player's intelligence, not particular game wisdom (a hardcore gamer knows game mechanics better than the casual). It can be also achieved by complete or nearly complete randomness, where even strategy doesn't help hardcore gamer to defeat a casual player (dices).
4. A casual player has a **high chance** (\>50%) to defeat a hardcore gamer. This is very hard to achieve, but is possible. Such game can't be agility based, because if a casual player has statistically more agility than some hardcore gamer, then, as stated in Urban Dictionary, he is just a *hardcore gamer in denial*. This situation can only be achieved if hardcore gamers are in some aspect weaker than casual players in the target audience, or if a player gets a penalty equal to time spent in game, and he somehow can't just create new account or doesn't want to. **However you should really reflect on if you want to punish settled players for playing your game!**

---

## MMORPG casual-friendly: equal chances

Here are the advantages of hardcore gamers above casual players:

1. They have more friends in game - friendship is like a flower, not watered will fade away, and it is rare to have lots of friends from real life in your favorite game.
2. They have general gaming experience - should I maximize one attribute, or balance two? What is diminished returns?
3. They know the game better - Chess players know openings, MMORPG players know if it's better to go in dodge or armor.
4. They have usually more agility; not real agility, but perceiving 2D monitor view and using keyboard and mouse is easier for someone used to it.
5. This may be a duplicate of first point, but they are inside better guilds.
6. Not only they have all above advantages, but they also are further in progress, and therefore get a technical advantage: better gear, more skill-points spent, more waypoints reached, more abilities unblocked (e.g. riding a horse) are all devastating to already unbalanced hardcore/casual gameplay.

**So how do we fix it?**

1. You can fight this:
    * Creating forum signatures and similar gadgets will let your players advertise the game on forums, their blogs etc. letting them bring old friends instead of forcing to make new friendships in new game.
    * Also fixing the casual-unfriendliness will help: a casual player who discovers your casual-friendly game will advertise it among his casual playing friends.
    * No inflation - if I'm a casual player, and I need help of my friends, these who didn't play for 6 months won't be helpful if there's a technology inflation, making their leather armors obsolete against AK47 guns.
2. Things like diminished returns are nice inventions. You want to use them, you just need to document them with tooltips and tutorials the way a new player gets it quickly.
3. The solution to make the game friendly for new players would be to create a system that is simple, and different from known systems (like D&D that also isn't that simple), or known very well to casual players (like card games). I wrote about it a little here: Turn based battle and formula
4. Here's where the very early design of the game (choosing a genre) is important for casual-friendliness. This rather can't be FPP, or a hard RTS game like Starcraft 2. Generally any game that you could imagine as an e-sport isn't friendly for a casual, unless you target your games to casuals that actually are computer-agile (then ignore this point). Best casual type would be a turn-based game without turn time limit (sometimes a casual player just goes on a trip and returns a month later usually it won't be longer than a day, though).
5. Remove the guilds, or don't give advantages from guilds, or set penalties for guild sizes.
6. And finally player's progress. It is obviously an unfair system for casual players:
    * One option would be to completely remove progress. You just make your build, and play with it.
    * Temporal progress - RTS style. You gain upgrades, but they are all lost when you finally win/lose/draw. Just like items and character levels in League of Legends.
    * Server wipes - this solution is good for weekend or summer casual players. The point of the game is to achieve something in limited number of time a casual player can afford. Red Dragon works like this.
    * Wealth inflation. Adding a possibility of lose, instead of only gaining. If you base a chance of negative events on player's wealth, he will progress slower and slower to the point of his skill. A new casual player who proves to be more skillful in a given game mechanic, will quickly overtake an old player who didn't learn how to deal with some difficulties. I don't know a good example of this mechanic, but every hardcore (death is permanent) game implements it partially (even if a player with more wealth has same chance of dieing as a new player, the former everyday loses statistically more than the latter). Of course this shouldn't affect offline players - I would suggest a chance of a negative event only after every player's action - therefore less active or inactive at all players wouldn't be a subject to the inflation.
    * **You really don't want to advertise your game with such limited progress as a MMORPG game!** The phenomena behind new MMO success is the progress itself. People love to gain power, money and experience. Advertising a game that does otherwise is like creating a family car by a Ferrari company. In this analogy hardcore gamers would be people who like speed of Ferrari, and casual players people who like safe, cheap in exploitation and comfortable cars that Ferrari doesn't produce. In effect casuals who don't like other MMORPG games wouldn't try yours anyway, and hardcore gamers would go away with dissatisfaction.

---

## Higher chances for casuals than for hardcore gamers

If we want to achieve an equality for casuals and hardcore gamers, we should probably aim higher or we will never achieve it, just like Achilles will never get to the tortoise in the Zeno's paradox.

I like to think of people not as better and worse generally, but with different talents. If hardcore gamers are talented in playing computer games, then casual players are probably talented elsewhere. If we want to balance these groups, we should give casual players an opportunity to use their other talents. I don't suggest to balance healthy players with blind in a FPP shooter game, but to give everyone an opportunity to gain some bonuses outside of game mechanics, and the idea is **content created by players**.

If players who are possibly talented in graphic arts, programming, writing, can create their mods or prepare content on forums for awards from developers, this is really a win-win situation that hardcore gamers for sure won't mind.

---

## What a casual game is?

Once on a design stage of a game I decided this game's target will be casual players. So what does that mean? What requirements should it fulfill? That's what I figured out:

* You should be able to pause the game at any time. That's why it's easier to make a single player game for a casual player. Imagine someone plays at work and suddenly his boss arrives, or he 'works' at home and suddenly hears his dog fell from stairs and broke his porcelain bowl - how much time will you give him to pause the game? In games like League of Legends you just can't pause the game, and destroy experience of others if you don't finish the math that can take up to 90 minutes. If you have a small baby and your wife is not at home (or she is not cooperative enough) you just can't play LoL.
* You shouldn't be punished in any way for pausing a game. You may be forced to do some activities in a long period of time, like 2 days, but only if you ask for it, e.g. if you start a poker round, you should answer to every action of your opponent not later than 2 days from his last action.
* Your score should not be dependent on time spent in game, or there should be no score at all (you just fight with others for the eventual fun from winning).
* You should be able to install the game easily - that's why browser games are best for casuals.
* It's not the must, but a lot if not the most of casual activity comes from smartphones when the casual players simply don't have anything better to do. That's why it is a good idea to design your game as a touch friendly (there are also a lot of people playing on touchpads).
* Casual players often work, that's why casual games should be SFW: it doesn't necessarily need to look like Excel, but it shouldn't put players with muted sound at disadvantage.
* The game should not enforce you to be active at a particular time (like OGame does). Everyone, even most hardcore gamers have their life and awarding players who take the game as more important than their real duties is promoting "no-lifes".
> 7 votes

# Answer
Another alternative you could try appart from those already said, you could maybe boost the experience, or some other bonuses, the player gets for the first hour he/she plays per day.

For example, the first 2 hours would grant 4x the exp gained from everything or something, that way even if one grinds too much he/she won't be that far into the game.

Or maybe some kind of feature that would allow the more advanced player to help the lower one in a way that helps both. 9Dragons, for example, had a system of master-disciple, in which the master would aid the disciple with the game and would also gain (and give) a permanent buff as long as the two were logged on.
> 5 votes

# Answer
I think it's almost impossible to make hardcore players play well alongside with casual, unless they are IRL friends. The solution, in my opinion, lies in analysing player stats, and grouping players based on their usual behaviour. This is how it's done in real world of chess (and almost any kind of sport actually). Grand master will not play with amateur, they both will not enjoy it (again, unless they are friends).

This solution is already implemented in some online games. When you are joining the game, you will join party which is close to you in experience and game style. If the player enjoyed the game session, he's more likely to be connected to similar, or even the same players again, if possible.

I guess it is now a general solution applicable to all MMO games, but so far it seems like the most natural. Limiting hardcore players or rewarding casual in some form looks like unfair play.
> 3 votes

# Answer
How about going deep into the mechanics? If you reward a skill instead of time spent then people only investing a little time might do better. As an example, let the power of a spell depend on how poetically the player can describe its effect (as evaluated by other players, of course).
> 2 votes

# Answer
Turn based strategy MMORPG hybrids achieve exactly what you describe. You have a limited number of action points (or other resources) you can spend / units you can build, etc. per day. A casual gamer can log in for 10 minutes, perform all the basic tasks and log out. Or you can spend the whole day if you wish, by micromanaging resources, trading, forging alliances, discussing tactics, spying, etc.

While I think you already have a basic concept and it might be far from a turn based strategy game, you might take a look at such games to learn some tricks or methods you can use.
> 2 votes

# Answer
I would base the game on the player skills, i.e. his abilities to use the mouse and keyboard with ease, rather than on how much points he cumulated.

This means replace "experience points" with real human experience.

As it is already the case for fighting games or car games, it might seems a bit unfitting for an RPG. I'll take in example the RPG game "Monster Hunter" which focuses on the gamer experience : there is no leveling system in this game and you can, with a lot of skill, beat a dangerous monster with the weakest armor of the game.

In this game, cooperation is important and much more emphasized, because you need to consider the skills of your partners and prepare a team strategy before jumping into the fight.

I would see an MMORPG with this kind of system very interesting to play as it removes from the game the boring farming part.
> 2 votes

# Answer
A long time ago, some two years by now, there was a similar question in the site GameCareerGuide and they asked people to send their ideas to mitigate this problem. You cal all read my entry through the following link:

https://docs.google.com/document/d/1NtGADrD0B6rFF1Xb1AJMW69mJJ\_jcGAnN4-DTWQYSx4/edit

It's quite a long read, so the short version is: it requires the shift in paradigm from levels acquired through play to items scavenged or acquired through the success of the player in playing. This way players will make the extra effort to complete missions one single-time instead of going through them repeatedly and become stronger by absorbing the powers of the items they acquire from the world.

It allows people who WANT to keep playing to do so and allows people who CAN'T keep playing to have their characters grow just as much as characters from people who can afford to play 40+ hours a week.

The text's also an old one, so there might be some revision lacking. And sorry for the wall of text, I'm a designer - not a programmer, back then I tended to run wild when writing.

Cheers, Roni
> 2 votes

# Answer
I'll address one point of your question:

> But even the busiest casual players sometimes like to spend a whole sunday afternoon playing a video game.

I always thought that good solution for this particular situation combined with daily/weekly limits is to replace periodic cap with total cap that extends every period.

So instead of allowing to gain 10 points every day, you allow to gain up to 10 points total (from start of game or relevant season), on next day 20, 30 on 3rd etc. That way every player who started on same day will still have exactly same cap, but those who missed some days for different reasons can spend extra time to catch up.
> 1 votes

# Answer
I think it depends largely on the game type, but personally I think focusing more on non-combat mechanics and balancing skills is important, at least for a game I'd enjoy playing. I always disliked the idea of levels as then you instantly put people at different stages in a game with or without their experience as a player but simply as the time invested in the game; which could be different. Ultima Online did a decent job at balancing skills: anyone could get good at something in a reasonable amount of time, but to master it took a long while and dedication. I would consider making a game where you can't simply master all skills, and especially such, some skill-mastery would decline opposing skill types which the player may be mastered in-- I wouldn't expect someone to be mastered in sword fighting and magic, except for the cheesy Game Master. In addition to this, skills could degrade over in-game-time when a player does not practice to a skill. This results in a player who plays the game constantly to need constant work on his character to be the best, and deservingly so, and someone who logs in a few times a week to potentially hold her/his ground in a competition. Much more could be written about this, but perhaps this will spark some ideas.
> 1 votes

# Answer
Why not cut back the interaction?

EVE online shows the starts of this, you level up regardless of if you're actually playing or not.

I've been toying with a concept I refer to as "Poo-RPG", essentially, a game that you interact with for about as long as it takes for a decent toilet break (obviously mobile enabled).

Desktop Dungeons is going down the right path - short individual levels that are not trivial to complete. Completing more will give you more stuff, but you'll still only progress at the same rate - so long as you stay active.

Make levelling about what you can do, not how well you do it. The more you play, the more of the game opens up to you, but playing alongside others you're realistically no more powerful. I think Realm of the Mad God does this - progress unlocks new characters, but they're all about the same power.
> 0 votes

# Answer
One of the strategies I've employed was to make the hardcore players have a real interest in helping and/or mentoring the casual players through the game. Simplest terms would be guild but a more effective version is something like, as you get more powerful in a game you become the ruler of an area and the smaller players actually flock to you for your "coverage" and you in turn want them to do well for NO OITHER REASON than to make you more powerful =)
> 0 votes

---
Tags: game-design, mmo
---


# Question
Title: Unity 2D: Change one instanced prefab then make all the others on the scene like it
I want to get this thing working: I have a prefab with coins, some obstacles and enemies, and i want it to be instantiated each time the player got to the right or left on the stage, to make the stage kinda loop. Then, if the player get a coin in this prefab, this coin will not exist in any other prefab, so if the player goes back to his original place, this coin wouldn't be duplicated(because the idea is a loop)

And it can't delete from the original prefab, because then if we start the game again it'll not have the coins anymore.

Exactly like this: https://www.youtube.com/watch?v=ETxoUDWCBvE

As you can see, when the blue bird gets the other birds, the yellow bird it isn't there anymore if you go back, because the stage kinda loops, and i want to do that.

How enemies would work? Or there's another way of doing this?

# Answer
> 0 votes
(Two ideas here. See bottom for the "simpler" one.)

## Answering exact question:

(Instantiate **each time** the player reaches right/left edge)

Assuming your stages are of similar complexity to those in the video you linked, you can simply give **unique** GameObject tags to each of the dynamic (can be destroyed/deleted) children in the prefab.

Then have a global StageManager object/script used to keep track of changes, perhaps a dictionary mapping from tag to state.

With that in place, next have the code that instantiates the stage prefab recurse down the object's tree. Get each child object's tag and ask the StageManager about the state of that tag. Register, ignore, or kill the child object depending on the StageManager's response.

Maybe try something like so **(warning: have not compiled or tested this)**:

```
public void instantiateStagePrefab(GameObject stageObjPrefab)
{
  GameObject stageObj = GameObject.Instantiate(stageObjPrefab) as GameObject;
  for( int i=0; i<stageObj.transform.childCount; i++ )
  {
    registerOrKill( stageObj.transform.GetChild(i) );
  }
}

private void registerOrKill(GameObject childObject)
{
  StageManager.instance.ensureRegistered(childObject.tag);
  if( !StageManager.instance.getState(childObject.tag) )
  {
    GameObject.Destroy(childObject);
  }
  else
  {
    for( int i=0; i<childObject.transform.childCount; i++ )
    {
      registerOrKill( childObject.transform.GetChild(i) );
    }
  }
}

```

Then in StageManager, have:

```
... (Singleton stuff) ...
private Dictionary<string,bool> tagStates = new Dictionary<string,bool>();
...
public void ensureRegistered(GameObject tagObj)
{
  if(! tagStates.ContainsKey(tagObj.tag))
  {
    tagStates[tagObj.tag] = true;
  }
}

public bool getState( string tag )
{
  bool state = true;
  if( tagStates.TryGetValue(tag, out state) )
  {
    return state;
  }
  return true; // if it's uninitialized, it's active by default.
}

public bool setState( string tag, bool newState )
{
  tagStates[tag] = newState; // overwrite old value or add as new entry
}

```

Finally, have your "collected coin!" code:

1. Call setState with the coin's tag and newState=false.
2. Use GameObject.FindGameObjectsWithTag(tag) to locate all of the already-instantiated objects with that tag. Then GameObject.Destroy() those.

With this bookkeeping code, any new instantiations of the prefab should be free of any objects you've already deemed 'dead'. This applies to enemies, collectibles, platforms, etc. Really, anything you want to give a tag (again: critical that the tags are **unique!**).

---

## Simpler answer in the same spirit:

I think it's possible to just instantiate the prefab 2 or 3 times, side-by-side. Then just move the player and camera "back" a screen when the player nears the edge.

In order for this to look smooth, you'll need to make sure all the animated objects are animated identically (same position, same frame, etc.) or there will be visual artifacts when you shift the player and camera.

You'll still benefit from the 'tag' approach here. E.g. when a coin is collected, the other 1-2 coins with tag "Coin26" can be found by tag and deleted.

This approach takes a lot less bookkeeping, but will also be a lot nicer on whatever machine you're running this on. Instantiating a large "stage" prefab regularly might cause hiccups in rendering/responsiveness, no fun.

No code suggestions here - just move the camera and player left or right by the width of the stage prefab. Should be imperceptible.

Hope all this helps!

---
Tags: c#, unity, 2d, game-loop
---


# Question
Title: Correct way to integrate scaled axis angular velocity into a quaternion
Across my travels on the internet I have came across two different ways of integrating a scaled axis angular velocity into a quaternion.

**The first way** converts the angular velocity into an axis angle quaternion like so

```
Quaternion q = new Quaternion(vector.normalised(), vector.getLength());

```

Where the constructor looks like:

```
float sinHalfAngle = (float) Math.sin(angle / 2);
float cosHalfAngle = (float) Math.cos(angle / 2);

this.x = axis.x * sinHalfAngle;
this.y = axis.y * sinHalfAngle;
this.z = axis.z * sinHalfAngle;
this.w = cosHalfAngle;

```

And then multiplies the existing quaternion by that new quaternion

```
this.rotateSelf(q);

```

**The second approach** also converts the velocity into a quaternion, but uses a different method:

```
Quaternion change = Quaternion.mul(
    new Quaternion(x * 0.5f, y * 0.5f, z * 0.5f, 0),
    this
);

```

It then adds the quaternions together, scaled by delta T:

```
this.w += change.w * scale;
this.x += change.x * scale;
this.y += change.y * scale;
this.z += change.z * scale;

```

Both approaches produce a rotation, however the first approach rotates the object much faster than the second. I was wondering which is the 'more' correct way, or if they are just different methods used for different units perhaps? (ie: degrees vs radians?)

Thanks very much if you can help.

# Answer
When Microsoft created the XNA framework (I know you're using Java, but the math is the same), they created a built in method to create a Quaternion from an axis and angle. The method they used (and you can "reflect" their managed code to verify it, see below) is the same as your first snippet:

```
public static Quaternion CreateFromAxisAngle(Vector3 axis, float angle)
{
    Quaternion quaternion;
    float num2 = angle * 0.5f;
    float num = (float) Math.Sin((double) num2);
    float num3 = (float) Math.Cos((double) num2);
    quaternion.X = axis.X * num;
    quaternion.Y = axis.Y * num;
    quaternion.Z = axis.Z * num;
    quaternion.W = num3;
    return quaternion;
}

```
> 1 votes

---
Tags: java, physics, quaternion, integration
---


# Question
Title: Trapping mouse inside window in OpenGL with GLUT?
I perfectly understand that GLUT is limited and the following problem can't probably be solved with OpenGL/GLUT, but since I don't know exactly if it can or not, I better just ask. Maybe I'm doing something wrong or forgetting something important. Or probably not and GLUT doesn't get better than this.

My problem is that I can't trap the mouse inside the window. Well, actually, I can, the code below does just that. I trap the mouse inside the window and I can use the mouse freely to rotate the world. The problem? If I move the mouse too fast I can get way from window prison.

Is there a way around this with OpenGL/GLUT or the only option is another library or make some calls to the Windows API directly? Enough words, here's my current code:

```
void processPassiveMouseMotion(int x, int y) {
    static int centerX = glutGet(GLUT_WINDOW_WIDTH) / 2;
    static int centerY = glutGet(GLUT_WINDOW_HEIGHT) / 2;

    CameraAngle.x = -1.0f * (y - centerY);
    CameraAngle.y = -1.0f * (x - centerX);

    if(CameraAngle.x != 0.0f || CameraAngle.y != 0.0f) {
        SceneCamera.Rotate(CameraAngle);
        glutPostRedisplay();

        glutWarpPointer(centerX, centerY);
    }
}

glutPassiveMotionFunc(processPassiveMouseMotion);

```

# Answer
To the best of my knowledge this is Windows-API specific - this functionality doesn't even exist on all platforms. If you want to dig through my code you can find a working Windows implementation (LockMouseCursor is the entry point into the OS module, ClipCursor is the actual Windows function that does the trapping, but there's some niceties surrounding that function - it shouldn't be too tough to decipher.)

I also have a Linux implementation in pure X (again, start with LockMouseCursor) but I've never found a usable OSX API for it. If you end up needing one or coming up with one, check my Stackoverflow question on the matter :)
> 7 votes

# Answer
With a quick search through the GLUT spec, GLUT does not seem to have mouse capture capabilities. The best you can do (like you seem to be doing) is to warp the cursor to the center and hope the user isn't fast enough (or isn't using a tablet) =)

Or, you could switch to SDL or SFML, as GLUT is only designed for testing, not "real" software.
> 2 votes

# Answer
Try a newer version of freeglut; My v2.6, traps cursor with glutWarpPointer without any possibility of escape by mouse.
> 2 votes

# Answer
In my case, modify

```
glutWarpPointer(centerX, centerY);

```

to something like

```
if (x != centerX || y != centerY) glutWarpPointer(centerX, centerY);

```

perfectly solved the problem.

The problem is caused by glutWarpPointer triggering another passive motion event to (centerX, centerY), which results in a loop and/or floods the event queue. To avoid it, simply check if the mouse is at (centerX, centerY), if so, don't warp.
> 2 votes

---
Tags: opengl, windows, glut
---


# Question
Title: How does sound effects being in tune affect the game?
Many sound effects have a dominant frequency, especially for artificial sounds (UI, "powerups") and short effects that get repeated (machine guns). Whether by design or accident, these sound effects could be in tune with each other, or with the music.

My questions are, **does this matter** at all (in games), and if it does, **what effects does this produce**? When would one purposefully create harmonies, disonnances, or avoid such effects altogether?

In music theory, the effects of consonance/dissonance is well known, one of which is that notes in tune with each other are *pleasant*, and those that are not are *unpleasant*. But what about in games, does it matter that, for example, the laser gun you are shooting is in tune with the music?

At least a few well known games have *harmonic* sound effects, and although it may be deliberate, I'm not sure if it's a purely subjective/artistic choice, or whether it was designed to evoke specific feelings from the player. One notable example is *Candy Crush Saga*, whose match effects are all part of the same major key as the music: https://youtu.be/8TIeNDnJiN8?t=6m57s

Another example is *Super Mario Bros*, in particular the 1-up sound effect: https://youtu.be/w2NjUDfOp2o?t=22s although other powerup effects like the coin sound are *not* in the same key, for whatever reason.

At least one sound designer seems to think this is important:

> **Aaron Marks**: I think I’m pretty much always in the ‘musical’ mindset when doing sound design, whether it’s recording, mixing and mastering or on a creative level. Music is definitely in my blood and I think, subconsciously at least, it’s always there when I’m doing any audio work. I definitely have some techniques where I ‘tune’ sound elements to be either pleasant or something a little more harsh. I also tend to pay attention to the music that is accompanying a scene or game level and often tune the sound effect to a note which blends well or I’ll go the opposite direction and detune it, especially for evil characters and their weapons, for example. You definitely want the audience to ‘feel’ the evilness and this is a great way to do it without being in their face about it.
>
> In games especially, part of the goal is for all of the sound effects to feel natural to the game and not bring any undue attention to themselves. By doing this, the ones you want to really stand out will definitely be noticeable and have more impact. I’m always very careful for sounds like tractor beams, engines, humming machinery or ambience to tune them so they all work together and with the music.

Although this is just one opinion; I'd like to hear from those who have experience with professional game sound design to weigh in, is it something that sound designers generally worry about, and if so, when would one want to have sounds that are in tune, out of tune, and what the effects are.

# Answer
Harmonizing the soundscape is another level of polish you can apply to your game, and it works like this: If you're going to be playing a lot of the same sounds over and over, and most action games need to, you don't want it to get annoying. So you fine tune the sounds so that they don't clash but still sound pleasant, or even musical, when played together.

Conversely, you can emphasize sounds by using harmony followed by sudden dissonance or vice versa. Horror games often use ambiance in harmonized tones, then make the parts that are supposed to be scary dissonant. Just like we can use music to signal changes in tone, so can we use contrasting harmony. This way we can get quick changes in mood that wouldn't make sense to try with music.

So, when the sound isn't clipping, all the recorded audio is high quality and noise free, and they aren't playing the same voice samples over and over, but the game just sounds *off*, it might just be the harmony. You'll usually find it in low budget games that make heavy use of clips from libraries or found on the internet, with no attention to tweaking those sounds to work together. It's not *that* bad (compared to some of the other flaws mentioned), but it can make the game sound "amateurish."
> 4 votes

---
Tags: sound, sound-effects
---


title: Implementing A* with Heap tree

text:
# Question
Title: Implementing A* with Heap tree
I'm trying to implement Heap into my A\* algorithm, However I'm having trouble with implementing one method. The Contains method. Which checks if the heap array has a specific node in it or not. I don't know how to implement that. If I just make a for loop and check every item in the heap that would be very very slow and defeat the purpose of a heap.

So my question is, How do you check if an item exist in a OpenSet of type Heap? What is the fastest way to do it?

This is my heap code:

```
namespace AI
{
public interface IHeapItem<T> : IComparable<T>
{
    int HeapIndex { get; set; }
}

class Heap<T> where T : IHeapItem<T>
{
    T[] Items;
    int count;
    public int Count { get { return count; } }

    public Heap(int MaxSize)
    {
        Items = new T[MaxSize];
    }

    public T this[int Index]
    {
        get
        {
            if (Index > count)
                Index = count - 1;

            return Items[Index];
        }

        set { Items[Index] = value; }
    }

    public void Push(T Item)
    {
        Item.HeapIndex = count;
        Items[count] = Item;
        SortUp(Item);
        count++;
    }

    public T Pop()
    {
        T FirstItem = Items[0];
        count--;
        Items[0] = Items[count];
        Items[0].HeapIndex = 0;
        SortDown(Items[0]);
        return FirstItem;
    }

    public bool Contains(T Item)
    {

    }

    void SortDown(T Item)
    {
        while (true)
        {
            int LeftChildIndex = Item.HeapIndex * 2 + 1;
            int RightChildIndex = Item.HeapIndex * 2 + 2;
            int swapIndex = 0;

            if (LeftChildIndex < count)
            {
                swapIndex = LeftChildIndex;

                if (RightChildIndex < count)
                    if (Items[LeftChildIndex].CompareTo(Items[RightChildIndex]) < 0)
                        swapIndex = RightChildIndex;

                if (Item.CompareTo(Items[swapIndex]) < 0)
                    Swap(Item, Items[swapIndex]);
                else
                    return;
            }
            else
                return;
        }
    }

    void SortUp(T Item)
    {
        int ParentIndex = (Item.HeapIndex - 1) / 2;

        while (true)
        {
            T ParentItem = Items[ParentIndex];
            if (Item.CompareTo(ParentItem) > 0)
                Swap(Item, ParentItem);
            else
                break;

            ParentIndex = (Item.HeapIndex - 1) / 2;
        }
    }

    void Swap(T ItemA, T ItemB)
    {
        Items[ItemA.HeapIndex] = ItemB;
        Items[ItemB.HeapIndex] = ItemA;
        int itemAIndex = ItemA.HeapIndex;
        ItemA.HeapIndex = ItemB.HeapIndex;
        ItemB.HeapIndex = itemAIndex;
    }
}
}

```

# Answer
> 4 votes
In A\* implementations, this method is commonly completely unneeded, as you maintain an "open list", which is the minheap (note minheap vs maxheap here). Instead of finding out if a node is contained in the frontier, you maintain a list called something like "costSoFar", which maintains a list of the smallest cost for any one node, and check for the node in this. Note that this could be handled inside of the node itself, in your case by adding a `bool OnOpenList { get; set; }`, a `bool OnClosedList { get; set; }`, as well as a `float (or int) costSoFar { get; set; }`. This would allow you to check if the node is contained in the minheap without actually checking. A sample loop would be as follows: (I use Vector2's to store positions here, but you could very well use two integers or floats.)

```
private static Foo FindPathReversed(Vector2 start, Vector2 end)
{
    var world = GetWorld();

    MinHeap<Foo> openList = new MinHeap<Foo>(); // The frontier
    Foo[,] nodeWorld = new Foo[(int)world.size.x, (int)world.size.y];
    Foo node;
    Vector2 temp;
    int cost;
    int diff;

    Foo current = new Foo(startPosition);
    current.cost = 0;

    Foo finish = new Foo(end);
    nodeWorld[(int)current.position.x, (int)current.position.y] = current;
    openList.Insert(current);

    while (openList.Count > 0)
    {
        //Find best item and switch it to the 'closedList'
        current = openList.RemoveRoot();
        current.onClosedList = true;

        //Find neighbours
        for (int i = 0; i < surrounding.Length; i++)
        {
            temp = new Vector2(current.position.x + surrounding[i].x, current.position.y + surrounding[i].y);
            if (world.TileIsPassable((int)temp.x, (int)temp.y)) // You must define this method
            {
                //Check if we've already examined a neighbour, if not create a new node for it.
                if (nodeWorld[(int)temp.x, (int)temp.y] == null)
                {
                    node = new Foo(temp);
                    nodeWorld[(int)temp.x, (int)temp.y] = node;
                }
                else
                {
                    node = brWorld[(int)temp.x, (int)temp.y];
                }

                //If the node is not on the 'closedList' check it's new score, keep the best
                if (!node.onClosedList)
                {
                    diff = 0;
                    if (current.position.x != node.position.x)
                    {
                        diff += 1;
                    }
                    if (current.position.y != node.position.y)
                    {
                        diff += 1;
                    }

                    // These functions are not part of the standard library but probably have equivalents.
                    int distance = (int)Mathf.Pow(Mathf.Max(Mathf.Abs(end.x - node.position.x), Mathf.Abs(end.y - node.position.y)), 2);
                    //int distance1 = (int)Mathf.Pow(Vector2.Distance(new Vector2(node.position.x, node.position.y), new Vector2(end.x, end.y)), 2);
                    cost = current.cost + diff + distance;
                    //cost = current.cost + diff + (int)Mathf.Pow(Vector2.Distance(node.position, end), 2);

                    if (cost < node.cost)
                    {
                        node.cost = cost;
                        node.next = current;
                    }

                    //If the node wasn't on the openList yet, Insert it
                    if (!node.onOpenList)
                    {
                        //Check to see if we're done
                        if (node.Equals(finish))
                        {
                            node.next = current;
                            return node;
                        }
                        node.onOpenList = true;
                        openList.Insert(node);
                    }
                }
            }
        }
    }
    return null; //no path found
}

```

Note that this code should be taken at face value: as a sample. I have written this code from memory, so it may very well be not completely accurate. I also have more infrastructure surrounding this; if you have some basic implementation or structure questions don't be scared to leave a comment.

# Answer
> 2 votes
Pip's answer is the right answer but I wanted to add that if you really did need to know set membership quickly and efficiently, you could have added a flag to each node to specify which list it was in. That gives you the extra burden of maintaining that flag's correctness as you move nodes between lists, but the benefit is that you get a super quick answer to your question about whether its in the open list or not.

---
Tags: c#, tree
---


# Question
Title: Relation between TFLOPS and Threads in a GPU?
What's the relation between Teraflops and Threads in a GPU like GTX Titan X has 7 TFOPS of Compute Performance but how many threads it has ? And Like Xbox and PS4 have 1.32 and 1.84 TFLOPS of compute performance but how many threads they have? Like what’s the relation between teraflops and threads?

If they are different concepts. Can you please explain both of them?

# Answer
A TFLOPS is short for **T**erra(Billion) **F**loating **P**oint **O**perations **P**er **S**econd

It simply means how many floating point operations(Such as adding, multiplication, division) can a processing device do in a second.

Threads are simply paths of execution, the more threads a process has, the more processor cores can it use, so in a multi-core environment it is faster.

Both of these are general concepts that apply to both processors and GPUs. GPUs usually have much more cores(in the hundreds) so parallelism(use of many threads) is very important to achieve high performance there.

There is no direct relationship between the two, but usually the more threads means more processing power, as there is a limit how much transistors and thus flops can we pack into a single core.

---

You could compute a processors total FLOP speed using the following calculation:

`Performance = Cores * CorePerformanceInFLOPS`

Tough many processes can't be parallelized well, and the performance increase is less than 50% when adding a second core, and gets less and less effective with more cores.

A thread is a separate thing than a core. A core is a physical entity, while a thread is a path of execution. Tough if you have an `n` threaded program, you can't use more than `n` cores to do that.

Also please note that this doesn't take into account hyperthreading(mainly found in Intel CPUs) where one physical core runs 2 threads, effectively acting as 2 separate cores.

As for what performance is needed for a specific algorithm, it depends on waaay too many factors to be determined. Just because a hardware has a high FLOP value, it doesn't mean it will be able to use it, if its bottlenecked by Memory bandwidth, or the CPU. Also the algorithm may be optimized poorly or well, also it may be optimized specifically for this hardware or another, and again the hardware may be optimized for this process or another, and the process may be parallelizeable or not(in which case you won't benefit from additional cores) so as you can see its not a question easily answered.
> 1 votes

---
Tags: gpu, gpgpu
---


# Question
Title: How to stop a running timeline in GameMaker Studio?
I am creating a game using GameMaker Studio and I need to stop a timeline that is in progress. How can I approach that with GML code?

# Answer
> 1 votes
You can use

```
timeline_running = false;

```

or

```
timeline_speed = 0;

```

---
Tags: game-maker
---


# Question
Title: Instantiating prefabs dynamically in script
I have a canvas object. I right click it and add a Button, which defaults to having a rect transform, image script, button script and text child object. I make it a prefab and delete it from my canvas. I want to have a data driven engine so I have an external list which I want to make into buttons. When I have my list loaded I attempt to create dynamic buttons by:

```
GameObject prefabButton = new GameObject("StandardButton");

```

This in the hierarchy but it doesn't have the image or button or text components added, only a transform.

Why doesn't it have the things the prefab has??

I read I might need to instantiate it, so I tried:

```
GameObject stdButton = (GameObject)Instantiate(prefabButton);

```

Again this creates another object in my hierarchy with nothing but a basic transform.

What is the difference between this object and the one I created before? Why instantiate at all?

# Answer
> 2 votes
Presuming you've saved the prefab out to your Resources folder in your project, you will need to load and instantiate it and then attach it to the canvas. Your code should be something like this:

```
Canvas canvasComponent = GameObject.Find("Canvas").GetComponent<Canvas>();
GameObject myButtonPrefab = Resources.Load<GameObject>("whatEverTheButtonPrefabIsCalled");
GameObject actualButton = GameObject.Instantiate(myButtonPrefab) as GameObject;
myButtonPrefab.transform.SetParent(canvasComponent.gameObject.transform, false);

```

Hope that helps.

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


# Question
Title: Correctly bitmasking path tiles based on existing paths
Currently, I have a bitmasking implementation that sometimes incorrectly bitmasks the tiles. Conventionally, it is done correctly, and the math/etc is sound, but it achieves results such as the following:

This is similar to what you might expect, and looks fine when doing simple x-shaped crossings. However, I would like for the images to remain unchanged in some of these cases. For instance, the parallel paths in the third image would remain parallel paths instead of being bitmasked into many crossings. In the first and second images, only the parts of the path highlighted in the following images would be bitmasked (Different parts of path labelled for clarity.)

If I purely update only the tiles that make up the newest path, I again get good results in simple x-shaped crossings, however I get results such as those demonstrated in the following image:

What could I do to achieve results where this would not occur? I have though about adding some sort of flag to the tile to indicate that it is a crossing, but how could I detect that?

# Answer
> 3 votes
You draw out your first path, and it has no knowledge of other upcoming paths. Once you draw your second path (overlapping the first) you need to update your first path again, so that it knows about the second path.

This is just a bad way of doing it. A better option would be to draw out all your paths first, and then check the neighbors in a second pass to instantiate your bitmasking. Otherwise, you are going to have to update all trails everytime you create a new trail (which could also be a solution for you, albeit a little slower).

**EDIT**

Ok, so I understand now that you don't want some of the paths to intersect. You should try to give each path an ID, and then check if your surrounding tiles are from the same path or not.

If they are not from the same path, then you would not include it in your bitmask calculations. However, if the tile is crossing over another path, then you would include them, as at this point you would want them to connect.

---
Tags: graphics, tiles, tilemap, tile-bitmasking
---


# Question
Title: How to setup a particular blend state where the alpha channel is additive?
I would like to set a blend state to be "*additive*" and do the following:

```
Result.R = Source.R + Destination.R;
Result.G = Source.G + Destination.G;
Result.B = Source.B + Destination.B;
Result.A = Source.A + Destination.A;

```

So I've tried setting a blend state to:

```
IsBlendEnabled = 1;
SourceBlend = BlendOption.One;
DestinationBlend = BlendOption.One;
BlendOperation = BlendOperation.Add;
SourceAlphaBlend = BlendOption.One;
DestinationAlphaBlend = BlendOption.One;
AlphaBlendOperation = BlendOperation.Add;

```

I was thinking it would do:

```
Result = Source*BlendOption.One + Destination*BlendOption.One;

```

But I doesn't work (I've tried so other combinations as well). The color (`RGB`) channels are adding up correctly but the `alpha` channel is not (it's not affected by the blend finally, but still not adding up). I'm drawing three overlapping quads with different colors (`red`, `green`, `blue`) and `alpha` of 0.1. But result `alpha` is not 0.0-0.3 (0.0 = no overlap, 0.1 = one quad, 0.2 = two quads overlap, 0.3 = three quads overlap) as I would expect.

**Is it even possible to setup blend state to accumulate `alpha` on render target?**

**Note**: I would like to have a color map (`RGB`) being mixed and `alpha` channel indicating how many quads are overlapping (0-3 quads =\> 0.0-0.3 `alpha` value).

# Answer
To close this up. As far as I know this is not possible. I solved it by using a different texture to store this information.
> 0 votes

---
Tags: xna, directx, sharpdx, blending, alpha-blending
---


# Question
Title: OpenGL: Is it efficient ok to glPushMatrix, plMultMatrix, plPopMatrix for every object in my scene?
I'm very new to opengl, and I might not fully understand the openGL matrix projection stack thing.

So, I have about 300 'objects' in my scene, each with their own position/rotation, and I want to draw them all (ignore culling and overdrawing for now). Would it be efficient enough to:

```
for each object {
    glPushMatrix();
    glMultMatrix(object pose);

    // do object drawing

    glPopMatrix();
}

```

or is there a better way to draw each object?

# Answer
Generally speaking, using old OpenGL API is not efficient.

In ye olden days of OpenGL 1.0 this pattern was necessary. The model view matrix contains the model and the view matrix. You have the view matrix on the camera and the model matrix on the model. You set the view matrix onto the model view matrix and then push/pop the model matrix on top of it for each object. This was the most efficient way to do it.

But since OpenGL 3.0 the these matrices don't exist anymore and you need to maintain your own state and submit them as uniforms to the shader. As a result this question basically is obsolete. The most efficient way is to compute the matrices in the CPU as you need them. For example if you only need a projection-view-model, it makes sense to compute the PVM matrix on the CPU instead in the vertex shader over and over again.
> 3 votes

# Answer
generally it's acceptable but not best. If objects share same material and animation skeleton, make them into one batch and call glDrawArray once, though it's advanced usage if you are new to opengl, and it need more code work to achieve. you can read this and this for reference.

Another simpler way is reduce the glPush/Pop Call by grouping objects share same transform. Push /Pop matrix once and draw the group.
> 1 votes

---
Tags: opengl, matrix, projection-matrix
---


# Question
Title: How do I draw a sprite on top of a video in Andengine?
I'm playing a video in Andengine on

```
@Override
protected void onSetContentView() {}

```

However, when I place a sprite on the screen at some point in time, it is placed behind that video view. I want it to appear in front of it.

My attempt:

```
Entity foregroundLayer= new Entity();
foregroundLayer.attachChild(drag1);
scene.attachChild(foregroundLayer);

```

Setting `setZIndex` also didn't work

Here's a screenshot:

The world icon is half outside and half behind. It should be on top.

# Answer
> 0 votes
It should be straightforward, I think:

* Set Z index of your `WorldIcon` higher than `VideoView`.
* Do `scene.sortChildren()` to apply the Z index sorting.

# Answer
> -1 votes
try this. In short terms you have to rearrange the rendering order.

---
Tags: andengine, draw-order
---


# Question
Title: Doing object movement in a loop in unity
I have a Game Object at position (0, 0, 0). To move it to position (2, 2, 2), I'm using this code below -

```
void Update () {

Vector3 TargetPosition = new Vector3(2, 2, 2);

transform.position = Vector3.MoveTowards(transform.position,TargetPosition,

23 * Time.deltaTime);

}

```

How do I put this movement in a loop like behavior so that whenever the Game Object reaches position (2, 2, 2), it again starts moving from (0, 0, 0) to (2, 2, 2) ?

# Answer
I did some more reading. And did it this way. It finally works.

```
public Vector3 position1 = new Vector3(0 ,0, 0);
public Vector3 position2 = new Vector3(2, 2, 2);

void Update(){

    transform.position = Vector3.MoveTowards(transform.position,
                                             position2, 23 * Time.deltaTime);

    if (transform.position.x == 2) {

        transform.position = position1;

        transform.position = Vector3.MoveTowards(transform.position,
                                                 position2, 23 * Time.deltaTime);

    }

}

```
> 0 votes

# Answer
I'm assuming you're a beginner so I've kept this as simple as I could think of. Please let me know if you need more clarity.

```
public class ObjectMover : MonoBehaviour
{
    public Vector3 position1 = new Vector3(0.0f, 0.0f, 0.0f);
    public Vector3 position2 = new Vector3(2.0f, 2.0f, 2.0f);

    Vector3 currentTargetDestination;

    public float distanceTolerance = 0.5f; //you can change the tolerance to whatever you need it to be

    void Start()
    {
        transform.position = position1; //set the initial position
        currentTargetDestination = position2;
    }

    void Update()
    {
        transform.position = Vector3.MoveTowards(transform.position, currentTargetDestination, 23 * Time.deltaTime);

        if(Vector3.Distance(transform.position,currentTargetDestination) <= distanceTolerance)
        {
            //once we reach the current destination, set the other location as our new destination
            if(currentTargetDestination == position1)
            {
                currentTargetDestination = position2;
            }
            else
            {
                currentTargetDestination = position1;
            }
        }
    }
}

```

I'm not on a machine that has Unity on it, and thus can't test it, but I think that should work (let me know if you see any errors!)
> 3 votes

---
Tags: unity, movement
---


# Question
Title: Polygons requirement on mobile devices, around 3000 vertices?
I read on the `unity` documentation that a character should be between 300 to 1500 "polygons" on mobile devices to have good results. In `Blender`, we have "tris" or "faces", does "polygon" stand for the "face" here?

Also, my character will have around 2800-3000 vertices, with 10-12 bones. Considering the requirement for 1500 vertices was written some years ago, should I trust in the power of the new mobile devices and continue like this, or should I make a new retopology to reach the 1500 vertices in total? I will not have more than 2 characters on screen.

Thanks

# Answer
> 2 votes
You seem to be mixing polygons and vertices in your question.

Polygons generally refer to triangles.

As for the load on the graphics, you should probably aim for a "minimum requirement" device and see how it handles your game, graphics wise. This is going to be your maximum number of polys.

---
Tags: unity, performance, blender
---


# Question
Title: Deleting fewest Navmesh Obstacles when no valid path is found
So I'm building a Tower Defence, with mazing (i.e. the player can place towers to make the mobs take a longer route to there destination.)

I'm using Unity's Navmesh system. Each Enemy unit has a Navmesh Agent component. And each Tower has a Navmesh Obstacle component.

The Path-finding is working Perfectly. However (as expected) when the play completely blocks off all routes to the Agent's Destination, the agent simply moves to the spot closest to the destination that it can get to and sits there.

What i need, is to detect when that happens... Some kindof NoValidRoute() or something, I haven't been able to dig anything up in the Unity documentation or from google Searches.

Once i have that, I need to determin which Navmesh Obstacles need to be destroyed to open the shortest route possible with the fewest number of Obstacles destroyed. (i.e. if a path can be opened with only 1 tower destroyed which tower would give me the shortest route.)

I'm finding a serious lack of any information on this subject.. as far as i can tell no one has even tried to do this, or asked for help doing something like this. (at least not with Unity's Nevmesh.) I think A\* is a little(and by little i Mean LOTS) outside of my skill to implement at present.

Thanks In advance

# Answer
> 1 votes
Make the cost of moving through/destroying an obstacle an order of magnitude greater than the cost of the entire path. The exact amount is not important just that destroying a single obstacle is more expensive than taking the long way around through every tile of your map.

Then using the usual shortest path search methods (Dijkstra/A\*) you will end up with the path that uses the least amount of obstacle destructions.

From the cost of the resulting path you can derive how many obstacles there need to be destroyed.

# Answer
> 0 votes
I feel like there is a conceptual error: Do you really want to destroy the 'cheapest' obstacle, or rather preventing the player from placing this last, full blocking, tower. If this is the case you should recreate a new route as soon as the player clicks to place a tower. As ratchet freak said you can assign a much higher cost to passing through towers and you will find out this way if there is still a valid route (no high cost). If there isn´t you just prevent the player from placing the tower.

---
Tags: unity, navmesh
---


title: ScrollPane scrolling velocity

text:
# Question
Title: ScrollPane scrolling velocity
I'm working with a custom ScrollPane, but I can't find how to change the velocity of scrolling (not on fling action). Can anybody tell me how reduce scrolling velocity on calling setScrollY() or setScrollX()?

# Answer
> 2 votes
I had a look at the ScrollPane source code on GitHub. That's quite a difficult problem.

The animation is done in the ScrollPane's act method. If you set the scroll value manually, the visual scroll value used for rendering will align on the scroll value over time through an interpolation process (usually in a few frame).

Here is the code responsible for this behaviour in the ScrollPane's act method :

```
            // ...

            if (visualAmountX != amountX) {
                if (visualAmountX < amountX)
                    visualScrollX(Math.min(amountX, visualAmountX + Math.max(200 * delta, (amountX - visualAmountX) * 7 * delta)));
                else
                    visualScrollX(Math.max(amountX, visualAmountX - Math.max(200 * delta, (visualAmountX - amountX) * 7 * delta)));
                animating = true;
            }
            if (visualAmountY != amountY) {
                if (visualAmountY < amountY)
                    visualScrollY(Math.min(amountY, visualAmountY + Math.max(200 * delta, (amountY - visualAmountY) * 7 * delta)));
                else
                    visualScrollY(Math.max(amountY, visualAmountY - Math.max(200 * delta, (visualAmountY - amountY) * 7 * delta)));
                animating = true;
            }

            // ...

```

As you can see, the speed depends mostly on the distance between the current visual value and the setted "official" value. Some values that limit and defines the speed are hardcoded ("200", "7"), so *there is currently no way to setup the speed for this animation cleanly*.

**Here are some ideas/solution :**

* **Override the act method** of the Scrollpane. Just copy the source from the full act method and tune the hardcoded values (but that's dirty)
* **Create customs actions** to update the visual scroll value and the scroll value manually.
* **Modify the Scrollpane class** to make the animation speed use the velocity attributes and make a pull request on the libgdx Github repository, so that everybody will maybe benefit of this fix one day.

# Answer
> 1 votes
You could try creating your own version of the `ScrollPane` by inheriting from `ScrollPane` and then overriding `visualScrollX(float pixelsX)` and `visualScrollY(float pixelsY)`, and multiply the parameter by some factor before calling the base class implementation;

```
class MyScrollPane extends ScrollPane {
  @Override
  protected void visualScrollX(float pixelsX) {
     super.visualScrollX(pixelsX * 0.5f);
  }

  @Override
  protected void visualScrollY(float pixelsY) {
     super.visualScrollY(pixelsY * 2.0f);
  }
}

```

---
Tags: libgdx, scrolling
---


title: Understanding normal mapping

text:
# Question
Title: Understanding normal mapping
I am trying to understand the basics of normal mapping using this tutorial : http://ogldev.atspace.co.uk/www/tutorial26/tutorial26.html

What I don't get there is the following equation : E1 = ( U1 - U0 ) * T + ( V1 - V0 ) * B

How do they came to this equation? This it out of nowhere for me. What is E1? The tutorial say that E1 is one edge of the triangle. But I don't get it, in the equation E1 seems to be a real number, not a vector ( which an edge is supposed to be right? he have a x and y component ).

# Answer
You have 3 points, P01, P1 and P2. (Look at the figure right above the equation.) The points create a triangle. This triangle lies on a plane and on this plane are the two vectors T and B. (Tangent and Bitangent) These vectors are more or less random, optimally they are at a right angle, but this may not be the case, the only requirement is that they are not the same.

With all this you can define the edges (E1 and E2) in respect to T and B.

```
P0 = (U0, V0)
P1 = (U1, V1)
P3 = (U2, V2)

E1 = (U1 - U0) * T + (V1 - V0) * B
E2 = (U0 - U2) * T + (V0 - V2) * B

```

---

Going from there:

Now since you know T and B in world space (and the normal N), you can construct the matrix TBN that will convert the normal from tangent space (as in the normal map) into world space (as required from lighting). The following equations basically outline the mathematical principles based on TB matrix. (The normal N is added later to also account for Z value of the normal.)

For arbitrary meshes the tangent and bitangent are vectors along the surface of the mesh. These need to be computed during construction/loading of the mesh. (You can skip the bitangent if you allow to simply do `B = T x N`)
> 1 votes

---
Tags: opengl, mathematics
---


title: How to read neighbor pixels in GLSL?

text:
# Question
Title: How to read neighbor pixels in GLSL?
I'm using SFML 2.1, it's much more straightforward for me so I can jump directly to learning the shading language.

I'm trying to do something similar to conway's game of life. I already learned that I will need to use 2 textures since I need to read and write at the same time.

My questions:

* How do I read neighbor pixels ? Do I need to pass a vec2 from the vertex shader to the fragment shader like this ? :

vertex shader:

```
out vec2 pixelpos;
void main(){
    pixelpos = gl_Position;
}

```

fragment shader:

```
in sampler2d mytexture;
in vec2 pixelpos;
void main(){
    if(mytexture[pixelpos.x][pixelpos.y].r > 0.5)
    {}
}

```
* How do I write to a texture ?

# Answer
> 5 votes
I did something similar, but with edge detection algorithm. I would use the following setup:

* 2 frame buffers with one texture each.
* a vertex buffer/mesh with a full screen rectangle (-1,-1 -\> 1,1) with the texture cords going from 0,0 to the texture size.
* one shader computing the game of life

The two frame buffers are used alternating, since they can not be read and written to. (At least that is not efficient.)

The vertex shader is basically a pass through shader:

```
#version 400

in vec3 aVertex;
in vec2 aTexCoord;

out vec2 vTexCoord;
out vec3 vNormal;

void main()
{
    vTexCoord   = aTexCoord;
    gl_Position = vec4(aVertex, 1);
}

```

The fragment shader then uses `texelFetch` to get the individual values from the texture. For example something like this:

```
uniform sampler2D uTexture;

in vec2 vTexCoord;

out vec4 oFragColor;

void main()
{
   bool alive = texelFetch(uTexture, ivec2(vTexCoord)).r < 0.7;
   float s = 0;
   for (int i=0; i<3; i++)
   {
        for (int j=0; j<3; j++)
        {
            if (i != 1 && j != 1)
            {
                s = s + texelFetch(uTexture, ivec2(vTexCoord) + ivec2(i-1,j-1), 0).r;
            }
        }
    }

    if (alive)
    {
        if (s < 1.5)
        {
            oFragColor = vec4(0, 0, 0, 1);
        }
        else if (s > 1.5 && s < 3.5)
        {
            oFragColor = vec4(1, 1, 1, 1);
        }
        else
        {
            oFragColor = vec4(0, 0, 0, 1);
        }
    }
    else
    {
        if (s > 1.5 && s < 3.5)
        {
            oFragColor = vec4(1, 1, 1, 1);
        }
        else
        {
            oFragColor = vec4(0, 0, 0, 1);
        }
    }
}

```

---
Tags: shaders, sfml
---


title: Can I use Node.js on consoles?

text:
# Question
Title: Can I use Node.js on consoles?
I was wondering if Node.js was suitable for making games and apart from threads and engines, a big problem is *can I port my game to Xbox or PS3/PS4?*

# Answer
> 5 votes
Node.js runs on the V8 JavaScript engine:

> Node.js is a platform built on Chrome's JavaScript runtime for easily building fast, scalable network applications. Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient, perfect for data-intensive real-time applications that run across distributed devices.

V8 itself is C++ and can be embedded in any C++ application.

Thus, it is theoretically possible to use Node on consoles, although I'm not aware offhand of anybody who has tried. You may or may not run into porting issues as you would with any codebase.

That said, I don't see why you'd choose to use Node for client-side work on consoles, given the hoop-jumping you'll need to do.

# Answer
> 0 votes
I'm pretty sure that you'll have a hard time using V8 on game consoles because it's going to need to generate code into writable executable pages, which usually isn't allowed.

If you ask the developer support folks for the console you're targeting, you may be able to make a business case to make this work.

---
Tags: xbox360, node.js, playstation3, playstation4
---


title: MonoGame 3.3 Font loading

text:
# Question
Title: MonoGame 3.3 Font loading
Is there any way to have fonts in game without making a separate Content Project and adding a .spritefont file in the new 3.3 Monogame? You can now load other resources directly from the Content folder but not spritefonts...

# Answer
> 10 votes
I found out that the Content.mcgb is actually a little GUI helper and you can generate and easily load a .spritefont file with it.

Steps:

1.Load the GUI app by double clicking the "Content.mcgb" file in the "Content" folder

2.Go to Edit -\> New Item... -\> Choose SpriteFont and give it a name -\> Hit "Ok"

3.Go to Build -\> Build (or hit F6) - You should get some info on the font getting built

4.Load the .spritefont file in VS (Right-click the projct -\> Add -\> Existing Item -\> Choose the newly created file)

# Answer
> -2 votes
Incidentally, if you use MonoGame 3.3, you can just add a new SpriteFont to the MonoGame Pipeline and it works automatically :)

---
Tags: xna, c#, monogame
---