# Question
Title: Back button press on Windows Phone 8.1 Monogame
I am developing a simple game for windows phone and I got stuck when at the handling the back button press.

I have been searching for a while on google but I have not found anything that could work for me. I have seen a function GamePad but i couldn't find on which namespace is this function located, and if it is working on WP8.1.

So my question is, how can I set up a function in which I can handle some code when user press back button.

Thanks.

# Answer
I too couldn't wrap my head around this, as there is no mention of it in the documentation whatsoever. I also tried every single thing I could google and in the end, I figured it out by chance.

It's quite simple, really:

```
GamePadState padState = GamePad.GetState(PlayerIndex.One);
if (padState.Buttons.Back == ButtonState.Pressed) {
    // Do your stuff
}

```

**BUT!**

I had some major issues with it for what appeared to be two incomprehensibly related reasons: firstly, be sure to call this in your update as soon as you can. Calling it on the end of my update method made it work only *sometimes* (probably for some other reason, but I couldn't figure it out).

And secondly, keep one global instance of `GamePadState`for use in all classes that might have some control logic - I had two classes that registered control (with their own `GamePadState` instances) and while one did register the back button, the other didn't - and when I "paused" the update of the first one, the second one started to register it. Beats me.
> 0 votes

---
Tags: monogame, windows-phone-8
---


title: 2D Collision Detection XNA C#

text:
# Question
Title: 2D Collision Detection XNA C#
I've read all around the net, watched videos, tried things and in the end I can't make a decent platform collision detection.

I've followed this tutorial.

It didn't work out at 100%. My object stops above ground and can't hit the ground. Anyway, I think the guy got fed up with me asking questions. And his way seems too complicated. In short it's about constant calculations how far are you from a wall/ground and how much steps can you make("step" is also defined), how much DID you make, etc. Too complicated if you ask me. So let's forget about that.

I began anew on my own. Here's what I got:

```
private void ApplyCollision()
    {
        if (PlayerIsOnPlatform())
        {
            this.Position -= new Vector2(0, 5);  // Holds Player on platform.
        }
    }

private bool PlayerIsOnPlatform()
    {
        int playerBottom = this.Bounds.Bottom;
        int platformTop = Platform.CurrentPlatform.Bounds.Top;
        bool playerIntersectsPlatform =
            this.Bounds.Intersects(Platform.CurrentPlatform.Bounds);

        if ((playerBottom >= platformTop) && (playerIntersectsPlatform))
        {
            return true;
        }
        return false;
    }

```

And gravity and friction:

```
private void Friction()
    {
        Movement -= Movement * new Vector2(.1f, .1f);
    }

private void Gravity()
    {
        Movement += Vector2.UnitY * .5f;
    }

```

Like this, the player bounces a bit and stays about a pixel above ground. And the gravity is always trying to pin the object down even when I somehow manage to land on the platform.

=======

**EDIT:**

The player stops at the platform top correctly. But now I have another problem:

```
private void ApplyCollision()
    {
        // Object is above
        if (playerBottom > platformTop && playerBottom < platformBottom && playerIntersectsPlatform)
        {
            this.Position = new Vector2(currentPlayerPosX, platformTop - playerHeight);
        }
        // Object below
        else if (playerTop < platformBottom && playerTop > platformTop && playerIntersectsPlatform)
        {
            this.Position = new Vector2(currentPlayerPosX, platformBottom);
        }
        // Object to the left !! Conflicts with Vertical detection
        if (playerLeft < platformLeft && playerRight > platformLeft && playerIntersectsPlatform &&
            this.Bounds.Center.X <= platformLeft) // Not perfect
        {
            this.Position = new Vector2(platformLeft - playerWidth, currentPlayerPosY);
        }
        // Object to the right !! Conflicts with Vertical detection
        else if (playerRight > platformRight && playerLeft < platformRight && playerIntersectsPlatform)
        {
            this.Position = new Vector2(platformRight, currentPlayerPosY);
        }
    }

```

This methods works. It's shorter, better and doesn't need my initial boolean methods I had for top, bottom, sides check. But the Left and Right checks still need work. When the player is near the Platform border, he gets pushed/teleported off the edge. The Left check actually allows half of the Player to go off the edge without falling instantly - thanks to `this.Bounds.Center.X <= platformLeft`. Not perfect. Here's a picture to illustrate the problem:

I know why this is happening. It's due to the conditions in the if statements. I guess this calls for collision depth calculation. I find Jon's implementation kinda confusing. And I wonder if that's the only solution. I tried adding another condition. Pseudocode for left check: `if 1/4 of Player.Width <= platformLeft >THEN> this.Position = new Vector2(platformLeft - playerWidth, currentPlayerPosY);` But due to the friction and speed I have, it doesn't work.

# Answer
The

```
if (PlayerIsOnPlatform())
{
    this.Position -= new Vector2(0, 5);  // Holds Player on platform.
}

```

is innocorrect. You need to calculate the depth penetration. IE: Calculate how far the player intercepted the other item. XNA has a method for this that returns the rectangle formed when two rectangles intersect. It returns the purple rectangle in this picture:

```
Rectangle collisionRect = Rectangle.Intersects(player.Rect, platform.Rect);
if(intersection.Height > 0)
{
    player.Rect -= intersection.Height;
}

```

This will push the player outside the other rectangle. Depending on how you programmed gravity it might create a jittery effect on the player where he falls, gets pushed back up, falls, gets pushed back up, falls, etc. To fix this you need to simulate (everything, particularly gravity) and THEN push back up, then draw.

Edit: If you want to check the bounds yourself. These you will have to think about carefully. I think I got them all right.

```
if(player.Bottom > platform.Top && player.Bottom < platform.Bottom) // Object is above
    player.Rect.Pos += new Vector2(0, platform.Top - player.Bottom);
else if(player.Top < platform.Bottom && player.Top > platform.Top) // Object below
    player.Rect.Pos += new Vector2(0, platform.Bottom - player.Top);
if(player.Left < platform.Right && player.Left > platform.Left) // Object to the left
    player.Rect.Pos += new Vector2(platform.Right - player.Left, 0);
else if(player.Right > platform.Left && player.Right < platform.Right) // Object to the right
    player.Rect.Pos += new Vector2(platform.Left - player.Right, 0);

```
> 1 votes

# Answer
I figured I'd come in and explain to you how I used to do my Rectangle collisions in XNA/Monogame. Firstly, I declare an enum that will serve as a way to indicate what axis we are going to be working with. This is important, as our calculations will be done one axis at a time.

```
public enum Direction
{
    Horizontal,
    Vertical
}

```

You will also need a function that can determine if two Rectangles are intersecting, and if they are, you are going to want to know how deep this intersection is. The depth will be important when we get to collision response.

The below functions, will do these calculations for you.

```
// A helper function for the next two
public static bool Intersects(Rectangle player, Rectangle block, Direction direction, out Vector2 depth)
{
    if (direction == Direction.Vertical)
        depth =  new Vector2(0, GetVerticalIntersectionDepth(player, block));
    else
        depth = new Vector2(GetHorizontalIntersectionDepth(player, block), 0);

    return depth.Y != 0 || depth.X != 0;
}

public static float GetHorizontalIntersectionDepth(Rectangle rectA, Rectangle rectB)
{
    // Calculate half sizes.
    float halfWidthA = rectA.Width / 2.0f;
    float halfWidthB = rectB.Width / 2.0f;

    // Calculate centers.
    float centerA = rectA.Left + halfWidthA;
    float centerB = rectB.Left + halfWidthB;

    // Calculate current and minimum-non-intersecting distances between centers.
    float distanceX = centerA - centerB;
    float minDistanceX = halfWidthA + halfWidthB;

    // If we are not intersecting at all, return (0, 0).
    if (Math.Abs(distanceX) >= minDistanceX)
        return 0f;

    // Calculate and return intersection depths.
    return distanceX > 0 ? minDistanceX - distanceX : -minDistanceX - distanceX;
}

public static float GetVerticalIntersectionDepth(Rectangle rectA, Rectangle rectB)
{
    // Calculate half sizes.
    float halfHeightA = rectA.Height / 2.0f;
    float halfHeightB = rectB.Height / 2.0f;

    // Calculate centers.
    float centerA = rectA.Top + halfHeightA;
    float centerB = rectB.Top + halfHeightB;

    // Calculate current and minimum-non-intersecting distances between centers.
    float distanceY = centerA - centerB;
    float minDistanceY = halfHeightA + halfHeightB;

    // If we are not intersecting at all, return (0, 0).
    if (Math.Abs(distanceY) >= minDistanceY)
        return 0f;

    // Calculate and return intersection depths.
    return distanceY > 0 ? minDistanceY - distanceY : -minDistanceY - distanceY;
}

```

Now, in your player class (or whatever class you want to have collisions check done in, you would utilize these above functions, in order to check for collisions, and then handle its response.

The following function will take a direction, and calculate to see if you need to provide a collision response or not.

```
private void CheckCollisions(Direction direction)
{
    //Get a list of objects to test against
    //You probably already have a mechanism for this
    List<Tile> tiles = quadtree.GetObjects(this.Rectangle);

    //Loop and check for collisions on these objects
    for (int i = 0; i < tiles.Count; i++)
    {
        if (!tiles[i].Collidable) continue;

        //Calculate intersection depth
        Vector2 depth;
        if (Intersects(this.Rectangle, tiles[i].Rectangle, direction, out depth))
        {
            //If an intersection was found - adjust position
            Position += depth;

            //Adjust velocity based on intersection direction
            if (direction == Direction.Horizontal)
                Velocity.Y = 0;
            else
                Velocity.X = 0;
        }
    }
}

```

Then finally, in your Update method, you will re-position and check for your collisions one axis at a time.

```
public void Update(GameTime gametime)
{
    float elapsed = (float)gameTime.ElapsedGameTime.TotalSeconds;

    //Velocity Calcs
    Velocity = new Vector2(100, 50);

    //Update one axis at a time
    this.Position.Y += Velocity.Y * elapsed;
    CheckCollisions(Direction.Vertical);

    this.Position.X += Velocity.X * elapsed;
    CheckCollisions(Direction.Horizontal);
}

```

Hopefully this will help you, or someone else, having similar issues like this.
> 1 votes

---
Tags: xna, c#, collision-detection
---


# Question
Title: Finding enemy object in player's forward direction within a range
I would like to know the way by which I can find enemy objects tagged with "player" in a forward direction within a range say 3 units from the player.

# Answer
What you need is to cast a raycast forward like this: \`

```
     Raycast hit;
     Vector3 fwd = transform.TransformDirection (Vector3.forward);
     if(Physics.Raycast(transform.position, fwd, out hit, RANGE)){
         if(hit.collider.tag == "Player"){
            ...
         }

```

\` RANGE = max range eg.3
> 0 votes

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


# Question
Title: computer science or software engineering for game development?
I know this question is asked frequently, but I need your opinion on it to choose my path. I want to work in the game development. I know going to school isn't required to become a game developer. I'm trying to learn by myself, but without someone to help me or to guide me, it's useless. I hate learning by listenning videos...

Is software engineering worth it or it's a waste of time? I have watched the course curriculum and all the courses of computer science are in. Seems like software engineering is like computer science but with more knowledge. Those extra courses would be usefull or not. Both are offered with the computer games option thats really nice.

Also, for engineering I need one more year of school because I need physic and chimestry x.x and computer science is only 3 years. Does software engineering really worth 2 years of my life -.- ?

# Answer
If you're interested in building/refining 3D game engines with realistic physics, then this more intensive software engineering program you've described *might* be worth the extra time and effort. Then again, computer science programs are generally sufficient (many institutions don't make a distinction between "computer science" and "software engineering"). If you're primarily interested in scripting and level design, computer science will more than suffice. So, it may depend on the *specifics* of what you want to do, but whichever program you choose, you should be able to land a relevant job eventually so long as you're diligently learning and practicing in the specific area of game development that interests you most.
> 0 votes

---
Tags: education
---


title: Game server/client like wordfeud

text:
# Question
Title: Game server/client like wordfeud
My friends and I are creating a game for mobile platforms. We are now in the phase of creating the multiplayer part of the game.

We know how to do it but we are not sure how the multiplayer should work. Our game is turn-based, so if we would do something like Wordfeud. Where there is a time limit.

How could we be certain that \[User2\] knows that \[User1\] has ended his turn if lets say \[User2\] has his phone turned off.

Should we let the server control this time limit or should we let the client count for itself?

# Answer
You should store all the state and place all the logic on the server (never trust any data coming from the client!).

In my opinion the best way to do it would be keep track of when User1 ends its turn, and in that moment send a push notification to User2. Then, whenever User2 opens the app, to retrieve the current game info it will need to send a request to your server, so store that time in your server and keep also a timer locally.

If User2 is a "normal user" and its local timer runs out, your app should notify the server. But he is a cheater and sends a fake petition manually after the local timer has ended, your server should check against the stored time to see if his timer is really running.
> 1 votes

---
Tags: networking, client-server
---


title: How do I combine two HTML levels?

text:
# Question
Title: How do I combine two HTML levels?
If I have two levels that I have made separate in HTML5 how may I combine them so one comes after another?.

# Answer
If you mean that they are in several .html files you can simply call

```
window.location = "level2.html"

```

when the player ends the first level.

Also: You should consider that if you are playing the game from a browser (not on a packaged app), many server requests will happen between the levels so it won't be an optimal user experience. If you are still learning is fine to do it the "crappy" way, but eventually you game will be big enough that this will be unbearable.

If you are using HTML5 canvas I would suggest placing two canvas on your HTML file and "swap" them (make the first one invisible and the second one visible, it is just some css). If you are planning to create many levels, I would suggest you to design your game so you can place everything in one .html file and use just one canvas, even if you keep different .js files.
> 2 votes

---
Tags: javascript, html5, html
---


# Question
Title: Sphere Texture Mapping shows visible seams
As you can see from the above picture there is a visible seam in the texture mapping. The underlying mesh is a geosphere based on octahedron subdivisions. On that particular latitude, vertices have been duplicated. However there still is a visible seam.

Here is how I calculate the UV coordinates:

```
float longitude = (float)Math.Atan2(normal.X, -normal.Z);
float latitude = (float)Math.Acos(normal.Y);

float u = (float)(longitude / (Math.PI * 2.0) + 0.5);
float v = (float)(latitude / Math.PI);

```

Is this a problem in the coordinates or a mipmapping issue?

**Edit:** the GeoSphere is generated using SharpDX's Toolkit code. My SamplerState is set to Clamp. Further, I am using a normal mapping shader.

Could it be that the tangent of the duplicated vertices needs to be altered? I am using a Vector4 element for it, where w is the handedness. If so, how should it be modified?

**Edit2:** this is the code used to duplicate the vertices along the seam

```
int preCount = vertices.Count;
var indicesArray = indexList.ToArray();
fixed (void* pIndices = indicesArray)
{
    indices = (int*)pIndices;

    for (int i = 0; i < preCount; ++i)
    {
        // This vertex is on the prime meridian if position.x and texcoord.u are both zero (allowing for small epsilon).
        bool isOnPrimeMeridian = MathUtil.WithinEpsilon(vertices[i].Position.X, 0, XMVectorSplatEpsilon)
                                 && MathUtil.WithinEpsilon(vertices[i].TextureCoordinate.X, 0, XMVectorSplatEpsilon);

        if (isOnPrimeMeridian)
        {
            int newIndex = vertices.Count;

            // copy this vertex, correct the texture coordinate, and add the vertex
            VertexPositionNormalTexture v = vertices[i];
            v.TextureCoordinate.X = 1.0f;
            vertices.Add(v);

            // Now find all the triangles which contain this vertex and update them if necessary
            for (int j = 0; j < indexList.Count; j += 3)
            {
                var triIndex0 = &indices[j + 0];
                var triIndex1 = &indices[j + 1];
                var triIndex2 = &indices[j + 2];

                if (*triIndex0 == i)
                {
                    // nothing; just keep going
                }
                else if (*triIndex1 == i)
                {
                    Utilities.Swap(ref *triIndex0, ref *triIndex1);
                    Utilities.Swap(ref *triIndex1, ref *triIndex2);
                }
                else if (*triIndex2 == i)
                {
                    Utilities.Swap(ref *triIndex0, ref *triIndex2);
                    Utilities.Swap(ref *triIndex1, ref *triIndex2);
                }
                else
                {
                    // this triangle doesn't use the vertex we're interested in
                    continue;
                }

                // check the other two vertices to see if we might need to fix this triangle
                if (Math.Abs(vertices[*triIndex0].TextureCoordinate.X - vertices[*triIndex1].TextureCoordinate.X) > 0.5f ||
                    Math.Abs(vertices[*triIndex0].TextureCoordinate.X - vertices[*triIndex2].TextureCoordinate.X) > 0.5f)
                {
                    // yep; replace the specified index to point to the new, corrected vertex
                    indices[j + 0] = newIndex;
                }
            }
        }
    }

    FixPole(northPoleIndex);
    FixPole(southPoleIndex);

    // Clear indices as it will not be accessible outside the fixed statement
    indices = (int*)0;
}

```

# Answer
> 1 votes
This problem may be related to mipmapping. The pixels along the edge are being mapped to a much more copressed LOD than the rest of the sphere, so the entire map is actually being compressed into that line.

You may try putting in a tex2Dlod call in the shader and forcing the LOD to 0:

```
return tex2Dlod(TextureSampler, float4(u, v, 0, 0));

```

Explanation and possible solution for this over was found on stackoverflow: https://stackoverflow.com/questions/19723698/sphere-texture-mapping-error

---
Tags: textures, hlsl, uv-mapping
---


# Question
Title: Creating HTML5 Canvas Objects in Javascript
I'm currently trying to learn how to make HTML5 Canvas games with JavaScript. I would like to use object oriented JavaScript to manage the elements of the game, but i'm having trouble. I've done a lot of research already, but there seems to be a million ways of doing everything and no one source has been able to provide me with the information I think I need in order to get the result I think I want. More specifically I'm having trouble utilizing object prototypes. I've started out by creating the canvas in my code like so

```
var body = document.getElementsByTagName("body")[0];
var canvas = document.createElement('canvas');
body.appendChild(canvas);

```

My thought process has lead me to thinking that I should make an object out of this so I can use this dynamically later on if needed. So i've implemented it like so.

```
var gamearea = function(){
this.generate = function(){
  var body = document.getElementsByTagName("body")[0];
  var canvas = document.createElement('canvas');
  body.appendChild(canvas);
}

```

I know that I will probably need multiple contexts of the canvas element going forward, so I'm thinking that I should create a prototype for this like so.

```
var context = function() {
  return canvas.getContext('2d');
}

```

My thinking is that I can then ceate the objects for the context I need by instating them with there prototypes like so.

```
var background = Object.create(context);
var foreground = Object.create(context);

```

But in order to assign IDs to these objects so I can reference them for drawing on later, I need to assign IDs to them. I found a blog that indicated the proper formatting would mean implementing the following.

```
var background = Object.create(context, {id: {value: 'background'} });
var foreground = Object.create(context, {id: {value: 'foreground'} });

```

So my question is this. Is there a way to incorporate more unified formatting to all of this? Id like to establish this prototypes with their id's beforehand like I did with the gamearea object. I want to avoid giving objects properties inline. I am doing this right? Is there a better way? I'm I a complete idiot?

Thank you very much for your time on this guys, I really appreciate it. :)

# Answer
> 0 votes
Honestly I think you are creating problems out of nowhere :)

**About the gamearea.generate function:**

If I understand what you are trying it do, shouldn't it return "canvas" so you have a way to reference it later.

**About the context function:**

You will only need one context. Read the answer of this question: https://stackoverflow.com/questions/8417318/html-canvas-multiple-getcontext-plotting-at-same-time You only need (and can create) one context per canvas. You have two options: either your code should keep track of the "layers" and draw everything in order (I have a library that does that, I would recommend you have a look at code: http://spritesheet.js.org/), or create many canvas, each one with its context, and draw one layer in each one.

Also, I think you may not understand protypical-inheritance and JS "constructors" completely. `Object.create(context);` would only return a function that inherits from context, to get a context you only need to call it: ´var background = context();´. Also, it would return the same context on each call, you would need to specify the canvas as a parameter to make it reusable.

**About the ids:**

I think you are inventing a very complicated way to do it. If I'm right, you want to test if

`x.id.value === "whatever"`

I think you should consider: what is x? x would be the background variable, so... you already know that this is the background. Instead of storing the id inside the object, do it the other way around: link the reference to the object to the value. From example, you could create an object and use it as a hash table:

```
var layers={};
//Store the contexts
layers["background"]=somecontext;
layers["foreground"]=someothercontext;
//Retrieve a context by its id
function getContext(id) {
  Return layers[id];
}
getContext("background");//Would return somecontext

```

I think your problem is not the canvas and context itself, but some lack of JavaScript basic knowledge and design patterns. I would recommend to you reading a good JS book like "JS: The good parts" or read some real-world code (not just DOM manipulation, real application code) and have a look at the design patterns used :)

---
Tags: javascript, html-canvas, objects, prototyping
---


# Question
Title: Pass-through pixel shader not displaying properly
I'm new to shaders, HLSL and XNA in general. I'm trying to write a pass-through pixel shader but I'm experiencing some odd behaviour. I created a simple texture, shown below:

Here's what I see when I run my game:

Drawing the texture without passing `effect` in `spriteBatch.Begin()` works fine, for instance:

Drawing the texture at (40, 10) instead of (0, 0) gives different results, too (the green stripe isn't as thick):

My shader file:

```
sampler input;

float4 PixelShaderFunction(float2 coords: TEXCOORD0) : COLOR0
{
    float4 color = tex2D(input, coords);
    return color;
}

technique Technique1
{
    pass Pass1
    {
        PixelShader = compile ps_4_0_level_9_1 PixelShaderFunction();
    }
}

```

My game code:

```
public class Game1 : Game
{
    GraphicsDeviceManager graphics;
    SpriteBatch spriteBatch;
    Texture2D tex;
    Effect effect;

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

    protected override void Initialize()
    {
        base.Initialize();
    }

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

        tex = Content.Load<Texture2D>("tex");
        effect = Content.Load<Effect>("effect");
    }

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

        base.Update(gameTime);
    }

    protected override void Draw(GameTime gameTime)
    {
        GraphicsDevice.Clear(Color.CornflowerBlue);

        spriteBatch.Begin(sortMode: SpriteSortMode.Immediate, effect: effect);
        spriteBatch.Draw(tex, new Vector2(0, 0), Color.White);
        spriteBatch.End();

        base.Draw(gameTime);
    }
}

```

What am I doing wrong? I'm expecting my pass-through shader to simply draw the texture on the screen as-is (appearing as in the second screenshot above), but it looks totally wrong. (For what it's worth, I was trying to follow this tutorial: http://blog.josack.com/2011/07/my-first-2d-pixel-shaders-part-1.html)

# Answer
Since you override SpriteBatch's default effect with your own, you are now responsible for setting effect parameters, especially matrices. You probably would like to replicate default SpriteBatch behaviour, so set `effect.World` to identity, and for projection default SpriteBatch effect uses `effect.Projection = Matrix.CreateTranslation(-0.5f, -0.5f, 0) * Matrix.CreateOrthographicOffCenter(0, GraphicsDevice.Viewport.Width, GraphicsDevice.Viewport.Height, 0, 0, 1);`
> 1 votes

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


title: RPG hit/miss formula

text:
# Question
Title: RPG hit/miss formula
Ive been developing an RPG for sometime, and its far enough now where I need to get some formulas down for attacking and whatnot. What Im looking to understand is a basic hit and miss formula based on dexterity or another stat. If someone can give me a basic framework to modify and extend, or helpful pointers, Id be appreciative.

# Answer
The formulas that you define *are* the game design for your game. You can specify whatever it is you want it to be.

You would probably do something like define a "base" hit rate based on your level compared to the enemy's level. Maybe have weapon expertise play a role (if that's a stat in your game). That kind of thing.

But if you want an example to work from, there are a lot of pages of people doing things like deconstructing the internal formulas in World of Warcraft. Like this one, for example: http://www.wowwiki.com/Hit
> 9 votes

# Answer
Here is a page with an equation to determine attack skill for Everquest. You may wish to follow the links on that page to other parts of the hit/miss/damage formulas. The formula has gotten very complicated over the years as the developers have added items that give bonuses to many of the secondary stats.
> 1 votes

# Answer
Mmmhh I hope I can help with the first thing that get's into my mind, and is something like this: I have an agility, that represents my characters ability to evade an attack. Then, in the other hand, I could have a dexterity or skill, or wathever status you would use to represent my character ability to succesfully hit an oponent. So, if I would like to keep things the most simple as possible, I'd say, well, if my ability to dodge is the same as your ability to hit, then, probably you would hit me the 50% of the times. That I think, would be my starting point. (I want to make clear that you would probably never hit me, but, that's not fun, at least not for games.) Right now I cannot think about hitting without necessarily knowing about my opponent's agility, cause, every case would be different, depending on what kind of enemy Im gonna hit., but, if your agility are same as my dexterity, I know you would hit me at least 1 of 2, and, if you are as twice as skillfull as me, I know you would surely hit me. Let us start with that premise in our minds.

Let's say that I have 12 dex., and I'm gonna hit you. You have 8 Agi. That said, I should have a good chance to hit you. So...using rule of three...

(Your agi) If 8x2 (16)----represents---100% chance I hit you. (I have to be at least two times as skillfull as you to hit you fure sure)

Then 12-----represents--- ((12\*100) / 16) = 75% chance I hit you. That said, your chance to dodge me would be like 25% (Or chance that I miss)

75% and 25% are what it is for us, certain. But it does not end here, cause, well, those are chances, and you could still avoid my attack if I hit you, in spite you being weaker.

So we can add an extra random chance, to what for us is certain. I would do something like:

```
If((MyCharacter.CalculateChanceToHit(MyEnemy.GetAgi()) + (Usefullthings.GetRandomChance())) >
(MyEnemy.CalculateChanceToAvoid(MyCharacter.GetDex()) +(Usefullthings.GetRandomChance()))
{
  Hit(MyEnemy.getStatus)
}
Else
{
  MyEnemy.Dodge() /** Animate your enemy dodgin' like a pro.
}

```

Where Calculate chance to hit and avoid returns the result chance of that happening(three simple rule) and getrandomchance is just a function that may return any percent from 0 to 100, or 0 to 50, or whatever you like. Good thing is that, Getrandomchance gives you some control of what amount of "Lucky" you want to add to the game when chances are not on your side, and thinking a litlle bit too deep, you would have to try it several times to get what you think would be more "Fair". Its not cool that, If you have a more powerfull character, I got to avoid you many times, since it would seem like the "Certain" chance It's not really there. Im not a game developer but I think that would be enough, at least for a simple game., I guess you could add Some other chances like when you wear a weapon, I would make lances more reliable to hit somebody than a knife. Just a thought.
> 0 votes

---
Tags: rpg
---


# Question
Title: Heightmap, how can i prevent bad odd numbers
I am building my world-editor for my game. I've noticed, that, no matter how i implement the heightmap, i'll end up with dumb odd numbers in calculations.

For example, lets take a HeightMap of 4x4 which covers a area of 2x2 OpenGL-Units. Thats a small image which shows the problem. The **black** lines and numbers represent units in OpenGL, the **red** lines and numbers repesent pixel/values on my heightmap.

You can easily see, that in the top image, every number is really odd and i actually need a lot of additional code to calculate everything correctly (OpenGL-position -\> heightmap-pixel and heightmap-pixel -\> OpenGL-position).

In the bottom image however, i am missing height-values for the right and the bottom row of vertices.

I thought i could just use +1 pixel for every heightmap, this would solve this problem but i am sure it will introduce problems at other ends.

How would you guys handle this?

---

As stated in the comments, the real problem here is, that i need to calculate OpenGL-position -\> heightmap-position and OpenGL-range -\> heightmap-range fairly often to *draw* on the heightmap and the math gets really hard to handle with the mapping as seen in the top-image.

# Answer
> 1 votes
Don't think in World Units -\> Heightmap. Think in World Units -\> Model Units -\> Heightmap. This is called normalization.

You will need to normalize from world units back to your model units *before* you try to map to the heightmap and vice versa. You can do this with some simple scale-factor, assuming that the vertices in your terrain mesh are uniform distance of 1 unit apart from each other.

Lets say you have a terrain mesh that is 100x100 vertices and a height-map that is 100x100 pixels, but you want the terrain to be 257x257 units.

Now, when you are painting with the terrain brush, you will find the world coords from your mouse position, then scale that position back down to your model units, so you get a 1:1 mapping with your height-map.

In this example, the model scale is 100units but the world scale is 257units, so that is a scale factor of 2.57

Let's say that you click on the position at {183,183,z} in world units. So divide by 2.57 and you get 71.206226... rounded, that would be vertex\[71\]\[71\] (but don't round yet).

You will need to do this for the brush size as well, if the brush size is 3 world units in diameter, then divide by 2.57 and you get a model unit size of 1.167315... for your brush diameter. Knowing this, you can work on the vertices and pixels within a radius of (1.167315/2.0) from {71.206226, 71.206226}. If your brush were square, that would be {70.622568, 70.622568} to {71.789884, 71.789884}

Once you determine the bounds of your brush in model units, then you round to integer so you can index the vertices or heightmap.

Hope that helps.

---
Tags: heightmap
---


# Question
Title: LibGdx TextButtonStyle Offset not working correctly
I'm intending to give an animation to the `TextButton` by giving the `pressedOffsetX` and `pressedOffsetY` values:

```
TextButtonStyle buttonStyle = new TextButtonStyle();
buttonStyle.font = font25;
buttonStyle.fontColor = Color.WHITE;
buttonStyle.up = new TextureRegionDrawable(settingsAtlas.findRegion("achievements"));
buttonStyle.down = new TextureRegionDrawable(settingsAtlas.findRegion("achievements"));
buttonStyle.pressedOffsetX = 5;
buttonStyle.pressedOffsetY = -5;

```

And I created a button like this:

```
TextButton achievementsButton = new TextButton("ACHIEVEMENTS", buttonStyle);
achievementsButton.addListener(new ChangeListener() {
    @Override
    public void changed(ChangeEvent event, Actor actor) {
        // show achievements
    }
});

```

But when I click the button, only the text in it is animated. The button background stays in the same position. What might I be doing wrong here?

# Answer
As the comment says offset only effects the children, i.e the text inside the button.

What you need to look at is this piece of code:

```
buttonStyle.up = new TextureRegionDrawable(settingsAtlas.findRegion("achievements"));
buttonStyle.down = new TextureRegionDrawable(settingsAtlas.findRegion("achievements"));

```

Since you set the same image for `up` and `down` you wont see any change on the actual button when you click it. You need to change `down` to whatever color or image you want to show on click, giving it an animation effect.

If you want the actual button to 2move" like the text inside it, well I don't think libdx has any built in methods for that.
> 1 votes

# Answer
Sorry yesterday I was a wreck :) but I just found a solution for you. Simply build up the button yourself... lol, I cannot believe I didn't think of that yesterday?

```
Button button = new Button();
        button.setDebug(true);
        Button.ButtonStyle style = new Button.ButtonStyle();
        style.pressedOffsetX = 100;
        Label label = new Label("Touch me!", skin);
        button.add(label);
        button.setStyle(style);

        button.addListener(new ClickListener()
        {
            @Override
            public void clicked(InputEvent event, float x, float y)
            {
                System.out.println("I moved with label background and text of label");
            }
        });

        table.add(button);

```

You can add any actor you want to the button since it's actually a table with a click state. Anything within the button should be offset and thus you can put a label with background like I did, a stack with an image and label on top or even multiple tables inside the button.

So in your case you just need to setup a label with your text and use your achievements region as the background or seperate image. Put those in your custom made button and you are set.
> 0 votes

---
Tags: libgdx, animation, gui
---


title: Game Sprite Motion

text:
# Question
Title: Game Sprite Motion
I really like the effect that I see in this video of Mario Party 10 Jewel Drop (at 2:40). It occurs when the four green orbs join together. You'll see a four items with long trails move to the top left of the screen quickly. What is the "science" behind the acceleration of these particles? Are there any resources that I can be directed to that discuss animation with UI? Thanks in advance.

**EDIT**
This is based on the answer provided @Felsir.

```
#import "GameScene.h"

@implementation GameScene

-(void)didMoveToView:(SKView *)view {
    SKSpriteNode *ship = [[SKSpriteNode alloc] initWithImageNamed:@"Spaceship"];
    [ship setScale:0.2];
    [ship setPosition:CGPointMake(50, 300)];
    [self addChild:ship];

    CGPoint end = CGPointMake(500, 500);
    CGPoint ctrlB = CGPointMake(300, -100);
    CGPoint ctrlA = CGPointMake(400, 250);
    SKAction *fly = [SKAction customActionWithDuration:2 actionBlock:^(SKNode *node, CGFloat elapsedTime){
        node.position = [self bezierWithPointA:node.position B:ctrlA C:ctrlB D:end amount:elapsedTime];
        NSLog(@"position = (%f, %f)", node.position);
    }];
    [ship runAction:fly];
}

-(void)update:(CFTimeInterval)currentTime {

}

-(CGPoint) bezierWithPointA:(CGPoint)pointA B:(CGPoint)pointB C:(CGPoint)pointC D:(CGPoint)pointD amount:(float)amount {
    CGPoint ab, bc, cd, abbc, bccd;
    ab = [self linearInterpolationBetweenPointA:pointA pointB:pointB amount:amount];
    bc = [self linearInterpolationBetweenPointA:pointB pointB:pointC amount:amount];
    cd = [self linearInterpolationBetweenPointA:pointC pointB:pointD amount:amount];
    abbc = [self linearInterpolationBetweenPointA:ab pointB:bc amount:amount];
    bccd = [self linearInterpolationBetweenPointA:bc pointB:cd amount:amount];
    return [self linearInterpolationBetweenPointA:abbc pointB:bccd     amount:amount];
}

-(CGPoint) linearInterpolationBetweenPointA:(CGPoint)pointA pointB:(CGPoint)pointB amount:(float)amount {
    CGPoint newPoint = CGPointMake(pointA.x + (pointB.x - pointA.x)*amount, pointA.y + (pointB.y - pointA.y)*amount);
    return newPoint;
}

@end

```

# Answer
The trajectory of the particles is a Bézier curve. A Bézier curve is a smooth curve along four points:

pointA: startpoint pointB: startdirection+acceleration pointC: enddirection+accelleration pointD: endpoint

Basically it generates a curve through from point A to point D, using the vectors towards A-B and C-D to determine the path.

See C# (Monogame) code example:

```
public static Vector2 bezier(Vector2 pointA, Vector2 pointB, Vector2 pointC, Vector2 pointD, float t)
{
    Vector2 ab, bc, cd, abbc, bccd;
    ab = Vector2.Lerp(pointA, pointB, t);
    bc = Vector2.Lerp(pointB, pointC, t);
    cd = Vector2.Lerp(pointC, pointD, t);
    abbc = Vector2.Lerp(ab, bc, t);
    bccd = Vector2.Lerp(bc, cd, t);
    return Vector2.Lerp(abbc, bccd, t);
}

```

The path is defined by the 4 points and float `t` from `0f`-`1.0f`. Note that due to the nature of the curve, the speedup and slowdown come with the curve.

For the effect, sparkles spawn along the path of the curve. The sparkles themselves could be regular particles that have their own behaviours.
> 1 votes

---
Tags: physics, animation, spritekit, ui-design
---


# Question
Title: is there a formula to know how many enemies i can place before jumping character?
My game is very similar to the hidden game in chromes web browser. I have a character that needs to jump over incoming enemies. Is there any way i can know when to send an incoming enemy? Some of the factors to take in to account i guess are the speed of enemies, height of jump, speed of jump, and dimensions of bitmaps (that represent character, and enemies).

Thanks

# Answer
Something as simple as this would give you the rough time the player will have to react if you were to spawn an enemy right now.

```
minReactionTime = 0.5; //Give the player half a second to react
closingSpeed = enemySpeed + playerSpeed;

if ( (enemySpawn - playerPosition) / closingSpeed >= minReactionTime )
{
   spawnEnemy();
}

```
> 1 votes

---
Tags: android, game-design, game-mechanics
---


# Question
Title: Should I pass my resource manager to types that might need it, or make it global?
Say I have this `Cache<typename Resource>` class template, which is a resource cache that contains an `std::map<std::string, Resource>`, mapping strings to resources.

I can many different kinds of resources: sounds, textures, geometry etc. So I need to have something like a container of all of these caches:

```
struct ResourceManager {
  Cache<Sound*> _soundCache;
  Cache<Mesh*> _meshCache;
  Cache<Texture2D> _textureCache;
};

```

A Mesh object might need to query Texture objects from the texture cache, so working with these caches is possible in two ways: Either pass a pointer to `_textureCache` to every Mesh object, perhaps via its constructor (this approach is pretty clumsy), or define a ResourceManager object globally, so every class can use its caches all the time.

Has this issue ever been brought up for discussion? How should I deal with it?

What do most engines do? Where do they store these caches? Is it viable to do something like this? :

```
~GameEngine.h~

...
#include "ResourceManager.h"

//global object
resourceManager g_resourceManager;

class GameEngine {
  ...
};

```

# Answer
Like most things in software development, the answer is "it depends". Only you will be able to decide which is the right approach because you have intimate knowledge of what you need to accomplish and whether it is worth the extra effort to make it right.

Properly designed, you might use both methods. Global anything in code is typically a bad idea. Though it should not and cannot be avoided entirely, anytime you find yourself considering something for being global, think it over carefully because it will implicitly tie things together, which most often leads to greater complications than explicit connections between your code.

It's always a good idea to limit the knowledge of one piece of code to another as much as possible. Even though it means more thought and more work up-front to connect things together and will be a bit more complicated to code your classes, it will simplify the use of those classes. It also helps to avoid problems later when you need to make changes to or reuse either part.

You want your code to be "plug 'n play" as much as possible. Compromises always have to be made though. It's a trade between get it done fast or get it done well.

See Coupling and Cohesion. Always try to aim for *low coupling* and *high cohesion*.

Sorry this is a round-about answer and I can't explain this in too much detail for you. It is a rather deep topic and will take quite a bit of experience making your own mistakes before you really get it. Just keep these things in mind.

To be more direct, if you have to ask then just make it work and don't worry about it too much. It seems like you already have a decent idea of how to make it work, so just go with it. Refactor it later to be better when you find there are issues with your current implementation. What most good engines do is evolve as needed. I don't expect you want to spend several years developing your engine to perfection before you produce your first game.
> 1 votes

# Answer
The simplest way is to pass STL shared pointers of resources around to your objects, it's fairly painless but hard to catch errors in and it's not particularly obvious what system/object owns the particular resource.

Personally I prefer the method of the resource system giving out handles, a handle (in this case) just something comprised an integer value that some other system can use to bind a texture, play a sound or bind a vertex buffer.

This blog post from Molecular Musings has some pretty good insight: https://molecularmusings.wordpress.com/2013/05/02/adventures-in-data-oriented-design-part-3a-ownership/
> 1 votes

---
Tags: architecture, resource-management
---


title: Unity 5.1 Asset bundle for windows

text:
# Question
Title: Unity 5.1 Asset bundle for windows
I am working on the asset bundle method, i know how to use the asset bundle for untiy 4.x series but i am trying to do this in unity5. I heard in unity 5 is more compatibility to do. I searched in youtube and google but i didnt get the proper tutorial to how to use that. So please suggest me or provide some tutorial to do this.

Thanks in Advance.

# Answer
So, Unity 5 has changed asset bundles quite a bit from what I can see(never used them in 4). In Unity 4, you had to push and pop asset bundle dependencies and gather a list of assets that will go into your bundle.

Unity 5 provides some editor support for asset bundles. Basically every asset that has an AssetImporter can be assigned an asset bundle using the editor. There's a small UI that helps you create new asset bundle names and assign them and their variants to an asset. First you select the asset in the editor, then at the very bottom of the inspector you should see where you can assign asset bundles. The UI is pretty self explanatory and pretty much the only thing about asset bundles in 5 that's decently documented, so I'll talk about the more complicated stuff.

So, once you assign all the assets you want an asset bundle, how do you build them? Well we have to do this in an editor script still:

```
public class BuildAssetBundles
{
    [MenuItem( "Assets/Build Asset Bundles" )]
    public static void ExecBuildAssetBundles()
    {
        BuildPipeline.BuildAssetBundles( "Path/To/Output/Folder", BuildAssetBundleOptions.None, BuildTarget.StandaloneWindows );
    }
}

```

And that's it. This will build all your bundles tagged in the editor and put each one's dependencies in the bundle with the same name as the output folder. We can specify some options here such as no compression, force rebuilds every time etc. The last parameter we give is the target platform. You should build asset bundles for each platform you release on. Only asset bundles that have changed are rebuilt when calling this method.

That's fine, but what if you want to set asset bundles in scripts? You have a couple of options:

```
public class BuildAssetBundles
{
            [MenuItem( "Assets/Build Asset Bundles" )]
    public static void ExecBuildAssetBundles()
    {
        var assetPath        = SomeMethodThatGetsAnAssetIWant();
        var assetImporter    = AssetImporter.GetAtPath( assetPath );

        // This will set the same tag we can edit through the editor.
        assetImporter.assetBundleName = "MyAssetBundleName";

        // Build all bundles with a valid assetBundleName on their importer.
        BuildPipeline.BuildAssetBundles( "Path/To/Output/Folder", BuildAssetBundleOptions.None, BuildTarget.StandaloneWindows );
    }
}

```

So this basically does what we did before except now we're changing our asset's bundle in code rather than the editor. This can be useful, but maybe not the best solution depending on what you're going for. Another option is the AssetBundleBuild struct that Unity provides:

```
public struct AssetBundleBuild
{
    public string     assetBundleName;
    public string     assetBundleVariant;
    public string[]   assetNames;
}

```

Using this data structure we can create asset bundles entirely in code:

```
var build = new AssetBundleBuild();
build.assetBundleName = "MyAssetBundle";

// NOTE: These must be paths to your assets relative to the project root.
// This will usually be one level above your assets folder.
build.assetNames      = new string[]{ "My", "Asset", "Paths" };

```

There we go. It's a bit annoying we have to specify paths instead of UnityEngine.Object references, but besides that it's pretty easy. So, how do we build this? We can't use the method we used before because that's for editor asset bundles. We can use an overload of that method though:

```
BuildPipeline.BuildAssetBundles( "Path/To/Ouput/Folder", new AssetBundleBuild[]{ My, AssetBundle, Build, Structs }, BuildAssetBundleOptions.None, BuildTarget.StandaloneWindows );

```

This will build our bundle structs. NOTE: dependencies will only be recorded within the same BuildAssetBundles call. This means if you use two calls to build two asset bundles, dependencies between them will not be considered. If things will have dependencies you have to build them in the same call, or make your own dependency file.

This should be enough to build your bundles. I haven't gone into too much detail regarding variants because I've never really used them. I know they're a way to have the same bundles( names and types must be identical ), but different assets. Think swapping out HD and SD UI textures without having to load different assets entirely.

Now that's done, let's load our asset bundles. All dependencies are stored in the manifest bundle. This bundle is named the same as our output folder, and is also stored in the output folder. Let's load that first:

```
public IEnumerator LoadAssetBundleManifest()
{
    // Let's load the manifest using the WWW class. We need to put File:// here
    // to specify that we're looking in the local file system( opposed to
    // a server or whatever. )
    using( WWW www = new WWW( "File:///" + outputPath + "/" + outputFolderName ) )
    {
        // Wait for download to finish.
        yield return www;

        // Check for an error. Bail out if there was one.
        if( !string.IsNullOrEmpty( www.error ) )
        {
            Debug.LogError( www.error );
            yield break;
        }

        // Load the manifest object from the bundle.
        var manifest = ( AssetBundleManifest )www.assetBundle.LoadAsset( "AssetBundleManifest" );

        // This will unload the asset bundle memory. That is, unloaded
        // objects from the asset bundle. This is probably compressed data
        // unless you specified otherwise. If you pass true to this method,
        // any loaded objects will also be deleted. If you don't they will
        // remain and it'll be your responsibility to clean up after the
        // bundle. We pass false here because we still want to use the
        // manifest object we just loaded.
        www.assetBundle.Unload( false );
    }
}

```

This gives us our manifest. What does the manifest do? Well it can tell us some things about our bundle build such as what depends on what, and what bundles were actually in the build.

http://docs.unity3d.com/ScriptReference/AssetBundleManifest.html

Also, pretty importantly, it gives us an asset bundle hash. This allows us to download a bundle only when it's been updated. The bundle will then be cached and used locally. This may not be so important if you're not planning on hosting your asset bundle on a server though.

So, now let's use our manifest to load an actual bundle:

```
public IEnumerator LoadAssetBundle( AssetBundleManifest manifest )
{
    // Here we'll use LoadFromCacheOrDownload. We give this a URL to our
    // bundle, and a "version". We can use the bundle hash in the manifest
    // to specify a version. If our bundle( and therefore version ) change,
    // we will download the updated version instead of loading from the cache.
    using( WWW www = WWW.LoadFromCacheOrDownload( "File:///" + absoluteBundlePath, manifest.GetAssetBundleHash( assetBundleName ) ) )
    {

        // Same as the manifest.
        yield return www;
        if( string.IsNullOrEmpty( www.error ) )
        {
            Debug.LogError( www.error );
            yield break;
        }

        // Here's our AssetBundle object.
        var bundle = www.assetBundle;

        // From here we can load assets sync or async.
        var loadedObjects = bundle.LoadAllAssets<MyType>();

        // Or...
        var request = bundle.LoadallAssetsAsync();
        yield return request;
        var loadedAsyncObjects = request.allAssets;

        // Clean up the compressed data:
        bundle.Unload( false );

       // Dispose of objects correctly when you're done with them. I'm not
       // quite sure how to explicitly dispose of them, but removing all
       // references to objects and calling Resources.UnloadUnusedAssets
       // works.
    }
}

```

That's how you load objects from asset bundles. There's a bug in Unity right now( 5.1 ) that will crash the application, even in the editor, on occasions if you use LoadAllAssetsAsync. You can use the manifest to get dependencies between bundles and load them in the correct order. I've heard that Unity automatically loads bundle dependencies, but in my experience this does not happen.
> 3 votes

---
Tags: unity
---


title: Redeeming an item on a periodic basis

text:
# Question
Title: Redeeming an item on a periodic basis
I want to allow a user to redeem a token every X time (i.e. 24 hours). Once they redeem it, they must wait X time again before redeeming the next item. This ensures that users must visit the app daily to continue gaining tokens.

I'm not sure how to work with clock differences between machines. What if

```
Server B:      9:03:41
User A tablet: 9:03.59
Server C:      9:05:23

```

(assume they all have the same date and all are AM)

User A's tablet makes a request and server B response with "Token available". The user then tries to immediately redeem the token, but server C responses with "Sorry, token not yet available." This would obviously be annoying to the user.

I could potentially handle this on the server. If the server says a token is available, then set a flag that actually guarantees that it is available.

But what if I want to actually let the user know how much time is left before they receive their next token. If all the servers have a different clock time, then all requests for time left would return a slightly different time.

I don't think I could rely on client time, since the user may play with different devices.

How could I handle this?

# Answer
> 0 votes
Time is a fleeting concept, relative to different observers and mostly illusive. It is up to you to decide how to deal with it.

My advice is that you should synchronize time between your servers. The easiest way is to use an authoritative time server. This ensures that all your machines agree, up to a useful error margin, with some source such as an NTP server.

You should synchronize client time using server as a time source. Do not trust any timestamp or other data from the client. In order to implement clock synchronization, you can borrow a fairly simple existing protocol such as SNTP. There is a detailed explanation in another SE answer.

UTC time should be used everywhere, it is much simpler that way.

### Now for your example

You describe a situation where a single client session is divided between several servers, and each of these servers can 'chime in' to handle any request. This means you have at least two options:

1. Update client time to match the current server each time your client changes servers.
2. Update client time to match the authoritative time server, and ignore small discrepancies.

I would prefer the 2nd option.

You will also need to store current state of said session globally, somewhere where every server can read it. Lets say you decided to use stand-alone database as a state storage.

For your example, this means when client presses a button and requests a token redeem, write something in the database, like "client with login id 'dan\_f' succesfully redeemed token 'santa hat' at 2015-08-03T13:45:30 (authoritative server UTC time)" and set client button text to your token cooldown.

You can periodically sync button text, but it is not really necessary, time discrepancy should be too small to care anyway. If client disconnects and reconnects, sync time as usual and update client button text using timestamp from previously written DB record. If user presses button and requests another redeem, use DB record again to check if redeeming is available, and sync button text in process. Again, with all servers synced with one master, and client synced with that master as well, time difference should be too small to care.

# Answer
> 0 votes
Make the client request the time remaining from the server that handles giving out the token. Then count down from that using the local clock.

Also I believe that you could synchronize your servers much better than that and this wouldn't be a problem as long as your app can handle the disagreeing servers.

And also probably you shouldn't let a user push a button to get a token until he can actually get it, so just request that from the server too.

---
Tags: server, client-server, timer
---


# Question
Title: How do I refer to the object that called a function?
I have a large number of buttons instantiated from a prefab using a loop, as follows:

```
public void LayoutButtons() {

        GameObject newCanvas = Instantiate (canvas) as GameObject;

        for (int i = 0; i < 10; i++) {
            GameObject newButton = Instantiate(button, new Vector2((i * 100.0F)-500, -100), Quaternion.identity) as GameObject;
            newButton.transform.SetParent (newCanvas.transform, false);
        }

    }

```

I would like the `OnClick` function to output the clicked button's text. However, I don't know how to reference the clicked button. I tried doing `Debug.Log(this.GetComponent<Text>().text)` but I get a `NullReferenceException: Object reference not set to an instance of an object`.

I'm not positive I'm using `this` correctly but I have limited connectivity at the moment and can't think of what else I'm doing wrong.

# Answer
You need to find references to Button and Text components on your instantiated objects, not on your controller object. Depending on your prefab hierarchy you can use GetComponent or GetComponentInChildren.

```
public void LayoutButtons()
{
    GameObject newCanvas = Instantiate(canvas) as GameObject;

    for (int i = 0; i < 10; i++)
    {
        GameObject go = Instantiate(buttonPrefab, new Vector2((i * 100.0f) - 500, -100), Quaternion.identity) as GameObject;
        go.transform.SetParent(newCanvas.transform, false);
        var button = go.GetComponent<Button>();
        var text = go.GetComponent<Text>();
        button.onClick.AddListener(() => Debug.Log(text.text));
    }
}

```
> 2 votes

# Answer
If your OnClick handler is in a script attached to your button prefab then you can do something like the following:

```
public void OnClick() {
    UnityEngine.UI.Text textComponent = GetComponentInChildren<UnityEngine.UI.Text>();
    Debug.Log(textComponent.text);
}

```

Basically, you are on the right track but you need to search for the component in the children of the Button object, not the button itself. Key problem is `GetComponent()` instead of `GetComponentInChildren()`.

The NullReference error is because the Text component was not found attached to the Button, so it returns null.
> 1 votes

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


# Question
Title: What are the advantages and disadvantages of overlap testing and intersection testing?
I have been looking for the advantages and disadvantages of both *overlap testing* and *intersection testing*, but I was only able to find a few disadvantages; overlap testing may fail for objects moving very fast, and intersection testing makes assumptions that may lead to wrong predictions, such as a constant speed and zero accelerations.

What are the advantages and disadvantages of overlap testing and intersection testing?

# Answer
Overlap testing has a lower processing cost, is easier to implement yourself and is what you would use for collision between objects if realism is not important to your simulation. One thing to note is that 'bullet physics' or the collision of very small and very fast objects with thin surfaces won't always behave as expected. This can be resolved by decreasing the time-step of you physics simulation, but at a higher cost.

Intersection testing is generally more computationally expensive and harder to implement, but excellent optimized implementations like Bullet Physics make it easy for beginner and expert alike to use this type of testing. It is much more realistic and bullet physics are supported by virtue of the way collisions are calculated. So if your game mechanics revolve around physics, using a library like bullet can give you the realism you need.

All in all, you should use overlap testing for simple games that do not need the additional accuracy (and overhead) of an accurate physics simulation and intersection testing for everything else.
> 1 votes

---
Tags: collision-detection
---


title: Box2D - Platformer tiled map problem

text:
# Question
Title: Box2D - Platformer tiled map problem
I'm using C++, Box2D and SFML.

I convert a Tiled map to world in my platformer game and I get stuck when I go against a block when I go forward like that :

I can use a circle as foot of my character but sometime, it make me jump a bit. Is there a solution or I must only do shape ?

# Answer
> 2 votes
This is a quite known issue in box2d, the problem is that you are rendering a rectangle per Tile and in the joint of those there is a ghost vertex, you can read extensive explanation here: http://www.iforce2d.net/b2dtut/ghost-vertices

As for a solution to that i solved it by creating an object layer in my tiled map and created a Polyline object that defines how the body will look like.

Tiled Screenshot:

Afterwards obtain that layer and for each Polyline defined create a box2d Body using the vertices in the Polyline.

---
Tags: c++, box2d, sfml, tiled
---


# Question
Title: Using USB sound input for an android game - is it possible?
We are brainstorming ideas for an app, for a major project using Android Studio, and writing in java. My major is game development, so I intend on trying to build a video game based off the use of an electric guitar, as input.

While I can set up a means to provide input via the audio-in, through the 3.5mm, having USB input would be far more effective.

My main question is: Is it feasible?

To give background, I believe it must be entirely possible, however, I am unsure how difficult the process would be.

I am basing my question off three things.

1. If I plug my Xbox controller directly into my phone, it automatically works. So the requirement for local support does not work as strictly as I understood it too.
2. If I plug the Rocksmith cable into a computer, and tell my sound card to "listen" to it, the guitar automatically comes through the speakers as if I was using the computer as an amplifier. This implies that no software is required on the computer side to interpret the input.
3. If you set up the electric guitar to connect to the computer via the microphone, it is not only compatible with Rocksmith, but it works just as well. This tells me the USB cable does not do anything fancy, in order to interpret the guitar - it must all be software side.

To start me off, all I really need to do is be able to interpret the frequencies. If I run into brick walls, further on, I will simply build around it, or change my games scope.

In terms of accessibility, I do understand the repercussions of requiring the Rocksmith cable to run the game. However, at the moment, simple being able to use the Rocksmith cable allows me to work on the part I am being marked on. If it goes to plan, I can access a more accessible means to use USB, later.

For those that are not familiar with Rocksmith, for the purpose of this question, it is simply a game that includes an electric guitar to USB cable, and is able to assess the player as they play the guitar, by reading its frequencies to determine what notes are being hit.

# Answer
3.5mm support would probably be easier if you want something to work out of the box by default.

Android is a very mature platform at this point and it has plenty of other applications besides just a Phone operating system. The OS has a fairly well documented USB api: https://developer.android.com/guide/topics/connectivity/usb/index.html which can probably be used to get the USB functionality you want. However this may not work out of the box, I honestly couldn't tell you which devices do and do not work out of the box. If you want to end up interpreting frequencies from a device over USB you may end up having to write some sort of driver or wrapper.

Note that you may want or need to use a USB OTG cable or adapter to go from micro USB to full USB.
> 0 votes

---
Tags: java, android, input
---


title: FPS horizontal smooth camera rotation

text:
# Question
Title: FPS horizontal smooth camera rotation
I have a problem, my camera is parented to the FPS Controller prefab, then there is a script I wrote for the rotation of the player horizontally by mouse movement, it all works but the rotation is very choppy and not smooth. How can I have the camera rotating smoothly or should I not parent my camera to the FPS Controller at all and make the rotation through scripting if so then how?

here's the script of character rotation:

```
void Update () {
    float rotationY = Input.GetAxis ("Mouse X") * 50f;
    transform.Rotate (0, rotationY, 0);

}

```

# Answer
Try this:

```
using UnityEngine;
using System.Collections;

public class RotateTheCamera : MonoBehaviour {

    private float targetAngle = 0;
    private float currentAngle = 0;

    void Update () {

        float mouseXChange = Input.GetAxis("Mouse X");

        targetAngle += mouseXChange * 10;

        if (targetAngle < currentAngle)
        {
            while (currentAngle - targetAngle > 360) targetAngle += 360;
        }
        else if (targetAngle > currentAngle)
        {
            while (targetAngle - currentAngle > 360) targetAngle -= 360;
        }

        currentAngle += Time.deltaTime * (targetAngle - currentAngle);

        if (Mathf.Abs(currentAngle - targetAngle) < 1) targetAngle = currentAngle;

        transform.rotation = Quaternion.Euler(0, currentAngle, 0);
    }
}

```

I changed the multiplier to 10 here, because 50 seemed too fast, but you could make it 50 still if you wanted.

Hope this helps.
> 0 votes

---
Tags: unity, c#, rotation, character, first-person-shooter
---


# Question
Title: I want to now how to set. X to a spot and change it to a cord but. Keep my Y and Z
Let's say postion was X1 Z34 Y2 I want to move char to X2 no matter what Z or Y are I want to change my x and keep z and y the same and keep momentum

# Answer
> 1 votes
See Transform.position.

```
transform.position = new Vector3(newPosx, transform.position.y, transform.position.z);

```

# Answer
> 1 votes
You could do
`transform.Translate(SPEED, 0, 0);`

which will give you a continuous movement along the X axis only.

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


# Question
Title: How can I load local html pages into unity?
How can I open an HTML page inside UNITY, with the page functioning normally?

# Answer
It depends what you mean by "the page functioning normally". Assuming you mean a browseable webpage within a game, then no.

You can make HTTP requests from Unity and thus download the data, but Unity isn't a web browser and won't display the HTML as a webpage. Similarly, Unity can open a web browser to a specific URL, but then that's not "inside Unity".
> 1 votes

# Answer
It's trivial to load information and files from a url online into unity by passing json, xml, material types (unity doesnt have a browser itself). Alteratively, you can pass the user to their browser to view the webpage.
> 0 votes

---
Tags: unity
---


# Question
Title: Unity: UNetWeaver warning: SyncVar set from within property function. This will not set dirty flags. How to?
I was trying out the new Unity networking and I added the `SyncVar` attribute to one of my variables to be synced. I also have a property to get/set the variable and update the visuals when set. I set the "hook" variable in the SyncVar so the property is used and visuals are updated properly (or that was the idea, since it gives an error :P)

```
[SyncVar(hook = "set_Tapped")]
private bool _tapped;
public bool Tapped
{
    get { return _tapped; }
    set { _tapped = value; UpdateRotation(); }
}

```

Now however I get an error in the console:

```
UNetWeaver warning: SyncVar [_tapped] set from within property function [System.Void Card::set_Tapped(System.Boolean)]. This will not set dirty flags.

```

How should this be handled? I could just make a `set` method myself (not using properties), but is there a better/nicer way?

Thanks!

# Answer
I have the same problem.

Given this unnecessarily complex post and this possibly useful but awfully long manual page, it's safe to say that just rewriting it to be a normal function instead of a setter, would be order**s** of magnitude easier than any other solution.

---

That being said, here's an alternative approach, that uses `SyncVar`:

```
[SyncVar] private Status status = Status.Free;
private Status prevStatus = Status.Free;

void Update ()
{
    if (status != prevStatus)
    {
        DoStuff();
        prevStatus = status;
    }
}

```

Over `Rpc`, this has the advantage of being "automatically" synced to new clients, at the expense of being slightly less obvious/readable/clear.
> 1 votes

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


# Question
Title: What can I do to avoid one-off flags and checks throughout my code?
Consider a card game, such as Hearthstone.

There are hundreds of cards that do a wide variety of things, some of which are unique even to a single card! For instance, there is a card (called Nozdormu) that reduces player turns to only 15 seconds!

When you have such a wide variety of potential effects, how do you avoid magic numbers and one-off checks all over your code? How does one avoid a "Check\_Nozdormu\_In\_Play" method in the PlayerTurnTime class? And how can one organize the code such that when you add even *more* effects, you don't need to refactor core systems to support stuff they've never had to support before?

# Answer
> 12 votes
Have you looked into entity component systems and event messaging strategies?

Status effects should be components of some sort which can apply their persistent effects in an OnCreate() method, expire their effects in OnRemoved() and subscribe to game event messages to apply effects which occur as a reaction to something happening.

If the effect is persistently conditional (lasts for X turns, but applies only under certain circumstances) you may need to check for those conditions at various phases.

Then, you just make sure that your game has no default magic numbers also. Make sure everything that can be changed is a data driven variable rather than hard coded defaults with variables used for any exceptions.

In this way, you never assume what the turn length will be. It's always a constantly checked variable that can be changed by any effect and possibly undone later by the effect when it expires. You never check for exceptions before defaulting to your magic number.

# Answer
> 11 votes
RobStone is on the right track, but I wanted to elaborate since this is exactly what I did when I wrote Dungeon Ho!, a Roguelike that had a very complex effects system for weapons and spells.

Each card should have a set of effects attached to it, defined in such a way that it can indicate what the effect is, what it targets, how, and for how long. For example, a "damage the opponent" effect might look something like this;

```
Effect type: deal damage (enumeration, string, what-have-you)
Effect amount: 20
Source: my weapon
Target: opponent
Effect Cost: 20
Cost Type: Mana

```

Then, when the effect fires, have a generic routine handle the processing of the effect. Like an idiot, I used a huge case/switch statement:

```
switch (effect_type)
{
     case DAMAGE:

     break;
}

```

But a far better and more modular way to do it is via polymorphism. Create an Effect class that wraps all of this data, create a subclass for each type of effect, and then have that class override an onExecute() method specific to the class.

```
class Effect
{
    Object source;
    int amount;

    public void onExecute(Object target)
    {
          // Do nothing
    }
}

class DamageEffect extends Effect
{
    public void onExecute(Object target)
    {
          target.health -= amount;
    }
}

```

So we'd have a basic Effect class, then a DamageEffect class with an onExecute() method, so in our processing code we'd just go;

```
Effect effect = card.getActiveEffect();

effect.onExecute();

```

The way to deal with knowing what's in play is to create a Vector/Array/linked list/etc. of active effects (of type Effect, the base class) attached to any object (including the playfield/"game"), so rather than having to check if a particular effect is in play, you just loop through all of the effects attached to the object(s) and let them execute. If an effect is not attached to an object, it's not in play.

```
Effect effect;

for (int o = 0; o < objects.length; o++)
{
    for (int e = 0; e < objects[o].effects.length; e++)
    {
         effect = objects[o].effects[e];

         effect.onExecute();
    }
}

```

# Answer
> 1 votes
I’ll offer a handful of suggestions. Some of them contradict each other. But maybe some are useful.

**Consider lists versus flags**

You can iterate over the world and check a flag on each item to decide whether to do the flag-thing. Or you can keep a list of only those items that should do the flag-thing.

**Consider lists & enumerations**

You can keep adding boolean fields to your item class, isAThis and isAThat. Or you can have a list of strings or enum elements, like { “isAThis”, “isAThat”} or { IS\_A\_THIS, IS\_A\_THAT}. That way you can add new ones in the enumeration (or string consts) without adding fields. Not that there's anything really wrong with adding fields...

**Consider function pointers**

Instead of a list of flags or enums, could have a list of actions to execute for that item in different contexts. (Entity-ish…)

**Consider objects**

Some people prefer data-driven, or scripted, or component entity approaches. But old fashioned objects hierarchies are worth considering too. The base class needs to accept the actions, like “play this card for turn-phase B” or whatever. Then each kind of card can override and respond as appropriate. There’s probably a player object and game object as well, so the game can do things like, if(player-\>isAllowedToPlay()) { do the play…}.

**Consider debug-ability**

Once nice thing about a pile of flag fields is that you can examine & print out every item's state the same way. If state is represented by different types, or bags of components, or function pointers, or being in different lists, it may not be enough to just look at the item's fields. It's all tradeoffs.

**Eventually, refactoring: Consider unit tests**

No matter how much you generalize your architecture, you’ll be able to imagine things that it doesn’t cover. Then you’ll have to refactor. Maybe a little, maybe a lot.

A way to make this safer is with a body of unit tests. That way you can be confident that even though you rearranged things underneath (maybe by a lot!) the existing functionality still works. Each unit test looks, generally, like this:

```
void test1()
{
   Game game;
   game.addThis();
   game.setupThat(); // use primary or backdoor API to get game to known state

   game.playCard(something something).

   int x = game.getSomeInternalState;
   assertEquals(“did it do what we wanted?”, x, 23); // fail if x isn’t 23
}

```

As you can see, keeping those top-level API calls on game (or player, card, &c) stable is key to the unit testing strategy.

# Answer
> 0 votes
Instead of thinking of each card individually, start thinking in terms of categories of effects, and cards contain one or more of these categories. For example, to calculate the amount of time in a turn, you can loop through all cards in play and check the "manipulate turn duration" category of each card that contains that category. Each card then increments or overwrites the turn duration based on the rules you've decided.

This is essentially a mini-component system, where each "card" object is simply a container for a bunch of effect components.

---
Tags: architecture, software-engineering, scripting
---


title: D3D12 device not supported

text:
# Question
Title: D3D12 device not supported
In the last days, I tried to learn the basics of Direct3D12, using some online resources and tutorials/demos.

After failing to run the demos, I created a new project in Visual Studio 2015, added the necessary configurations and tried to get the basic initialization done. However, running that project, it fails at the same location, which is *D3D12CreateDevice()* (builds without any warnings/errors).

The return value I keep receiving is **DXGI\_NOT\_SUPPORTED**. I changed my code to enumerate through all adapters of the *DXGIFactory*, which ended up with the same result (the same applies to the warp adapter).

This is the part of the device creation:

```
bool created = false;

UINT i = 0;
ComPtr<IDXGIAdapter1> pAdapter;
HRESULT hr = S_OK;
while (SUCCEEDED(m_dxgiFactory->EnumAdapters1(i++, pAdapter.ReleaseAndGetAddressOf())))
{
    DXGI_ADAPTER_DESC1 desc = {};
    pAdapter->GetDesc1(&desc);
    if (SUCCEEDED((hr = D3D12CreateDevice(pAdapter.Get(), D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&m_device)))))
    {
        created = true;
        pAdapter.ReleaseAndGetAddressOf();
        break;
    }
}
if (!created)
{
    ComPtr<IDXGIAdapter1> pWarpAdapter;
    CHK(m_dxgiFactory->EnumWarpAdapter(IID_PPV_ARGS(&pWarpAdapter)));

    CHK((hr = D3D12CreateDevice(
        pWarpAdapter.Get(),
        D3D_FEATURE_LEVEL_11_0,
        IID_PPV_ARGS(&m_device)
        )));
}

```

My system is running on Windows 10, 64 bit and has integrated Intel HD Graphics, as well as a NVIDIA GeForce GT540M, using the Optimus Technology. I did make appropriate changes to the NVIDIA Control Panel, to make the program run on the GeForce 540M, which - according to the Control Panel - supports the DX12 Runtime and feature level 11.0.
The integrated card however, only supports DX11. According GPU-Z, the Intel card only supports DX10 and the GeForce DX11.

I did install all the latest Windows Updates and drivers for both cards.
My guess is, that this is a driver related problem, since I am not able to run the demos either.

Can this be any issue related to the program itself, or should I try to get help from NVIDIA(or Microsoft?) about this problem?

# Answer
After a lot of research, I finally found the reason for this. Apparently, Fermi-based GPUs do not support DirectX12 yet.
"\[They\] will gain support for DirectX 12 ... later this year".

Hopefully, this won't take too long.
> 0 votes

# Answer
It looks like Optimus is up to no good again. As long as you render to the screen connected to Intel HD, it simply would not go away, despite any changes made in control panel or device manager, or bios.

Optimus tech is designed in a way that screen connected to Intel HD is always linked to the framebuffer of Intel HD card. 'Real' NVidia GPU is only allowed to write memory pages directly into that framebuffer. When you change that Control Panel setting, you only allow or disallow these GPU writes, you do not toggle direct rendering to a screen like one would think.

So your Nvidia GPU cannot directly render to an Intel HD connected display. What should you do? I don't really know, no Optimus in my home now and never will be; theoretically your troubles should go away if you connect your primary display to the Nvidia card, bypassing Intel HD completely.
> 1 votes

---
Tags: c++, gpu, nvidia, directx12
---


title: Increment grid by rotation

text:
# Question
Title: Increment grid by rotation
I'm currently working on a grid for snapping objects side by side. My current script is working fine, but only for game objects which haven't been rotated.

Here is an example video of the problem:

https://vid.me/jN6D

The cube at the right has a rotation of Vector3.zero, the left one has been rotated on the Y axis.

As you can see snapping works perfectly for the right one, but at 0:15 you can see that the snapping doesn't work well for the rotated cube, that's because I've currently no idea how I can add the rotation in my current script.

Here is a snippet of the most important part of code I'm currently using to calculate the grid:

```
Vector3 pivotToPoint = hit.point - nearestGameObject.transform.position;

float positionX = nearestGameObject.transform.position.x +
                  Mathf.Round(pivotToPoint.x / nearestGameObject.transform.renderer.bounds.size.x) *
                  nearestGameObject.transform.renderer.bounds.size.x;

float positionZ = nearestGameObject.transform.position.z +
                  Mathf.Round(pivotToPoint.z / nearestGameObject.transform.renderer.bounds.size.z) *
                  nearestGameObject.transform.renderer.bounds.size.z;

Vector3 origin = new Vector3(positionX, 0, positionZ) + Vector3.up * 100;

if (Physics.Raycast(origin, Vector3.down, out hit, Mathf.Infinity, layerMask)) {
    previewGameObject.transform.position = new Vector3(positionX, hit.point.y, positionZ);

    previewGameObject.transform.rotation = nearestGameObject.transform.rotation;
}

```

Maybe some of you guys have an idea how to solve this, it's driving me crazy.

p.s. Here is some guy with a similar problem, but I'm very lost when in comes to adding the solution into my code.

# Answer
It's been a while since I've worked in Unity, but I believe the problem (or at least part of it) you're having may be that you're using renderer.bounds which gives you the axis aligned bounding box of the object in question. This would mean that when you rotate the bounding box is not rotating, but is in fact *growing* to fit the rotated object

You can test this out by outputting the bounds values you're getting out of the non rotated and the rotated object, this should also help you find the exact points where things are going wrong if you output the pieces going into the positionX and positionZ floats individually so you can compare between the working case and the non working one

Since the rotation seems to be accurate the main thing you need to focus on is the position, and with that you should be able to simply use half the size of each along the given axis summed together. since you should have the rotation of the box you are snapping to you should be able to apply it to the standard x and z directions to get the direction to offset in, which can then be multiplied by each correct distance to get the proper axis offsets.

On a side note, I highly recommend using things like Debug.DrawLine and Gizmos.DrawWireCube to help visualize what is going on in situations like these as they tend to make it easier to assess what is going on with various 3d direction things as you adjust rotation/position/...etc

---

Note: I'm assuming Unity because the Raycast and the renderer.bounds, if I'm wrong on that most of this should still apply, you'll just need to test whether bounds is axis aligned and figure out what the proper debug draw methods are for your situation
> 1 votes

---
Tags: unity, rotation, grid
---


title: Unity3D with C++

text:
# Question
Title: Unity3D with C++
So, my game is being developed in pure C++, with very limited dependencies (Mostly just pocoproject). The main goal here is portability, not performance. The code runs on multi-platform clients, as well as the server itself.

This is all headless, not graphics whatsoever. Everything is implemented, though. Menus, navigation, the game itself, online, single player, ... etc. You can essentially play the whole game with this C++ library. I added simple console bindings, so I can visually test and play the game, but haven't hooked it with a game engine yet.

I would really like to use Unity3D for the graphical part, as it kicks ass when it comes to rapidly developing graphics, but it was a hellish experience to try and marry Mono with C++, even when using SWIG. (Basically, Mono has limited C++ compatibility, but it is really annoying to work with).

Here is the problem, I am stuck between these two islands; C++ program and Unity3D. I am not very good with OS concepts, so I don't know if it's possible to fork the main process and run a local C++ server, and have the Unity game communicate using RPCs or even REST API. Performance isn't an issue, the only issue is maintainability. I need a robust and simple system that I can wrap my head around easily.

Other solutions welcome!

# Answer
> 0 votes
You can use Visual Studio 2013 with Unity, you just have to download the tools package from Microsoft. Not sure if this would help with using C++ but I know that C++ works in VS and may or may not work in the VS/Unity environment. I'd recommend using VS with Unity regardless, it's much better all around. If you attach VS to Unity just make sure you disable Monodevelop as you'll get annoying conflicts if you don't...

---
Tags: unity, c++
---


# Question
Title: What is the best way to manage 'state' in Phaser?
I have heard that this is not the best way to manage state in phaser

```
var game = new Phaser.Game(800, 600, Phaser.CANVAS,'YourGameName');
game.state.add("Boot", Boot);
game.state.add("Preload", Preload);
game.state.add("MainMenu", mainMenu);
game.state.add("Play", Play);
game.state.add("GameOver", GameOver);
game.state.start("Boot");

```

so what is the best way to do it. I am newbie in Phaser game development.

# Answer
> 1 votes
The point is - what are you really want form your state manager. In my case i created SceneManager that has method

```
addScene(name, state, options) {
    this.game.state.add(name, state);
    this.scenes.add(name, options);
}

```

And it can decided based on options what kind of scene should be loaded. So in initial phase a do fill it with states like this:

```
config.scenes.forEach( (scene) => deridara.addScene(scene[0], scene[1], scene[2]));

```

Where `config.scenes` is something like:

```
scenes : [
    ['DreamForest', DreamForest],
    ['Hills', Hills],
    ['TreeСreature', TreeСreature],
    ['Waterfall', Waterfall],
    ['Astral', Astral] //Third param could be options
]

```

And thouse objects are just classes that extends class Scene

```
class Scene {
constructor(game) {}

init() {}

preload() {
    this.preloadBar = this.game.add.graphics(0, 50);
    this.preloadBar.lineStyle(3, 0xffffff, 1);
    this.preloadBar.moveTo(0, 0);
    this.preloadBar.lineTo(this.game.width, 0);

    this.preloadBar.scale.x = 0; // set the bar to the beginning position

    PubSub.publish('scene:loading:start', {
        name : this.name
    });
}

create() {
    this.game.scale.fullScreenScaleMode = Phaser.ScaleManager.NO_SCALE;
    this.game.input.keyboard.onPressCallback = this.keyboardListener;
}

keyboardListener(key) {
    switch (key) {
        case 'а':
        case 'f':
            if (this.game.scale.isFullScreen)
            {
                this.game.scale.stopFullScreen();
            }
            else
            {
                this.game.scale.startFullScreen(false);
            }
            break;
    }
}

update() {}

shutdown() {}

loadUpdate() {
  // every frame during loading, set the scale.x of the bar to the progress (an integer between 0
  // and 100) divided by 100 to give a float between 0 and 1
  this.preloadBar.scale.x = this.game.load.progress * 0.01;
}

}

```

So i have place to pass common code like events triggers and loaders, and clever enough controller to rule them all =)

---
Tags: game-design, javascript, game-mechanics, phaser
---


# Question
Title: SerializeField vs GetComponent Efficiency
As far as I know, there are two built in ways to get an instance of a component in Unity.

1 - Serialize the field and drag in the component manually in the editor

```
[SerializeField] private MyScript script;

```

2 - Using MonoBehaviour's GetComponent method

```
script = GetComponent<MyScript>();

```

I would think that it is more efficient to drag the component in the editor lest making the engine illiterate through every component in the GameObject to find the component.

Is it more or less efficient to drag the component in the editor compared to using GetComponent? Or does Unity find components in a different way or dragging components in the editor is handled in a different way such that it would be more efficient to use GetComponent? Would using one over the other have any impact on performance in the real world?

A similar question would also be raised regarding GameObject.FindGameObjectWithTag() vs dragging in the editor.

As far as optimization go, should you use one method over another?

# Answer
> 6 votes
Use the inspector to allow the user (you, or other developers) to be able to easily define the Component themselves without having to modify your code.

Use the GetComponent() method if there is no need to be able to change it from the way you designed your script.

Efficiency doesn't have to do with it.

If you use GetComponent() in your script, you will generally store the component in a variable so that it is cached for reuse in your script, so it works out to be the same thing in terms of efficiency.

Where GetComponent() is slow, is if you are calling it as you need it to look up the component every update or something. Store it in a variable and then it's just fine.

Same goes for the FindObject methods. Cache it when your script starts, then it has no impact during runtime.

---
Tags: unity, c#, performance, optimization
---


title: accelerated curved bounce

text:
# Question
Title: accelerated curved bounce
I'm trying to make a simple pong clone and want the ball to curve when the racket was moving on hit. To test out curves I removed all the rackets and just have a ball bouncing around in a rectangle, curving in the positive Y direction.

I tried simulating gravity on the Y axis, but the outcome is weird. The bigger the rectangle, the faster the velocity gets over time. In a small rectangle, I lose velocity and the ball slows down.

I do the following: On each tick I check if I should do a curve, if so, then I increase the curve force and add it to the Y velocity (curves only appear on Y)

```
if (this->DoCurve)
{
    //check if we don't exceed the maximum curve force
    if (this->CurveForce < this->CurveMaxForce)
        this->CurveForce += this->CurveIncrease*delta;

    //add curve force to Y
    this->Velocity += FVector(0.f, this->CurveForce, 0.f) * delta;
}
//move object to new location
SetLocation(this->CurrentLocation + this->Velocity * delta);

```

When I hit a wall, I want the curve to stop until I hit the next wall.

```
//if we are already curving, stop it and reset
if (this->DoCurve)
{
    //subtract the force we added to make it move normal again
    this->Velocity -= FVector(0.f, this->CurveForce, 0.f);
    this->CurveForce = 0;
}

this->DoCurve = !this->DoCurve;

//reflect
FVector ReflectedVelocity = (-2 * FVector::DotProduct(this->Velocity, Hit.Normal) * Hit.Normal + this->Velocity);
//ignore Z axis
ReflectedVelocity.Z = 0.f;

//ReflectedVelocity.Normalize(); // this makes the ball stuck in a wall
this->Velocity = ReflectedVelocity;

```

Basically I have no idea what I'm doing.

What I want: When the ball hits a racket and it is moving I want the ball to move in a curve fast first, then slow down, like the racket gave it a boost.

My approach is very flawed, what would be the correct way?

# Answer
> 1 votes
I would express the direction of the ball in an angle. The curve would increase that angle each timestep until a wall or a racket is hit.

A quick pseudo-code to give you an idea of what I mean:

```
Update(float deltatime)
{
    direction+=curveangle*deltatime;
    position.x += cos(direction)*velocity*deltatime;
    position.y += sin(direction)*velocity*deltatime;

    if(wall_is_hit)
    {
        curveangle=0;
        direction=new_wallbounce_direction();
    }
    if(racket_is_hit)
    {
        direction=new_direction();
        curveangle=new_curvature();
        velocity=new_velocity();
    }
}

```

This gives you a basic curve movement. If you want the curve to get slowly to a straight line, reduce the curveangle each step until it becomes 0 or if you want the curve to become more steep increase it to some defined maximum.

# Answer
> 0 votes
I'm still learning coding soo this won't be a great answer but I hope I can help. If you set the velocity to increase after hitting a racket as a percentage instead of a flat rate and then set a max with a clause to return it to a normal speed after it hit's said max you might find what you're looking for.

---
Tags: c++, curves
---