# Question
Title: How do I letterbox a C#/Monogame viewport within a resizeable window?
I am making a 2d game with xna/monogame. I want the main view area to always show 15x15 tiles, or 480x480px.

I've got something that sort of works, following this guide. It expands the view range if you make the window smaller. However, it works somewhat properly if you expand it. It works as intended if the window is maximized.

I want the range of what is rendered to be no larger than 480px x 480px regardless of the the window's size, but I'd like the sprites to appear bigger if the window resolution is set larger (and conversely).

# Answer
> 5 votes
I've recently been implemented something like this in the MonoGame.Extended library. Creating a letterbox / pillarbox viewport in MonoGame is actually kinda tricky. I'll do my best to provide a good answer here.

There's basically 3 parts to it. The first is creating a scaling matrix to pass into the `SpriteBatch.Begin` call. The variables represent your *actual resolution* vs *virtual resolution*. For example, you code the game against a virtual resolution of 800x480 but render it on an actual resolution of 1024x768. This code will stretch the image to fit.

```
var scaleX = (float)ActualWidth / VirtualWidth;
var scaleY = (float)ActualHeight / VirtualHeight;
var scaleMatrix = Matrix.CreateScale(scaleX, scaleY, 1.0f);

_spriteBatch.Begin(transformMatrix: scaleMatrix);

```

The second part is how you get the letterbox / pillar box effect. It resizes the viewport on the `GraphicsDevice` and centers the image. This code needs to run every time the devices screen size or window size changes. For example, in the `Window.ClientSizeChanged` event.

```
var viewport = GraphicsDevice.Viewport;
var aspectRatio = (float) VirtualWidth / VirtualHeight;
var width = viewport.Width;
var height = (int)(width / aspectRatio + 0.5f);

if (height > viewport.Height)
{
    height = viewport.Height;
    width = (int) (height * aspectRatio + 0.5f);
}

var x = (viewport.Width / 2) - (width / 2);
var y = (viewport.Height / 2) - (height / 2);

GraphicsDevice.Viewport = new Viewport(x, y, width, height);

```

The last part is dealing with input coordinates from the mouse or touch screen. Because you've scaled and moved the graphics, you'll need to do the reverse for input coordinates. In this case, something like this

```
var viewport = GraphicsDevice.Viewport;
var matrix = Matrix.Invert(scaleMatrix);
var oldPosition = new Vector2(mousePoint.X - viewport.X, mousePoint.Y - viewport.Y);
var newPosition = Vector2.Transform(oldPosition, scaleMatrix).ToPoint();

```

I have a full tutorial with all this stuff in classes on my blog.

# Answer
> 1 votes
articles generally are not liked in Stack exchange but this is my go to blog post when trying to remember this

http://www.david-amador.com/2010/03/xna-2d-independent-resolution-rendering/

---
Tags: xna, 2d, monogame, viewport, scale
---


# Question
Title: How do I generate a mipmap for a texture loaded from a stream?
I am loading a `Texture2d` from a stream:

```
public static Texture2D GetTexture(GraphicsDevice dev, System.Drawing.Bitmap bmp) {
    Texture2D texture;
    using (MemoryStream s = new MemoryStream())
    {
        bmp.Save(s, System.Drawing.Imaging.ImageFormat.Jpeg);
        s.Seek(0, SeekOrigin.Begin);
        texture = Texture2D.FromStream(dev, s);
    }

    return texture;
}

```

I want to generate a mipmap for the texture, as my texture looks bad when viewed from afar. How do I do this?

# Answer
Shivam,

If you create your mipmap programatically, you will experiance such a problem with no doubt!

You have to create your mipmap in your 3D software, which will render each size seperatly,resampling with raster image editing tools and with programming will reduce the the pixel size without care and deletes a whole row or a whole col which hurts the edges and important spots in your raster, so you need to resample, during the render process, I hope you have a 3D model and the texture you are talking about is rendered from which.

**In this case :**

if your 3D software supports mipmap creation it is easy to be done, though without this ability, you may play with camera location, do the math!

Some 3D software support scripting I personally use a phyton code to create the mipmaps in Blender.

Tell me if you need a phyton code in case you use Blender.

Good luck

Iman
> 1 votes

# Answer
There is some API support: XNA Game Studio.

A thread about it: XNA 4 Texture2D.GenerateMipmaps() missing.

However, this will for sure **NOT** have the generation right. Because these functions will not apply gamma correction intrinsically:

You can also discard it if the slight imprecision is not of importance to you.

Without using the API generating mipmaps can be done manually but it is a piece of work to implement, you need to either do it on the CPU and map/copy to the correct parts of the texture. Or do it on the GPU using render targets and then using "resource copy" API to set the mips: https://stackoverflow.com/questions/11172218/mipmapping-with-generating-textures-in-xna.
> 0 votes

---
Tags: xna-4.0, textures, mipmaps
---


title: Changing direction after collision

text:
# Question
Title: Changing direction after collision
In the first tutorial for GameMaker (catch the clown), I want to set the direction of the clown after the collision with the wall.

I want to do it by pressing the wall object with the mouse (before the collision, to set the angle parameter). For example by pressing only once the wall object it would change the clown's direction after collision by 45 degrees, twice by 90 degrees, and so on.

How can I do that?

# Answer
> 1 votes
To change the direction of the clown, you can change the built-in property, "direction."

Since you want to change the direction on mouse click, you can use the following code.

```
// create event for clown
// this variable will be used to keep track of how many times mouse was clicked
globalvar numberOfClicks;
global.numberOfClicks = 0;

// mouse press event
global.numberOfClicks++;
if(global.numberOfClicks == 1) {
    // if mouse was clicked once, then direction is 45 degrees
    clownDirection = 45;
} else if(global.numberOfClicks == 2) {
    // if mouse was clicked twice, then direction is 90 degrees
    clownDirection = 90;
    // reset the number of times mouse was clicked
    global.numberOfClicks == 0;
}

// collision event with wall and clown
with(obj_clown) {
    direction = clownDirection;
}

```

# Answer
> 0 votes
Ok, so in your wall object, you should store the variable for how many times it has been clicked.
You can do this by first adding a *Create* event on it and create/set variable "numberOfClicks".
This can be done by adding a *piece of code* there and putting "numberOfClicks = 0;" inside it.
**Or** you can simply add a *create variable* and name it "numberOfClicks".

Then add a *Clicked* event. In there either add a *piece of code* again and put "numberOfClicks++;".
**Or** you can add a *set variable* enter "numberOfClicks", check relative, and set it to 1.

Lastly in the a *collision event* with the wall object for your clown object you need to add a *piece of code* with the following inside:

```
direction += 45 * other.numberOfClicks;
other.numberOfClicks = 0;

```

This will increment the direction of your clown by 45 per click on that specific wall.
If you want to set to that angle rather than increment by that angle, change "+=" to "=".

My guess is also you might want to invert the direction of the clown first (so that it bounces right back if it collides with one that hasn't been clicked). This can be achieved by putting "direction = -direction;" before those other two lines of code.

I haven't been working in Game Maker for some time so hopefully this works out! :)
Don't hesitate to ask for more info if anything is unclear.

---
Tags: collision-resolution, game-maker
---


title: Double buffer - Managing Collision

text:
# Question
Title: Double buffer - Managing Collision
I'm thinking about how I should manage collisions in my game. I'm thinking about having a "Collision" class that checks for collision, and in case takes actions to resolve them.

My problem is this:

A and B moving to the other, when they collide they must bounce.

If I resolve the collisions sequentially, like calling:

1. A.collideWith(B)
2. B.collidesWith(A)

B will be stuck, because A has already updated his velocity and position, and when will be called B.collideWith(A) there won't be any collision anymore.

So, is it a good idea to use a double buffer pattern?

I'll write the values obtained by the collision resolver in some variables, they will be swapped to the real ones when all the collision has been resolved. In that way all should work fine.

But it is a good software design?

**EDIT**

I see, yes of course i check only for half. So there should be a class that checks for collisions, and should be like:

```
checkedpairs.clear();
for( Object a : objects )
{
    for( Object b : objects )
    {
        if( ! a.collideWith( b ) || checkedpairs.contains( a, b ) ) return;

        Object a1 = copyf( a );
        Object b1 = copyOf( b );

        a.collideWith( b1 );
        b.collideWith( a1 );

        checkedpairs.add( a, b );
    }
}

```

Instead of putting the logic for the swap in the objects themselves...

But that way, I'm creating two objects for each collision, isn't too much overhead?

The problem is that I don't need only the position, but al lot of physics stuff like velocity, acceleration, mass... Should I pass them? Isn't it too hard-coded?

# Answer
If A.collidesWith(B) then you don't need to check B.collidesWith(A). You only need to check for half of the collisions.

If you have 3 objects A,B,C you only need to check collisions of

* A & B
* A & C
* B & C

You should have a separate pass that checks collisions and calls both A and B's collision callback if a collision has occurred with a copy of A and B's positions before adjustments.

In some cases you can avoid buffering the state of all objects this way.
> 1 votes

# Answer
Yeah, it's not necessary. When you detect a collision between A & B you should do something like:

```
if (detectCollision(A, B)) {
  A.resolveCollision(B);
  B.resolveCollision(A);
}

```

This may not be how you do it, but you get the idea!
If it is a problem that A has had it's values changed after resolving collision with B you could store the variables before calling A's resolve method and then pass them as arguments into B's resolve method.
> 1 votes

---
Tags: collision-detection, architecture, double-buffering
---


# Question
Title: How to go about an intermediate collision resolution system?
I would like to know a better way of collision resolution than I am currently doing. My current collision system stores the current positions and previous positions of each object. When an object collides with another it sets the current positions to the previous positions.

This would work fine if objects could only move in four directions, but when they can move in more than four directions the system doesn't work. For example if you are moving an object\_A up and right and it collides with and object\_B above it, the object\_A stops moving even if still going up and right. In most 2d games however if this scenario happened the object\_A would stop moving up but continue to move right. This is the kind of collision resolution that I would like to implement. I don't need anymore complicated physics right now this will do.

I'm just using rectangles so that would be the only shape I need to worry about.

# Answer
> 1 votes
Here are two options you could consider; an easy one and one that you'd find in commercial games.

# Solution 1: Separate your movement axes

If your objects are all rectangles (assumed to be axis-aligned), you could **consider horizontal and vertical motion separately**. This means your motion procedure will be updated to:

```
// Horizontal movement
x_previous = x;
x += velocity_x;
if (colliding()) { x = x_previous; }

// Vertical movement
y_previous = y;
y += velocity_y;
if (colliding()) { y = y_previous; }

```

Note that this will **only** work assuming **all-rectangular geometry** and small movement steps. For example, your objects would not be able to through an upward corridor smoothly as they will - as a matter of speaking - alternate between banging into the ground and into the roof.

An additional disadvantage of your technique is that objects will **not be able to stop right against the wall**. For example, if their horizontal velocity is 10 and their is a wall nearby, they will end up with a gap of 0 to 9 units between them and the wall.

---

# Solution 2: Calculate collision positions and normals

The behavior you are trying to achieve seems to be **"wall-sliding"**. This means, if you walk into a wall, you will slide along it depending on your movement direction.

The way this is achieved in commercial games, is by calculating more information on the collision. In your case, you just "calculate" the answer to the question "Am I colliding or not?". Information that is required to solve your problem in a more elegant manner is "At what **position** did I collide?" and "What is the **normal** of the surface I collided with?". This information can be obtained for example by raycasting your object's bounding box against collision geometry (e.g. by line-raycasting the configuration space obstacle (CSO)).

Using this information, you can resolve you collisions in the following way:

1. Calculate your *motion\_vector* as (*velocity\_x*, *velocity\_y*)
2. Perform a ray-cast along ths motion vector to obtain *collision\_position* and *collision\_normal*
3. Move your object to the *collision\_position* (or slightly before it) so that it doesn't intersect with other objects anymore
4. Calculate your new *motion\_vector*, as your current *motion\_vector* minus the component of your *motion\_vector* parallel to the *collision\_normal*
5. Shorten the length of your *motion\_vector* by the distance you've already moved
6. Repeat steps 2 through 5 until the object managed to move the full length of the *motion\_vector*

While this solution is more complicated, it will resolve the two primary problems with the simple approach (objects leaving a gap inbetween them upon colliding and not being able to cope with non-rectangular bounding boxes).

---

In summary: the easiest way to solve the problem for your use-case is to separate your movement axes. The way it is solved in commercial games involves calculating more information such as the collision position and the collision normal.

---
Tags: collision-detection, collision-resolution
---


# Question
Title: Pathfinding with differently-sized objects on tile map
It's my first RTS game and I'm having trouble finding out how to make infantry take less space than tanks.

Right now I have 1 tank and 1 infantry type ready with sprites, pathfinding, selection and movement mechanics all ready, up and running. The infantry unit is 16x16 and the tank is 32x32 which the size of one tile in my map. How can I make a foot soldier stand or walk with another foot soldier in the same Tile? Should I use 2 versions of the map for each of the unit types to make their pathfinding? In which case there would be problems with coordinates when these 2 types interact with each other like attack and defend which i haven't yet coded.

I'm even starting to question whether a tile based map is even a good choice for a 2D rts game, which is obviously a rediculous question xD.

# Answer
> 2 votes
To let your footsoldiers share a tile you should simply position them correctly after the pathfinding found the tile. If you are smoothing your path then each step should lead to the correct position for that unit within the tile.

You can also have a look at **flocking**. It basically finds a single path for a group of units and moves them as a group. Implemented right you have great control on how the units behave within the group. But if the units are very restricted to the grid this might not be what your looking for.

But for differently sized units on a tilemap you should probably implement **clearance based pathfinding**. If everything is setup already it should be easy to implement. What you do is give every tile a clearance value: 0 for wall, 1 next to wall, 2 for a extra tile away from a wall, etc how much you need.

A tank that covers two tiles will need a clearance of 2 and the pathfinding system should find a path using the tiles with a clearance value of 2 and above. A flying unit could use 0 or higher.

---
Tags: c++, tilemap, sdl, rts
---


# Question
Title: Rotate a rigid body not around its centre of mass
I have a rigid body (a boat) whose centre of mass is towards the front of the object. However, this makes the rotation look strange as the rudder that is turning the object is at the back of the boat so the rotation would be around that point.

**How can I rotate the object from the a separate point (using forces) without changing the centre of mass?**

Applying a force at a location still causes the object to rotate around the centre. In real life, you need to pin down the point that you want to rotate around, forcing the object to rotate around that point.

This would suggest using constraints but I can't figure out how that would work. You sort of need the rotation point to act as a hinge, but when I apply a suitable constraint, but that would just block the rotation rather than convert it into a rotation around the new point.

I want to resolve this using physics driven operations in Unreal Engine 4.

I don't want to move the Centre of Mass, admittedly for not a particularly good reason, but this still feels like a valid question even if that was an option - what if you want to rotate around two different points.

# Answer
> 3 votes
All free rigid bodies will rotate about their center of mass, so you're kind of stuck in that regard. However there are two options:

1. Implement an artificial pivot (specify the coordinate that you want it to pivot about) and do summation of moments about that point. This would require a modification to existing physics fxns, or a new fxn.
2. Temporarily store the old CoM, then replace that variable with your desired pivot before running the physics calculations (or allow the fxn to take CoM as an input)

Either way, once you sum your moments about the pivot, simply divide by the moment of inertia to obtain an angular acceleration (which is only valid for rotating about the pivot). More on rigid body dynamics

---
Tags: physics, unreal-4
---


# Question
Title: How to generate Spritefonts for monogame
I just want to render some text to the screen using:

* monogame 3.0
* MS Visual Studio 2010 C# Express

In XNA, you were able to add fonts to the content pipeline quite easily. But this doesn't seem to be the case in monogame. Loading TTF Files using `Content<SpriteFont>.Load()` doesn't work. Is there any way to generate or download \*.spritefont files or \*.xnb files containing the font data (without resorting to install XNA)?

# Answer
An alternative is to use pre-generated bitmap fonts instead. Here's a tutorial I wrote a while back on using the BMFont tool to get text into your game using the MonoGame.Extended library.

http://dylanwilson.net/bmfont-rendering-with-monogame-extended
> 6 votes

# Answer
I ran into the same problem as you. Thankfully, I had an existing XNA project that already used a .spritefont file, and generated the XNB file. I just compiled it, and copied the XNB into my MonoGame project, and I can use it without any problems.

(Disclaimer: I tried building the XNA content pipeline for MonoGame 3.0 beta as per instructions, and after a few hours, I gave up; it wouldn't include the project properly in Visual Studio.)
> 3 votes

# Answer
At least in August this year generating spritefonts was not yet supported by MonoGame, however the content pipeline was the main focus of attention the last few months so I wouldn't be surprised if it does work currently. Of course you need to know the syntax of a `.spritefont` file which needs to be added to your content folder. For that see the bottom of this post.

As far as I can tell, even as far back as August, the loading of already compiled spritefonts from XNB files is supported. Since you don't want to install XNA to generate these XNB files you might want to check the XNA Content Compiler Project on codeplex.

Here is an example `.spritefont` file so you can see if it's currently supported

```
<?xml version="1.0" encoding="utf-8"?>
<!--
This file contains an xml description of a font, and will be read by the XNA
Framework Content Pipeline. Follow the comments to customize the appearance
of the font in your game, and to change the characters which are available to draw
with.
-->
<XnaContent xmlns:Graphics="Microsoft.Xna.Framework.Content.Pipeline.Graphics">
  <Asset Type="Graphics:FontDescription">

    <!--
    Modify this string to change the font that will be imported.
    -->
    <FontName>Arial</FontName>

    <!--
    Size is a float value, measured in points. Modify this value to change
    the size of the font.
    -->
    <Size>10</Size>

    <!--
    Spacing is a float value, measured in pixels. Modify this value to change
    the amount of spacing in between characters.
    -->
    <Spacing>0</Spacing>

    <!--
    UseKerning controls the layout of the font. If this value is true, kerning information
    will be used when placing characters.
    -->
    <UseKerning>true</UseKerning>

    <!--
    Style controls the style of the font. Valid entries are "Regular", "Bold", "Italic",
    and "Bold, Italic", and are case sensitive.
    -->
    <Style>Regular</Style>

    <!--
    If you uncomment this line, the default character will be substituted if you draw
    or measure text that contains characters which were not included in the font.
    -->
    <!-- <DefaultCharacter>*</DefaultCharacter> -->

    <!--
    CharacterRegions control what letters are available in the font. Every
    character from Start to End will be built and made available for drawing. The
    default range is from 32, (ASCII space), to 126, ('~'), covering the basic Latin
    character set. The characters are ordered according to the Unicode standard.
    See the documentation for more information.
    -->
    <CharacterRegions>
      <CharacterRegion>
        <Start> </Start>
        <End>~</End>
      </CharacterRegion>
    </CharacterRegions>
  </Asset>
</XnaContent>

```
> 2 votes

# Answer
You can now do this without installing anything extra. In a brand new MonoGame project you should have a `Content.mgcb` file. That should bring up the MonoGame Pipeline app. You can right click on the `Content` node in the tree and add a new item. Select \`SpriteFont Description'. That will get compiled correctly and you should be able to load it in your code.
> 2 votes

# Answer
Check this out guys, I've been compiling my \*.spritefont files to .xnb for use in MonoGame, for me, it's the only way it worked.

Check it out, might help you too. http://xnacontentcompiler.codeplex.com/
> 1 votes

# Answer
The best alternative is to pre-generate the font xnb via XNA first then just use them in your Monogame for Windows project or you can do the old trick of getting the Window.Handle and the screen coordinates ScreenToClient then use the GDI to draw your text with the System.Drawing.dll.
> 1 votes

# Answer
I have been working on this for several days now, trying to fix this and eventually i got i to work. What i am working on is Windows8, VS2012, MonoGame. i should add that this is as "monoGame Windows OpenGL Pjoject"

Let me take you through the steps i have taken. 1. I installed monGame for VS2012 2. I installed WindowsPhone SDK8 3. I installed XNA 4.0 for my VS2010

I dont know if all these steps are nessecery....

Sence you cant generate a .spritefont in vs2012 I generated a spriteFont file in my vs2010 and then added i to my vs2012 project....BUT it did not work. And this morning I saw that the URL for that .spritefont file was wrong. When i added it through solution explorer..content--\>add exsisting item...then the url was wrong.. "C:\Users\admin\Documents\Visual Studio 2012\Projects\MyGame\MyGame\Content" this is not where vs2012 where looking for my \*.spritefot file it was here..--\> "C:\Users\admin\Documents\Visual Studio 2012\Projects\MyGame\MyGame\bin\WindowsGL\Debug\Content" I added i manully, and WOW it worked. i paste some code here so you better can see what i have done.. inside my game class i put these variables

```
    SpriteFont myFont;
    int score;

```

in my loadcontent method autogenerated by VS was

```
    myFont = Content.Load<SpriteFont>("test");

```

in my draw method autogenerated by VS was

```
         spriteBatch.Begin();
     spriteBatch.DrawString(myFont, "Score: " +score, new Vector2(20,10),Color.Red);
        spriteBatch.End();

```

and then manully added my spritefont file in the right folder

The strange thing is that i have added pictures with this way and the have ended up in the right folder but not the \*.spritefont, you have to manully add it in the later folder to get i to work..

I hope some of this makes sense to someone because this has given me the biggest headache these last days. I may have forgotten some steps and all this may be useless, but I hope that I may ease the headaches for some out there

And i hope that monoGame will be updated to fix these issues...
> 0 votes

# Answer
I've used XNB Builder to manually convert them into `.xnb` files. Simply run the app, choose your files and it will convert them into XNB files that are ready to use with MonoGame.
> 0 votes

---
Tags: xna, monogame
---


title: How can I create a stun gun in Unreal?

text:
# Question
Title: How can I create a stun gun in Unreal?
I am fairly new to the programming world. I am currently at college and one of the tasks I need to do is create a "stun gun" or "freeze gun."

Basically, when you shoot a target (another player) I want it to stop them for five or so seconds. The gun will do no damage to the player, just simply freezes them. The player can be refrozen and/or continuously shot to remain frozen until the shooter's ammo runs out.

If anyone can give me some help on what to call in certain classes, or even provide me with the basic code the will freeze the player for several seconds, I'll be very thankful.

I know how to make a new weapon, and change fire-rates, etc... I am just stuck with what it is I have to do to freeze a player using the projectile class, or pawn class?

# Answer
> 2 votes
Ok I decided to help you on your way. But we are simply not doing homework for you. UDK documentation seems down for maintainance but I have found this: http://www.moug-portfolio.info/udk-projectiles/ example. You should read it completely since it helps you understand projectiles. Towards the bottom they explain projectiles. Let it be clear that I have no experience other then creating some simple maps a decade ago with UDK.

The code I found on the mentioned website that I will be discussing:

```
class SandboxPaintballProjectile extends UDKProjectile;

simulated function ProcessTouch(Actor Other, Vector HitLocation, Vector HitNormal)
{
    if ( Other != Instigator )
    {
        WorldInfo.MyDecalManager.SpawnDecal ( DecalMaterial'SandboxContent.Materials.DM_Paintball_Splash', HitLocation, rotator(-HitNormal), 128, 128, 256, false, FRand() * 360, none );
        Other.TakeDamage( Damage, InstigatorController, Location, MomentumTransfer * Normal(Velocity), MyDamageType,, self);
        Destroy();
    }
}

simulated event HitWall(vector HitNormal, actor Wall, PrimitiveComponent WallComp)
{
    Velocity = MirrorVectorByNormal(Velocity,HitNormal); //That's the bounce
    SetRotation(Rotator(Velocity));
    TriggerEventClass(class'SeqEvent_HitWall', Wall);
}

DefaultProperties
{
    Begin Object Name=CollisionCylinder
        CollisionRadius=8
        CollisionHeight=16
    End Object

    Begin Object Class=DynamicLightEnvironmentComponent Name=MyLightEnvironment
        bEnabled=TRUE
    End Object

    Components.Add(MyLightEnvironment)

    begin object class=StaticMeshComponent Name=BaseMesh
        StaticMesh=StaticMesh'SandboxContent.Meshes.SM_PaintBall'
        LightEnvironment=MyLightEnvironment
    end object

    Components.Add(BaseMesh)

    Damage=25
    MomentumTransfer=10
}

```

My first assumption is that if you create a weapon with a projectile you have this script attached to it. I simply cannot help you with that.

As Mougli talks about this he explains that if a wall or actor with `bWorldGeometry set to true` the `HitWall` function/method will be triggered. Since we are not freezing walls or furniture we will leave that alone. Whenever another actor get's hit the `ProcessTouch` is being called and like I already mentioned you are supplied by the actor that actually is hit `Actor other`.

Now we can call that actor and do stuff with it by doing `other.doStuff`. So we want to increment a freeze variable? Then we need to supply this variable first too this actor. So first we need the script actor script.

Let's assign a variable `public int freezeCounter = 0f` on top.

Now we can access that variable from the `ProcessTouch` method and alter it. `other.freezeCounter = 2000` in milliseconds. Whenever an actor is hit he gets his `freezeCounter` set to 2000.

Now we need to make sure the actor is not able to move. We could wrap all the actors actions in a if statement stating `if (freezeCounter <= 0)` and he will be frozen for it's entire life. The last step is to decrease the `freezeCounter` by the amount of miliseconds since the last frame often called something like deltaTime.

The best lesson you should learn from this is to break down your problem into small steps. Try to define these steps and look around on Google for answers, like I did for the `Projectile Collision`.

However there might be a view catches. I'm not sure what the definition of actor is in UDK but basically anything that can be hit seems to be an actor. You might have to check in the `ProcessTouch` method if an actualy player or character has been hit. Again I do not know the naming conventions but if you open a players script and it says something like `class Character extends Actor` then you can add the variable to the `Player` script. But then you will not be able to use `other.freezeCounter = xxxx`. Now you need to cast it:

if (other instanceof Character) //check if the actor is a character { (Player)other.freezeCounter = 2000; //cast other as a player and alter freezeCounter }

This should get you on your way, otherwise I strongly suggest you tell your teacher to learn you the basics of programming first before telling you to code in a engine you barely know and afaik is pretty much obsolete (could be wrong on my last statement).

---
Tags: c++, software-engineering, unreal
---


# Question
Title: Can UNet do Rigidbody2D prediction? (i.e. using gravity)
Having a `NetworkTransform` with `transformSyncMode` set to `SyncRigidbody2D` (as opposite to a plain `SyncTransform`) I assumed it would try to sync all physics, hence handling gracefully forces, especially gravity.

What I got instead, is a very simple linear interpolation, which smooths out the gravity, so that jumping up and down looks incredibly unnatural: I would have expected this wish a `SyncTransform` of course, but, given the name I would have expected `SyncRigidbody2D` to solve this sort of problem…

So, am I missing something and might I have some value set wrong, or what?

# Answer
SyncRigidBody2D will also update velocity and angular velocity (if syncSpin is set to true). It will not however, also sync the entire state of the physics simulation, just of the synced body.

One way to reduce pulsing would be to use curved interpolation to match the start and end velocities, however it seems Unity's NetworkTransform script does a linear interpolation.
> 2 votes

---
Tags: unity, interpolation, movement-prediction, unity-networking
---


# Question
Title: Unity C#: strange texture/sprite problems
I've been making a gallery style shooting game, like something you'd find at a carnival, with ducks to shoot. I'd made the game and it was all working fine. However opening it today, it doesn't look the same. There are some problems with the GUI graphics. They are drawn like this:

The other day when I finished it, it worked completely fine, and unfortunately I don't have an image of what it looked like when working. The code I've used to draw this is as follows:

```
void OnGUI() {
    GUI.Label (new Rect (10, 10, scoreLabel.texture.width, scoreLabel.texture.height), scoreLabel.texture);
    GUI.Label (new Rect (scoreLabel.texture.width - 7, 10, colon.texture.width, colon.texture.height), colon.texture);

    int tempWidth = 0;

    for (int i = 0; i < charArray.Length; i++) {
        if(i > 0) tempWidth += numbers[int.Parse (charArray[i - 1].ToString ())].texture.width * 2 / 5;
        GUI.Label (new Rect (135 + tempWidth, 13, 40, 30), numbers[int.Parse (charArray[i].ToString ())].texture);
    }
}

```

Previously when it was working, the settings for the sprite/texture wouldn't affect the sprite/texture being drawn. The settings (for the numbers) are as below:

Can anybody advise me on what to do? I've played with the settings, and restarted unity and my computer and had no luck. Thanks in advance!

# Answer
> 0 votes
The solution I found was to disable 'Generate Mip Maps'. Easy fix for me, just took a bit of messing around to find.

# Answer
> 0 votes
Since you mentioned legacy UI is not a necessity, you can check the tutorials for new UI. Some resources: Unity official tutorial

3D Buzz youtube tutorial much better

---
Tags: unity, textures, graphics, sprites
---


# Question
Title: Unity UI InputField does not consume the keyboard input
Unity UI: I have an input field in which I can type. Unfortunately, when I hit any of the movement keys, such as the space bar, I move while I'm typing which is not the effect I want. Is there a way to force the input field to consume the keyboard input so it doesn't also get picked up by the game? Or do I have to write the code in my game to do that for me. (Seems like it should be configurable at least).

# Answer
> 1 votes
Use a boolean variable to indicate at what point you should enter text and when not, then constrain the actions of his character in relation to the bool, ie:

```
public bool keyboradisactive;

if(keyboradisactive==false){
    // actions of the character
}else{
}

```

---
Tags: unity
---


title: Map a normal image to a cubemap

text:
# Question
Title: Map a normal image to a cubemap
How can I map a normal non T form image to a cube map?

and if there is no manner with which to do this, is it possible to, via DX11, split the image, as the image may be generated on the fly?

Cheers.

# Answer
Since you have a spherical panoramic photo it isn't too difficult luckily (:

Basically what you need to do is make a sphere, texture it with your picture, then render 6 times from the center of the sphere, once with the camera facing each of the directions of the cube.

You just need to make sure and give the camera a 90 degree field of view when rendering each face of the cube, and the resolution needs to be square (such as 1000x1000)

BTW you can use this technique with any 3d rendered scene to make a cubemap of it. You aren't limited to a spherical panorama photo on a sphere, you can render whatever geometry you want.

People often use this sort of technique for baking out reflection data, or for doing light probes and things like that. I have heard they also interpolate between samples sometimes, so maybe you are doing something similar :p
> 0 votes

---
Tags: c++, graphics, directx11
---


title: Rigidbody on UV animations

text:
# Question
Title: Rigidbody on UV animations
I know we need to add rigidbody if we are moving objects.In Unity 5 the performance of moving non rigidbody objects has been increased too.

Though I have doubt over ,Do I need to add rigidbody if I am animating only UVs without moving the object?

# Answer
> 1 votes
RigidBody is for simulating physics. It is not required to move a gameobject.

```
transform.position += new Vector3(1,0,0);

```

# Answer
> 0 votes
The Unity Manual page for colliders is very helpful.

**Rigidbodies** should be used for objects that move often and use physics, such as the main character in a game. You shouldn't use `transform.translate()` or `transform.position` on Rigibodies. Instead, use `Rigibody.AddForce()`.

**Static colliders** have a collider but no rigibody. They should be used for objects that never move, such as walls.

**Kinematic rigibody colliders** have a collider and rigibody with the `IsKinematic` box checked. These are for objects that normally act like static colliders but occasionally need to move.

Note that only certain pairings of these object types will cause a collision. See the table at the bottom of the Unity Manual page for colliders.

---
Tags: unity
---


# Question
Title: Why is the drag force multiplied by the inverse normalised velocity vector?
In pure physics texbooks, I'm seeing this formula to calculate fluid drag force:

It is clearly stated that it should be opposite to the velocity. Now to me that means, in pseudocode:

```
fd = get_drag(v) // using the above formula
if v < 0: fd = -fd

```

That is, if the velocity is negative the drag should be positive, so we invert the returned value.

However, in game code, game physics books and tutorials, I see people doing:

```
drag = -v
drag.normalise()
fd = get_drag(v)
fd *= drag

```

That is, we multiply the drag force by the (inverted) velocity unit vector.

This to me is logic in regard to the sign, but also **it scales down the drag force by a factor between 0 and 1**.

Which one is correct, and why?

PS: to be noted, normalisation involves square root, multiplications and divisions, so it's more expensive than a conditional check and subtraction.

# Answer
> 1 votes
**Both ideas are actually correct**, but the second code snippet seems wrong to me.

If it is the same `get_drag()` in both cases, then it should operate on a scalar, and return a negative number. It should be something like:

```
drag = v                 # No sign inversion here; get_drag() does it
drag.normalise()
fd = get_drag(length(v)) # Operate on a scalar
drag *= fd               # Get a vector

```

The first formula operates in one dimension, where the “opposite” of the velocity just means choosing a number that has the opposite sign (hence `-fd`).

The second formula operates in two or three dimensions, where a force “opposite” of the velocity has to be a scalar multiplied by a unit vector that goes in the opposite direction (hence drag.normalize()\`).

Your final assumption that the drag force is “scaled down” is erroneous: a normalised vector has size 1, so the drag force is not changed. Getting the length of `drag` will give you the original drag force `fd`.

---
Tags: physics, physics-engine
---


title: Detecting Groups for Formations

text:
# Question
Title: Detecting Groups for Formations
In Starcraft 2, unit formations are created when a "group" is generated from a command. Generally, the rules for a group are:

* All units in the group are in the same spatial "clump".
* All units in the group were given the same move command.
* If any unit in the move command is not in the clump, the group is broken and units move towards the destination individually.

How do I define a clump programmatically and detect in a unit is not in the clump?

# Answer
I read about this algorithm a few years back for finding groups of units: http://lab.polygonal.de/?p=120

It's called recursive dimensional clustering and also appears in game programming gems 2, and was written by Steve Rabin from Nintendo.

There are probably other algorithms but I personally haven't come across any formally described.

In a nutshell, how it works is that you have a list of objects that each have a min and max x and y (and z if needed). You sort the list across each axis and find groups of objects that overlap on at least one axis.

That might get weird with a large map, but you could limit it to a couple nearest grid cells or something.
> 1 votes

---
Tags: rts, behavior
---


# Question
Title: Is Update called based on screens refresh rate? MonoGame
My game is running 60fps (Because I'm using a 60hz monitor) but if I would use a 85hz monitor it would be running 85fps. My question is if update is called based on the screens refresh rate or if its limited to 60 calls per second

# Answer
As far as I know, the fixed timestep in Monogame is 60 per seconds, regardless of the monitor refresh rate. The statement "it runs 85fps because my monitor refresh rate it 85hz" is false.

It just *tries* to give you 60 updates per second. It cannot *guarantee* it does, therefore using logic based on elapsed gametime is the best way to go.

If you want another timestep than 60, change the property `TargetElapsedTime` to the desired value. Again, this is unrelated to the refresh rate of your monitor since you can set the value yourself.

Read this http://blogs.msdn.com/b/shawnhar/archive/2007/07/25/understanding-gametime.aspx for more information on how it is implemented in XNA (Monogame is based on this).
> 1 votes

---
Tags: monogame, frame-rate, vsync
---


# Question
Title: Does fixed time step deltaTime get higher if the computer can't handle it?
If you use fixed time step and set it to for example 0.0166667 does it ever go up if the computer can't handle 60 updates/ticks per second?

# Answer
The answer is basically no, most fixed timesteps don't adjust the timestep if they cant keep up.

The actual solution to this problem used depends on the needs of your game and the reasons that it can't keep up.

If the reason that it can't keep up is rendering on the GPU, that means that the CPU is able to do more work even though the GPU isn't. In this case, you may opt to have your game run multiple simulations for each render, to keep the simulation caught up to real time.

Note that if your game goes a lot faster than your fixed update time, you may also opt to do multiple renders between simulation updates, and maybe do a linear interpolation between last and next simulation datas to make a smoother looking simulation.

If it really just unable to keep up at all, often games will be ok with not keeping up with real time and just letting the game run more slowly, but keeping the time step the same.

The reason most fixed timestep games don't adjust time steps when they run too slowly is that adjusting the time step at all ever makes you lose whatever benefits of fixed time steps that made you decide to use them - like deterministic simulation, or consistent physics behaviors.
> 0 votes

---
Tags: fixed-timestep
---


title: Phong lighting model - R vector

text:
# Question
Title: Phong lighting model - R vector
In Phong lighting model a vector R is used to calculate the spectral component of light. The equation used to obtain it is

```
R = 2(N•L)N - L

```

I can't understand why we use this equation. Could someone give me a demonstration of how we obtain this equation?

# Answer
> 2 votes
The equation is a consequence of the symmetry of the reflection of the light about the normal:

We know from the law of reflection that the angle between `R` and `N` is the same as the one between `L` and `N`. Therefore it's also clear that:

```
R•N = L•N (assume all are unit vectors)

```

From symmetry, it's also evident that

```
R - (R•N)N = - (L - (L•N)N)

```

Now we can replace `(R•N)N` with `(L•N)N` from the previous equation. So we have:

```
R - (L•N)N = - (L - (L•N)N)

```

Adding `(L•N)N` to both sides gives:

```
R = - (L - (L•N)N) + (L•N)N
  = - L + (L•N)N + (L•N)N
  = 2(L•N)N - L

```

---
Tags: lighting
---


title: Android multiplayer via bluetooth

text:
# Question
Title: Android multiplayer via bluetooth
How do I transfer game commands between 2 android devices via bluetooth first of all is possible to do this??If possible then someone please help in doing so.Thank u

# Answer
This is definitely possible. You should look at the Android developer documentation for bluetooth (Ocelot has posted the link).

At the minimum you will have to do this -

1. Discover the devices
2. Pairing and connecting devices
3. One of the device needs to become server. It will open a socket and listen for connection.
4. Other device(s) need to become client. They will try to connect to server.
5. Once a connection is established, client and server can exchange strings of message. These strings can be your game commands.

From my own experience, I would say pay good attention to architecture design for exchanging commands. As it may soon become messy.
> 0 votes

---
Tags: android, game-design, multiplayer
---


title: Can't render to FBO using a shader

text:
# Question
Title: Can't render to FBO using a shader
I've added functionality so that I can render to a framebuffer (for post-processing and stuff). I can successfully render to my framebuffer and then render that framebuffer, but anything with a shader does not render to my framebuffer. Rendering with the same shader worked before I added the framebuffer step.

Here's how I create my framebuffer:

```
// create the color texture
colorBuffer = GL.GenTexture();
GL.BindTexture(TextureTarget.Texture2D, colorBuffer);
GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba8, width, height, 0, PixelFormat.Rgba, PixelType.UnsignedByte, IntPtr.Zero);
GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Linear);
GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Linear);

// create the depth texture
depthBuffer = GL.GenTexture();
GL.BindTexture(TextureTarget.Texture2D, depthBuffer);
GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Depth24Stencil8, width, height, 0, PixelFormat.DepthStencil, PixelType.UnsignedInt, IntPtr.Zero);
GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Linear);
GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Linear);

// create the fbo
GL.GenFramebuffers(1, out fbo);
GL.BindFramebuffer(FramebufferTarget.Framebuffer, fbo);
GL.FramebufferTexture2D(FramebufferTarget.Framebuffer, FramebufferAttachment.ColorAttachment0, TextureTarget.Texture2D, colorBuffer, 0);
GL.FramebufferTexture2D(FramebufferTarget.Framebuffer, FramebufferAttachment.DepthStencilAttachment, TextureTarget.Texture2D, depthBuffer, 0);
GL.BindFramebuffer(FramebufferTarget.Framebuffer, 0);

```

And this is my shader code:

```
// VERTEX SHADER
#version 330

uniform mat4 world;
uniform mat3 worldIT;
uniform mat4 view;
uniform mat4 projection;
uniform mat4 textureTransformation;

in vec3 rPosition;
in vec3 rNormal;
in vec2 rTexCoord;
in vec3 rColor;

out vec3 vWorldPosition;
out vec3 vNormal;
out vec2 vTexCoord;
out vec3 vColor;

void main(void)
{
    vec4 tempWorld = world * vec4(rPosition, 1.0f);
    gl_Position = projection * view * tempWorld;

    vWorldPosition = tempWorld.xyz;
    mat3 normalSpace = mat3(world);
    vNormal = normalize(normalSpace * rNormal);
    vTexCoord = (textureTransformation * vec4(rTexCoord, 0.0f, 1.0f)).xy;
    vColor = rColor;
}

// FRAGMENT SHADER
#version 330

uniform sampler2D colorMap;

in vec3 vWorldPosition;
in vec3 vNormal;
in vec2 vTexCoord;
in vec3 vColor;

out vec4 fColor;

const vec3 ambientLight = vec3(0.1f, 0.1f, 0.1f);
const vec3 lightDir = vec3(0.0f, -1.0f, 1.0f);
const vec3 lightColor = vec3(1.0f, 1.0f, 1.0f);

void main(void)
{
    vec4 texel = texture(colorMap, vTexCoord);

    vec3 n = normalize(vNormal);
    vec3 l = normalize(lightDir);
    float nDotL = max(dot(n, l), 0.0f);

    vec4 diffuse = vec4((ambientLight + nDotL * lightColor) * vColor, 1.0f) * texel;

    vec4 specular = vec4(0.0f, 0.0f, 0.0f, 0.0f);

    fColor = diffuse + specular;
}

```

EDIT: It seems to be that, for some odd reason, my shader stopped outputting at all when I added the framebuffer support.

# Answer
> 3 votes
Maybe you are unbinding your framebuffer with the last call:

```
GL.BindFramebuffer(FramebufferTarget.Framebuffer, 0);

```

> ### void glBindFramebuffer(GLenum target, GLuint id)
>
> The first parameter, target, should be GL\_FRAMEBUFFER, and the second parameter is the ID of a framebuffer object. Once a FBO is bound, all OpenGL operations affect onto the current bound framebuffer object. The object ID 0 is reserved for the default window-system provided framebuffer. Therefore, in order to unbind the current framebuffer (FBO), use ID 0 in glBindFramebuffer().
>
> -- From the Songho OpenGL tutorials

# Answer
> 0 votes
After fbo creation call assert

```
assert(glCheckFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE);

```

I hope this will lead you to the right answer. See code errors here.

# Answer
> 0 votes
I had exactly this problem. To verify my operations to the framebuffer, I was drawing the framebuffer texture back to the screen using a simple GL\_QUAD. But it was not giving correct output since I was not setting glUseProgram(0) before drawing that quad. So the correct sequence of operations goes something like this:

```
glBindFramebuffer(GL_FRAMEBUFFER, myframebuffer );
glUseProgram(program_id);
...
// function call for drawing to framebuffer
...
glUseProgram(0); // <----- This is the important step
glBindFramebuffer(GL_FRAMEBUFFER, 0);

// draw my quad using texture that was bound to frame buffer
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, texture_framebuffer);
glBegin(GL_QUADS);

glTexCoord2f(0,0);
glVertex2f(0,0);

glTexCoord2f(1,0);
glVertex2f(1,0);

glTexCoord2f(1, 1);
glVertex2f(1, 1);

glTexCoord2f(0, 1);
glVertex2f(0, 1);

glEnd();

```

---
Tags: opengl, shaders, glsl, opentk
---


# Question
Title: Is GPU locality of reference worth worrying about?
Does locality of reference make as much of a difference to GPU performance as it does CPU performance?

For example, if I send 200 draw commands to the GPU, will I see a (potentially) noticeable difference if the data for each command is contiguous in memory instead of jumping around the buffers/texture maps?

Side question: I'm assuming the GPU ensures against false sharing issues by having most resources immutable. But in the case where they're not, is that why threads always do four fragments' worth of work?

# Answer
Locality of reference does matter, but you don't have to worry *that much*...because you don't have absolute control.

When using OpenGL/DirectX you usually have limited control over memory layout, the driver will do the rest. For example you can try multiple vertex buffers layouts, such as using interleaved or non-interleaved vertex data and depending on your data/driver/GPU performance will vary. Profile and choose what best fits your application.

For instance in GPU Gems Pipeline optimization, locality of reference is mentioned twice, the first:

> Access vertex data in a relatively sequential manner. Modern GPUs cache memory accesses when fetching vertices. As in any memory hierarchy, spatial locality of reference helps maximize hits in the cache, thus reducing bandwidth requirements.

And the second

> Optimize for the post-T&L vertex cache. Modern GPUs have a small first-in, first-out (FIFO) cache that stores the result of the most recently transformed vertices; a hit in this cache saves all transform and lighting work, along with all work done earlier in the pipeline. To take advantage of this cache, you must use indexed primitives, and you must order your vertices to maximize locality of reference over the mesh. There are tools available—including D3DX and NVTriStrip (NVIDIA 2003)—that can help you with this task.

In my opinion those recommendations follow what I have talking about, and imply that you don't have absolute control over memory layout, yet what you have control over, for example how each VBO vertices are laid out can have an effect on performance.

If your application is having a performance hit, you should first detect the bottleneck, it might not be a problem data locality of reference, but it might by because there huge amount data with no culling, for example you are not performing frustum culling ..etc You can check my answer here on the topic.

I think you should worry more about locality of reference when using OpenCL/CUDA were you have often absolute control over memory layout.
> 10 votes

# Answer
Originally, GPUs were only used for multimedia applications which show little data reuse. As GPUs become increasingly used for general-purpose applications (hence, the term GPGPU), they are now featuring large size hardware-managed caches, for example, Fermi GPU has 768 KB of last-level cache, the Kepler GPU has 1536 KB of last-level cache, and the Maxwell GPU has 2048 KB of last-level cache. This, along with a large body of research on GPU caches shows that data locality is definitely important for GPUs. See my survey paper for details and reference for the above.
> 3 votes

---
Tags: performance, gpu
---


# Question
Title: Objects phasing through each other in physics engine
I'm writing my own physics engine right now (following this tutorial), but I'm running into some problems. Sometimes on collision, objects will just phase through each other instead of bouncing off of each other.

Is there any way I can fix this?

```
public static void fixCollision(final RectObject a, final RectObject b) {
    final Vec2D normal = collisionNormal(a, b);

    // Calculate relative velocity
    final Vec2D rv = b.velocity.minus(a.velocity);

    // Calculate relative velocity in terms of the normal direction
    final float velAlongNormal = rv.dotProduct(normal);

    // Do not resolve if velocities are separating
    if (velAlongNormal > 0) {
        return;
    }

    // Calculate restitution
    final float e = Math.min(a.restitution, b.restitution);

    // Calculate impulse scalar
    float j = -(1 + e) * velAlongNormal;
    j /= a.getInvMass() + b.getInvMass();

    // Apply impulse
    final Vec2D impulse = normal.multiply(j);
    a.velocity = a.velocity.minus(impulse.multiply(a.getInvMass()));
    b.velocity = b.velocity.plus(impulse.multiply(b.getInvMass()));

    positionalCorrection(a, b);
}

private static void positionalCorrection(final RectObject a, final RectObject b) {

    final Rectangle2D r = new Rectangle2D.Float(a.min.x, a.min.y, a.width(), a.height()).createIntersection(new Rectangle2D.Float(b.min.x, b.min.y,
            b.width(), b.height()));

    final Vec2D normal = collisionNormal(a, b);
    // penetration is the min resolving distance
    final float penetration = (float) Math.min(r.getWidth(), r.getHeight());
    final float percent = 0.01f; // usually .2 to .8
    final float slop = 0.1f; // usually 0.01 to 0.1
    final Vec2D correction = normal.multiply(Math.max(penetration - slop, 0.0f) / (a.getInvMass() + b.getInvMass()) * percent);
    a.min = a.min.minus(correction.multiply(a.getInvMass()));
    a.max = a.max.minus(correction.multiply(a.getInvMass()));

    b.min = b.min.plus(correction.multiply(b.getInvMass()));
    b.max = b.max.plus(correction.multiply(b.getInvMass()));
}

private static Vec2D collisionNormal(final RectObject a, final RectObject b) {
    final float w = 0.5f * (a.width() + b.width());
    final float h = 0.5f * (a.height() + b.height());
    final float dx = a.center().x - b.center().x;
    final float dy = a.center().y - b.center().y;

    if (Math.abs(dx) <= w && Math.abs(dy) <= h) {
        /* collision! */
        final float wy = w * dy;
        final float hx = h * dx;

        if (wy > hx) {
            if (wy > -hx) {
                /* collision at the top */
                return new Vec2D(0, -1);
            } else {
                /* on the left */
                return new Vec2D(-1, 0);
            }
        } else {
            if (wy > -hx) {
                /* on the right */
                return new Vec2D(1, 0);
            } else {
                /* at the bottom */
                return new Vec2D(0, 1);
            }
        }
    }
    throw new IllegalArgumentException("Rectangles must be colliding");
}

```

RectObject

```
public class RectObject extends GameObject {
    // upper left
    public Vec2D min;
    // bottom right
    public Vec2D max;

    public Vec2D center() {
        return new Vec2D((max.x + min.x) / 2, (max.y + min.y) / 2);
    }

    @Override
    public void update() {
        min = min.plus(velocity);
        max = max.plus(velocity);
    }

    public float width() {
        return max.x - min.x;
    }

    public float height() {
        return max.y - min.y;
    }
}

```

GameObject

```
public abstract class GameObject {
    public static final float INFINITE_MASS = 0;

    private float invMass;
    public Vec2D velocity;
    public float restitution;

    public abstract void update();

    public float getMass() {
        if (invMass == 0) {
            return INFINITE_MASS;
        }
        return 1 / invMass;
    }

    public float getInvMass() {
        return invMass;
    }

    public void setMass(final float mass) {
        if (mass == INFINITE_MASS) {
            invMass = 0;
        } else {
            invMass = 1 / mass;
        }
    }

    public void applyForce(final Vec2D force) {
        velocity = velocity.plus(force.multiply(invMass));
    }
}

```

# Answer
There was something wrong with my `collisionNormal` method, where the left and right vectors were actually flipped. This made collisions along the x axis actually push the objects into each other.

```
if (wy > hx) {
    if (wy > -hx) {
        /* collision at the top */
        return new Vec2D(0, -1);
    } else {
        /* on the left */
        return new Vec2D(-1, 0);
    }
} else {
    if (wy > -hx) {
        /* on the right */
        return new Vec2D(1, 0);
    } else {
        /* at the bottom */
        return new Vec2D(0, 1);
    }
}

```

turned into

```
if (wy > hx) {
    if (wy > -hx) {
        /* collision at the top */
        return new Vec2D(0, -1);
    } else {
        /* on the left */
        return new Vec2D(1, 0); // flipped
    }
} else {
    if (wy > -hx) {
        /* on the right */
        return new Vec2D(-1, 0); // flipped
    } else {
        /* at the bottom */
        return new Vec2D(0, 1);
    }
}

```
> 1 votes

---
Tags: java, collision-detection, physics, collision-resolution
---


# Question
Title: How can I easily assign an array in the inspector?
If you make a public array class member in Unity, you can individually assign objects to the array in the inspector menu. It looks like this:

However, this is cumbersome if you you want to assign the same array to many objects. It's easy to do this programatically, but I'd rather not hard-define the array in code - it makes moving/renaming the objects harder.

If I want to pass the same array to multiple game objects, how can I do it more efficiently than dragging each individual element into the inspector?

# Answer
You can actually add multiple items to an array in one go. Just lock the inspector with the GO that contains the list, select the multiple gameobjects and drag & drop them into the inspector. No need to do anything special.
> 4 votes

# Answer
It sounds like you might want an editor script:

> http://docs.unity3d.com/Manual/editor-CustomEditors.html

You could place a button on your object's inspector that would take the current scene selection (http://docs.unity3d.com/ScriptReference/Selection-gameObjects.html) and set the values to be the contents of your array. Doing it this way would require that you select the object, lock the inspector to that object, then select all the explosion pieces you want, and press the button on the inspector to load the selection into the prefabs array.
> 0 votes

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


# Question
Title: What size should i use for my game design?
i am currently working on a android game by using libgdx and i am designing graphics with ps for it. I want my game looks the same quality for different screen sizes but i dont know in which size should i design my graphics. For example if i design the graphics 200x200 size and for a bigger screen i should make it bigger by resizing with code. But this will demage the graphic which is something i dont want. What i think is to make a much bigger graphic then shrink for ever screen sizes. is that right approach to do? Or there is a better way. And also if this approach what size should i use for portrait game. Like 800 width is good? Thanks for ur answers.

# Answer
> 0 votes
I'll assume you are talking about a 2D game or at least a 2D UI. Well, if you think you need to create graphics for 1920x1080 then you should go for it. If you setup a viewport properly libgdx does all the scaling for you. Personally I have my viewport represent a 1280 x 720 area. You won't see any difference on phones, I barely even notice the difference on descent sized tablets. But I'm not a great 2D artist, lol. Anyway this saves a ton of work so keep that in mind.

So what you basically do is create graphics that fit your viewport or camera size. If you are setting the screen size to 1920 x 1080 I guess you should always create your 2D art for that size. For 3D it's different, higher resolution will give you crispier edges on your models. Here I would use a high resolution camera for rendering the 3D and a lower resolution viewport to overlay the UI, again unless you want your 2D to look really crisp on bigger screens.

---
Tags: android, libgdx, graphics-design
---


title: How do I make an endless road in Unity?

text:
# Question
Title: How do I make an endless road in Unity?
Basically I created 2 quads side by side and I added a road texture. I used transform.translate so that the road moves, but I am trying to make the road endless by making the 2 quads reposition themselves in front of the current quads repeatedly so that when I add a player the road is endless. Any way I could do this?

# Answer
> 6 votes
You could have 2 sufficiently long road segments. Place them one after another. When player moves from one road segment to another, remove the segment which is (now) behind the player, to the front of the current segment.

# Answer
> 3 votes
Many infinite runners scroll the road rather than move the player forwards on the road to make the road truly infinite. You can do this with 2 alternating game objects.

```
public GameObject[] RoadPieces = new GameObject[2];
const float RoadLength = 100f; //length of roads

const float RoadSpeed = 5f; //speed to scroll roads at
void Update ()
{
    foreach (GameObject road in RoadPieces)
    {
        Vector3 newRoadPos = road.transform.position;
        newRoadPos.z -= RoadSpeed * Time.deltaTime;
        if (newRoadPos.z < -RoadLength / 2)
        {
            newRoadPos.z += RoadLength;
        }
        road.transform.position = newRoadPos;
    }
}

```

Just space the roads out correctly in the beginning, and this'll scroll them forever.

# Answer
> 0 votes
Well, the answer of Vinayak Garg is good but since you work with perspective this won't be perfect. This is basically paralax mapping and works great for 2D games. But here you want to have the road dissapear in the horizon probably. If your road is straight then just extent on this technique and add many pieces until it is looking good. Whenever you leave a piece behind move it to the front.

If you want a curvy rode you have to look in procedural algorithms to generate a path for you can use pieces to correct this path. Perlin noise for example can be used for "infinite" randomization. They use it for minecraft in 3D, you just probably just need a 1D variant that just controls the the curve of the road. ANyway, this is a lot harder to implement.

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


# Question
Title: 2d mmo open world connection and reconnection
I am trying to create an 2d html5 open word (the sprite does not have any fancy flare, just shapes around) with only maximum of 10 player at once. My question is how to create a seamless join for new player join when 5 others have already started roaming in the world? in the other words, how to maintain synchronization for a new player for all updates that is happenning in new world.

I know pub sub can do the trick but it is very wasteful to catch up from start of the queue. How can a new player get a refresh of the current state and continue to stream from movement from other exisitng player? Thanks.

# Answer
The typical way to do this is to send the new player the current state of the world / simulation, and then make sure and send any new events to them (even while they load into the map, to be processed when they are done loading) so that they are sure to be up to date.

If this doesn't work for your needs for some reason though, let us know, since different game requirements have different "best answers" to this.
> 1 votes

# Answer
Most of the time, the size of the world doesn't matter as much as the number of players. For just 10 players, you can get away with a lot of things.

Unless the world changes, syncing game states would be trivial. You could just have every player send their properties (i.e. position, rotation, health, etc.) to all the other players.

If the world changes, there is the issue of determining what the state of the world is. You could have one player be the "Master" of the game and have the final say of what's what in the world. When a new player joins, the new player requests the world state from the master client.

The cleanest way would be with an authoritative server but an authy server is more difficult to develop and manage than just giving that authority to a client.
> 0 votes

---
Tags: html5, mmo, synchronization
---


title: Need Help with Hovering Mouse Code

text:
# Question
Title: Need Help with Hovering Mouse Code
I am new to Unity and C#. I have a script here for a card game where my card is supposed to move up and down when the pointer is hovered over the card. But when my point hovers over each card, they all move up together and not separately. They also move when they touch other UI elements, regardless of what they are. I am doing something wrong but I don't know what.

Here is my code:

```
//My Codes I needs help on.
   using UnityEngine;
   using System.Collections;
   using UnityEngine.EventSystems;

   public class Mouse_Detector_Temp : MonoBehaviour {
    public bool hovered;
    // Use this for initialization
    void Start ()
    {
        hovered = false;
    }

    // Update is called once per frame
    void Update ()
    {
        //This checks to see if you are hovered over.
        if (EventSystem.current.IsPointerOverGameObject ())
        {
            Debug.Log(gameObject);
            if (hovered == false)
            {
                transform.Translate(0,10,0);
                hovered = true;
            }
        }
        else
        {
            if (hovered == true)
            {
                transform.Translate(0,-10,0);
                hovered = false;
            }
        }
    }

}

```

Additional Information: This code is run UI elements that are part of a Canvas (only way to do it, so that should be obvious).

# Answer
I figured out how to fix this myself. This took me days just to find an answer to this question. I hope other people who find this question can use this answer.

```
//My Codes I needs help on.
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using UnityEngine.EventSystems;

public class Mouse_Detector_Temp : MonoBehaviour, IPointerEnterHandler, IPointerExitHandler {
    private bool hovered;

    // Use this for initialization
    void Start ()
    {
        hovered = false;

    }

    // Update is called once per frame
    void Update ()
    {

    }

    public void OnPointerEnter(PointerEventData eventData)
    {
        Debug.Log(gameObject);
        if (hovered == false)
        {
            transform.Translate(0,10,0);
            hovered = true;
        }
    }

    public void OnPointerExit(PointerEventData eventData)
    {
        transform.Translate(0,-10,0);
        hovered = false;
    }
}

```

First I found out. For graphics, you need to use OnPointerEnter and OnPointerExit instead of EventSystem.current.IsPointerOverGameObject ()

And IT WASN'T WORKING, because... I was not aware I needed to add this:

public class Mouse\_Detector\_Temp : MonoBehaviour, IPointerEnterHandler, IPointerExitHandler

To use OnPointerEnter and OnPointerExit.

I figured it out.
> 1 votes

# Answer
I am not quite sure what this does:

```
if (EventSystem.current.IsPointerOverGameObject ())

```

But for me it seems as if this method just checks, if the pointer hovers over **any** gameobject. And as you are checking this, for each card, in each frame, I think it is obvious, why you get that effect. Again: this only holds if the method does what I think.

You can overcome this problem by somehow checking, if the hovered object is also the actual object. And as you already have an event system, it would be nicer to register all the cards to an hover event and just do the moving in the update method.
> 1 votes

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


# Question
Title: Phaser / PIXI: World size vs. Stage size
I am using Phaser to build a zoomable / pannable 2D map with the intended functionality being that the home camera position is always in the middle of the World coordinates. I have a problem where my Stage (Phaser.Stage) size is slightly smaller than my explicitly-set World coordinates, and it appears that my groups (Phaser.Group) within my world (Phaser.World) are the same size as the Stage (less than my world size).

From http://docs.phaser.io/Phaser.World.html:

> By default a world is created the same size as your Stage.

I am aware that Stage comes from PIXI and is used for rendering:

> A Stage represents the root of the display tree. Everything connected to the stage is rendered.

From http://docs.phaser.io/Phaser.Stage.html

> The Stage controls root level display objects upon which everything is displayed. It also handles browser visibility handling and the pausing due to loss of focus.

I have learned from the html5gamedevs.com forums that Camera (Phaser.Camera) does not have zoom capabilities (or multiple cameras) built-in at the time of writing this question (Phaser v2.1.1 | Pixi.js v1.6.1). Based on my experimentation so far, I believe that the camera translation (x, y) works by translating the world coordinates. However, I'm still running into some escaping issues regarding a camera offset with my zoom system.

I have not yet found any examples online (including the official Phaser examples) of working directly with the Stage (Phaser.Stage), or how the stage dimensions play into the World, Camera, and Groups.

What is the relationship between the Stage and the World in Phaser?

# Answer
The dimensions of the Stage (and the parent Group containing the Display Objects) is equal to the absolute value of the combined dimensions and positions of every Display Object in the Group, on the Stage, and in the World.

Example: if you have a World that is 100 (width) x 100 (height) but bounded to -50, -50, 50, 50 such that 0,0 is in the center of the World, and you have 2 display objects that both have the same dimensions of 10 (width) x 10 (height), then the width and height of the Stage will vary based on their placement within the world.

If the first display Object is at xy location (-50, -50), and the second display object is at xy location (40, 40), then the dimensions of the Stage and the parent Group will be 100 x 100.

However, if they are placed at (-10, 0) and (0,0) respectively, than the dimensions of the Stage and the parent Group will be 20 (width) x 10 (height).

As of Phaser 2.2.2, the camera implementation appears to move the World coordinates only; zooming / panning must be poly-filled using Group scaling and adjusting the pivot property of the parent Group.

EDIT: Zooming is now working in later versions of Phaser.
> 1 votes

---
Tags: 2d, camera, maps, phaser
---


# Question
Title: Cardboard on iPhone 5 doesn't render on stereo
Has anyone ran into this?

I'm on Unity 5.1.1p3, Cardboard Unity Integration v0.5 (5/28/2015) and an iPhone 5 running iOS 8.3 (12F70).

I made a game that uses Cardboard and on an iPhone 6 the screen renders as expected: two offset cameras. On an iPhone 5 however, while the screen does show the 2 viewport masking and the distortion correction, it's actually a single camera that is being rendered, defeating the purpose of Cardboard.

Here's what I mean. This is the iPhone 6, as expected:

And this is the iPhone 5, which is wrong:

Any ideas?

Some extra info:

The iPhone5 can only use GLES2. It doesn't support ES3 or Metal. But what I did notice is that if I make a build for GLES2 the first time the app runs on the device (be it iPhone 6 or 5), when the Cardboard camera gets enabled, the app crashes:

If then I quit the app and start it again from the phone without it being hooked up to Xcode, on the iPhone5 I get the wrong rendering I've shown while in the iPhone 6 the app just crashes again. And if instead I make my build with automatic graphics API detection, what happens is that on iPhone6 it goes to Metal mode and so it works fine and on the iPhone5 it goes to GLES2 mode which, as stated before, crashes if attached to Xcode but otherwise just runs only that with the wrong rendering.

# Answer
I found the issue. Though I'm still not 100% sure why this is so. But it turns out that if using GLES2 and using any post processing / screen space effects from Unity, I have to switch the Cardboard SDK's direct rendering mode off. Doing that (or alternatively not using post processing at all on the cameras) makes the game render correctly on GLES2.

A separate issue that still remains is why the first time I attempt running a fresh build from within Xcode, the app will crash while creating the render buffers. After that initial crash, starting the app subsequent times from within the springboard does not crash.
> 0 votes

---
Tags: unity, ios
---


# Question
Title: Developing an iOS/Android game with the free Unity license - feasible?
I recall, when I looked up the Unity license comparison page several months ago, seeing that some iOS/Android features were disabled for the Free license. However I can't seem to find that page now, all I can find is http://unity3d.com/get-unity which isn't platform-specific.

But the Pro Android and Pro iOS licenses still exist, which means that there is SOME difference. I already know of the revenue limit and the mandatory Unity splash screen for Free. But are there any other differences? Notably, anything that would really impact the game's performance or flexibility?

Are there any serious iOS and Android game developers who use the Free license?

# Answer
First of all yes, of course you are able to create mobile games with the Unity free engine. Otherwise it would be silly to have added a feature like that in the free version. In the past free versions there was limited access to the engine but still plenty of tools to work with and complete a game.

Unity changed its license since unity 5.0, they had to since they felt the heat from Unreal Engine 4. You can use the complete engine with all the features now as long as your company does not earn more then $100,000 / year. The only drawback I can currently think off is the Unity splash screen; you cannot turn it off. But if you are developing with it,then you should be proud of it and embrace that splash screen :).

Other then that, the pro version offers some extra things, as:

* Cloud building.
* Analytics.
* Team Licensing.
* Access to Beta versions.
* Performance reports.
* Discount on asset store.
* Access to Unity source code.

Neither of these features important for a solo developer to build a game. Perhaps slightly when your game is near its final state when you want to test and they offer handy tools when your game is published.

Your final question is very much subjective. If you are really serious about creating games then you should grab the pro license in my "opinion". It gives you that bit of extra control and what is 75 euro / month for someone that is serious about it? I pay more then half of that for my phone each month.
> 1 votes

---
Tags: unity, android, ios
---


# Question
Title: Collision resolution moving Point to AABB with raycasting
This is probably trivial, but I'm having trouble making it work.

I have a 3-coordinate world of particles simulated with Verlet Velocity. I only care for collision between their centers and a few static AABBs.

**Essentially, I can't get a clean way of resolving a collision.**

For example, say I have a box with coordinates:

```
min = (0, -1, -384)
max = (512, 1, 0)

```

Any particle colliding with it should stop moving in the relevant direction, but continue moving in the others - not bounce off.

I have one particle at `pos` that in a single timestep wants to go to `newpos` (it's being pushed both downward and eastward):

```
pos = (-0.068037, 0.000000, -58.516845)
newpos = (0.014446, 0.000000, -58.555490)

```

Clearly, on the X axis there is a collision. My ray collider detects it and pops back the point where the ray intersects the AABB:

```
intersection = (0.000000, 0.000000, -58.548722)

```

**Now, if I just set the position to that point, at the next time step there will be a collision because the position will be exactly on the border of the AABB**.

This makes every particle "stick" to whatever box they collide with. In the previous example, I'd like to have the particle slide down the AABB wall according to its current velocity.

How can I do that?

# Answer
> 1 votes
Ok, I think I've solved (although I still don't understand completely why - so I'm not sure it will work in every case).

I'll post here the (Java) solution in case somebody else has this problem. Note I only call this if I already know there is a collision between the `to` point and the `b` box.

It should work anyway but do your tests in case you use it.

The initial code was taken from Toxiclibs and adapted to my min-max based AABBs, and merges together a ray intersection with a purely position-based collision response.

```
public static void clampPointOutsideBox(final Vect3D from, final Vect3D to, final Box b)
{
    ImmutableVect3D normal;

    final Vect3D min = b.getMinPoint();
    final Vect3D max = b.getMaxPoint();

    final Vect3D direction = Vect3D.sub(to, from).normalised();
    final Vect3D invDir = Vect3D.reciprocal(direction);

    final boolean signDirX = invDir.x < 0;
    final boolean signDirY = invDir.y < 0;
    final boolean signDirZ = invDir.z < 0;

    Vect3D bbox = signDirX ? max : min;
    final double xmindist = bbox.x - from.x;
    double tmin = xmindist * invDir.x;

    normal = signDirX ? ImmutableVect3D.xaxis : ImmutableVect3D.xaxisinv;

    bbox = signDirX ? min : max;
    double tmax = (bbox.x - from.x) * invDir.x;

    bbox = signDirY ? max : min;
    final double ymindist = bbox.y - from.y;
    final double tymin = ymindist * invDir.y;

    bbox = signDirY ? min : max;
    final double tymax = (bbox.y - from.y) * invDir.y;

    if ((tmin > tymax) || (tymin > tmax))
        return;

    // take the maximum of the t(x)min and tymin,
    // and take the correct normal now to save later
    // computations
    if (tymin > tmin)
    {
        tmin = tymin;

        normal = signDirY ? ImmutableVect3D.yaxis : ImmutableVect3D.yaxisinv;
    }

    // take the minimum of t(x)max and tymax,
    // we don't need the normal here
    tmax = Math.min(tymax, tmax);

    bbox = signDirZ ? max : min;
    final double zmindist = bbox.z - from.z;
    final double tzmin = zmindist * invDir.z;

    bbox = signDirZ ? min : max;
    final double tzmax = (bbox.z - from.z) * invDir.z;

    if ((tmin > tzmax) || (tzmin > tmax))
        return;

    // take the maximum of (txmin,tymin) and tzmin,
    // and take the correct normal now to save later
    // computations
    if (tzmin > tmin)
    {
        tmin = tzmin;

        normal = signDirZ ? ImmutableVect3D.zaxis : ImmutableVect3D.zaxisinv;
    }

    // take the minimum of (txmax,tymax) and tzmax,
    // we don't need the normal here
    tmax = Math.min(tzmax, tmax);

    final Vect3D isec = Vect3D.add(from, Vect3D.mul(direction, tmin));

    double scale = 0.01;
    double restitution = 1.0;
    isec.add(new Vect3D(normal).mul(scale));
    to.assign(isec.sub(direction.mul(restitution)));
}

```

---
Tags: collision-resolution, raycasting
---


# Question
Title: How can I move a ball to a clicked location using physics forces?
I have a ball as a sphere in my game and I'm viewing it from top down view. The ball is a rigid body.

When I click somewhere on the screen, I want the ball to be moved towards that direction using physics forces.

The ball needs to move only on the X and Y axes, the Z axis can be ignored.

Here is what I tried, but gives me some weird results. The script is attached to the ball:

```
// Use this for initialization
    void Start () {
        rb = gameObject.GetComponent<Rigidbody> ();
    }

    void Update () {

        //
        Vector3 v3 = gameObject.transform.position;
        Vector3 v3Mouse = Input.mousePosition;

        //
        Vector2 pointA = new Vector2(v3.x, v3.y);
        Vector2 pointB = new Vector2(v3Mouse.x, v3Mouse.y);

        //
        float Angle = Vector2.Angle(pointA, pointB);
        float angleRad = Angle * (Mathf.PI / 180);

        Debug.Log ("Angle: " + Angle);
        //
        float dx = Mathf.Cos (angleRad) * 10;
        float dy = Mathf.Sin (angleRad) * 10;

        //
        if (Input.GetMouseButtonDown (0)) {

            rb.velocity = new Vector3(dx, dy, 0);

        }

    }

```

What should I do here? When I click on the top of the screen, the ball should move up toward the mouse, and in all the other directions.

Any ideas?

# Answer
Vector mathematics! Assuming you're using Unity, you could use the inbuilt functions of Vector2:

```
transform.position = Vector3.MoveTowards(transform.position, target, speed);

```

Otherwise, here's how it's done - first, calculate the direction from point `A` to point `B`:

```
public static float Length(float x, float y) {
    return Math.Sqrt(x * x + y * y);
}

public static Vector2 Direction(Vector2 position) {
    return new Vector2(position.X / Length(position.X, position.Y), position.Y / Length(position.X, position.Y);
}

```

Direction will return a Vector2 representing the direction towards the position as values from -1 and 1 on both the X and Y axis. This is a Normalized Vector. In the case of finding the direction towards a target, you need to pass it the target's position subtracted by the current position:

```
Vector2 direction = Vector2.Direction(target - position);

```

You can use this to move your ball to the desired position:

```
position += direction * speed;

```

And you can also use it to make the object rotate towards (face) the desired position, although with it being a ball, it doesn't seem necessary, but regardless:

```
float angleInRadians = Math.Atan2(direction.Y, direction.X);
float angleInDegrees = angleInRadians * 180 / Math.PI;

```
> 3 votes

---
Tags: physics
---


title: Need help with making a journal system

text:
# Question
Title: Need help with making a journal system
My game uses a system similar to Metroid Prime's logbook, in that it logs things the player encounters and discovers on their journey, categorizing it, etc.

I want to write out all of the possible entries they can find, with the categories and all, but I need a system similar to what'll be in the final product to toy with, and use as an example for when it gets implemented into the game itself.

A click through menu sort of thing. Writing out all of these long descriptions would be too much of a hassle in a regular text document (and would make it FAR too long), and doing it through HTML or something sounds far too messy.

Basically, I want something, like an app, that I can edit, and that'll let me click through the categories till I get to the entry I want, which should display on the side. Here's a really terrible example of what I'm looking for.

I'm probably stupid for asking this, and there's likely an extremely obvious solution to this, but I have a thousand other things related to the game to think about, and Googling didn't result in anything.

# Answer
> 1 votes
I would guess an XML file suits your need? Create a structure like this:

```
<categories>
   <category name="Animals">
      <item key="dog">
         <title>Dog</title>
         <description>Man's best friend</description>
      </item>
   </category>
<categories>

```

Load the structure in your game, add properties to track if the player has unlocked the entry. Each object in your game world would have a "key". If scanned the entry corresponding to that key in the catalog will be unlocked.

It would be trivial to create a your own tool to edit the XML structure (you could even just use your favorite text editor for it).

---
Tags: gui, assets, text
---


# Question
Title: Does Transform.childCount not work correctly?
This is my code:

```
void OnTriggerEnter(Collider collide) {
  if (collide.gameObject.transform.tag == "Laser") {
    Debug.Log ("Inside If");
    Transform resourceTransform = collide.transform;
    Transform[] tf = new Transform[resourceTransform.childCount];
    for(int i = 0; i<= resourceTransform.childCount-1; i++){
      tf[i] = resourceTransform.GetChild(i);
    }

    Debug.Log ("Child Count Before: " + resourceTransform.childCount);
    resourceTransform.transform.DetachChildren();

    Debug.Log ("Child Count After: " + resourceTransform.childCount);
    Vector3 centerOfMass = resourceRb.centerOfMass;
    Explode (tf, centerOfMass);
  }
}

```

Everything is working fine, except the childCount property is always zero and that screws everything else up. Here's an image of the hierarchy:

The script is on cube1 and the object has 12 or so children. So why is childCount equal to zero? Is it a problem with Unity itself?

# Answer
collide.Transform refers to the object you are colliding with. Change this line

```
Transform resourceTransform = collide.transform

```

to

```
Transform resourceTransform = transform

```

and try again
> 2 votes

---
Tags: unity, transformation
---


title: Client and server loops don't match up

text:
# Question
Title: Client and server loops don't match up
I'm trying to build a small networked game using WebGL and NodeJS. I have a basic client and server setup and I'm at the point where I'm trying to implement dead reckoning to simulate what happens on the client.

I have a odd problem which I'm not really sure how to fix, the game loops for my client and server don't seem to match up and the client one always seems to be faster. I'm hosting my server on the same system as my client right now and I'm logging every frame for the two. If I log it for longer than 5seconds the server starts to get behind by 10-20 frames and the gap just gets bigger and bigger over time. There isn't really anymore processing that is happening on the server than on the client at the moment because I'm working with a really basic example right now.

My loop for both right now look something like this:

```
var loopDelay = 16.666666666666666666666666666667;

function loop()
{
    setTimeout(function() {
        update();
        loop();
    }, loopDelay);
}

```

On the client I did have something like this:

```
function loop()
{
    setTimeout(function() {
        update();
        requestAnimationFrame(loop);
        draw();
    }, loopDelay);
}

```

But I removed it and copied the server one temporarily when I started running into this problem to make sure it wasn't that.

What can I do to make the two sync up perfectly?

Thanks

# Answer
> 2 votes
It's hard to tell for sure from the information given but it sounds like what you are trying to do is make the client and server run deterministic code such that if they start with the same starting state and process things on the same loop numbers that they will result in the same values for the same calculations. Is that correct?

One thing you are doing correctly is that you seem to have an update function that doesn't use elapsed time to do calculations (like how far something moves). That makes it frame rate independent which is important for preserving determinism.

However, it looks like you are relying on server code and client code to come up with the same results for the same code. That is tricky to get right using floating point math, and I believe is impossible if you ever use things like sine and cosine.

The way this is usually done is by implementing fixed point math using integers only. I haven't seen anyone do that in JavaScript. I don't run in JavaScript circles so it might be common, but I'm not sure.

Anyways, you are going to have a heck of a time making sure client and server always match up, even if you find a way to share code between the two without copy/pasting code or implementing every feature twice (both of which are error prone and make a lot of work!)

I think your better option would be to have one side (client or server) be authoritative and have the other side interpolate between data it receives.

In games with a low number of players in a match (like an fps where you can have up to 16 players), the server being authoritative is pretty reasonable and is more secure against cheating.

In games with high player counts (like MMOs), its usually the client that is authoritative believe it or not, and the server just makes sure a player isnt moving more quickly than they should be able to, jumping higher than they should etc.

Let's say he server is authoritative. You could have the client use dead reckoning and also player input to guess where things are going to be and extrapolate data. When the server sends an authoritative answer about these things though, the client would either need to "pop" the values to the right values or blend to the right values over a short amount of time to hide the fact that it was wrong.

Another way though would be for the client to be one simulation frame behind the server, so it always has knowledge of the last and next frame of data, and it can interpolate between those sets of data. Going this route, there is no wrong extrapolated data, but there is some input latency added. (Which you can again hide with client side prediction to get a blend of the two solutions!)

---
Tags: networking, game-loop, synchronization, fixed-timestep, client
---


title: How to Set HLSL Shader Input Textures?

text:
# Question
Title: How to Set HLSL Shader Input Textures?
Very simple question. With C++/Direct9, I'm creating a texture as RenderTarget with a full screen quad, creating a scene, setting a HLSL pixel shader, copying the image and then call Present.

1) How does the shader's input texture get defined? Does it get configured automatically, and if so how? Let's take this very basic sample shader.

```
sampler2D TexSampler : register(S0);

float4 main(float2 uv : TEXCOORD) : COLOR
{
    float4 color = tex2D(TexSampler, uv);
    return float4(1 - color.rgb, color.a);
}

```

2) Where in the chain does the shader's magic get applied? Somehow it's not being applied and I don't know where to look.

3) What about shaders that take 2 textures as input, how do I configure the input?

```
sampler s0 : register(s0);
sampler s1 : register(s1);
float4 p0 :  register(c0);
float2 p1 :  register(c1);

#define width  (p0[0])
#define height (p0[1])
#define px (p1[0])
#define py (p1[1])

```

When creating the pixel shader, I get a PixelConstantTable that allows me to define C0 and C1, and how do I feed in all the other information?

I'm trying to make the question as basic as possible to get a quality answer. I found PSSetShaderResources in DX11 which seems to be getting close but what's the equivalent in DX9?

Thanks!

Edit: Is it possible that DirectX9 doesn't support passing multiple textures in such a way, and that DirectX11 would be required?

# Answer
> 1 votes
Answer: IDirect3DDevice9::SetTexture

---
Tags: c++, shaders, directx, hlsl, directx9
---