# Question
Title: Player launches into air when hitting steep slopes
I've been debugging an issue where when my player is moving forward at high speeds (I have configurable movement modes for an overview/overwatch mode) if they are in walk mode and hit a steep slope the player gets launched into the air as though they've bounced or jumped. So far I've narrowed it to something in this portion of the code (called from Update() with a conditional flag):

**CharacterMotor.js (SNIPPET)**

```
private function UpdateFunction () {
    // We copy the actual velocity into a temporary variable that we can manipulate.
    var velocity : Vector3 = movement.velocity;

    // Update velocity based on input
    velocity = ApplyInputVelocityChange(velocity);

    // Apply gravity and jumping force
    velocity = ApplyGravityAndJumping (velocity);

    // Moving platform support
    var moveDistance : Vector3 = Vector3.zero;

    // Save lastPosition for velocity calculation.
    var lastPosition : Vector3 = tr.position;

    // We always want the movement to be framerate independent.  Multiplying by Time.deltaTime does this.
    var currentMovementOffset : Vector3 = velocity * Time.deltaTime;

    // Find out how much we need to push towards the ground to avoid loosing grouning
    // when walking down a step or over a sharp change in slope.
    var pushDownOffset : float = Mathf.Max(controller.stepOffset, Vector3(currentMovementOffset.x, 0, currentMovementOffset.z).magnitude);
    if (grounded){
        Debug.Log(currentMovementOffset);
        currentMovementOffset -= pushDownOffset * Vector3.up;
    }
    // Reset variables that will be set by collision function
    movingPlatform.hitPlatform = null;
    groundNormal = Vector3.zero;

    // Move our character!
    movement.collisionFlags = controller.Move (currentMovementOffset);

    movement.lastHitPoint = movement.hitPoint;
    lastGroundNormal = groundNormal;

    // Calculate the velocity based on the current and previous position.
    // This means our velocity will only be the amount the character actually moved as a result of collisions.
    var oldHVelocity : Vector3 = new Vector3(velocity.x, 0, velocity.z);
    movement.velocity = (tr.position - lastPosition) / Time.deltaTime;
    var newHVelocity : Vector3 = new Vector3(movement.velocity.x, 0, movement.velocity.z);

    // The CharacterController can be moved in unwanted directions when colliding with things.
    // We want to prevent this from influencing the recorded velocity.
    if (oldHVelocity == Vector3.zero) {
        movement.velocity = new Vector3(0, movement.velocity.y, 0);
    }
    else {
        var projectedNewVelocity : float = Vector3.Dot(newHVelocity, oldHVelocity) / oldHVelocity.sqrMagnitude;
        movement.velocity = oldHVelocity * Mathf.Clamp01(projectedNewVelocity) + movement.velocity.y * Vector3.up;
    }

    if (movement.velocity.y < velocity.y - 0.001) {
        if (movement.velocity.y < 0) {
            // Something is forcing the CharacterController down faster than it should.
            // Ignore this
            movement.velocity.y = velocity.y;
        }
        else {
            // The upwards movement of the CharacterController has been blocked.
            // This is treated like a ceiling collision - stop further jumping here.
            jumping.holdingJumpButton = false;
        }
    }
    Debug.Log("Before the bounce test: " + tr.position);
    // We were grounded but just loosed grounding
    if (grounded && !IsGroundedTest()) {
        grounded = false;
        Debug.Log("Before bounce?");

        SendMessage("OnFall", SendMessageOptions.DontRequireReceiver);
        Debug.Log("1. Lost grounding, maybe bounced?");
        // We pushed the character down to ensure it would stay on the ground if there was any.
        // But there wasn't so now we cancel the downwards offset to make the fall smoother.
        Debug.Log(tr.position);
        tr.position += pushDownOffset * Vector3.up;
        // MIGUET

        // END MIGUET
        Debug.Log(tr.position);
//      Debug.Break();
    }
    // We were not grounded but just landed on something
    else if (!grounded && IsGroundedTest()) {
    Debug.Log("3. Found my grounding");
        grounded = true;
        jumping.jumping = false;
        SubtractNewPlatformVelocity();

        SendMessage("OnLand", SendMessageOptions.DontRequireReceiver);
    }
}

```

Specifically if we look at the line "if (grounded && !IsGroundedTest()) {" is where I can capture the bounce as it happens. When putting in break points my first debug message fires "Before Bounce" just before launch. On landing we get the Debug message "3. found my grounding".

Unfortunately I'm not experienced enough with character movement to determine exactly why it's launching the player up, any advice on debugging and tracking the issue more closely is appreciated

**EDIT** Most recent debug results:

* Before the bounce test (5655.7, 65.1, 6032.1)
* IsGroundedTestResults: False
* Before bounce?
* 1. Lost grounding, maybe bounced?
* (56.557, 65.1, 6032.1) \[NOTE this is the first Debug.Log(tr.position)\]
* (56.557, 65.1, 6032.1) \[NOTE this is the second Debug.Log(tr.position)\]

Then we are back to normal

# Answer
> 1 votes
The computer is not aware of what type of object is moving around, whether it is a character walking/running (which you don't want to launch when it hits a ramp) or a car driving (which you would want to launch). Since you said that your character is moving at high velocity, that would explain why it is launching.

It is best to think of your character as a vehicle with wheels on the feet to help understand why the physics engine is launching your character when moving at high speed.

I haven't done it in Unity but I think the fix would be to **restrict `velocity.y` to only move in the downward direction if the player is not grounded *and* not jumping**. This should allow your player to fall off cliffs or walk downhill with normal gravity but would prevent it from launching into the air when it hits some type of ramp. As long as the player is grounded, running uphill shouldn't be affected.

If the player is explicitly jumping, then don't restrict `velocity.y`.

If you want to allow for a little bit of bounce, you might try scaling down `velocity.y`, rather than limiting it to downward motion or some small positive value. Otherwise if you just limit it, your character will look like it's hitting a ceiling when it launches too fast.

---
Tags: movement, scripting, unityscript
---


# Question
Title: Aligning pathfinding to the center of tiles?
I'm looking to achieve tile by tile movement in a project I'm working on. I employed the use of the asset Simply A\* Path-finding to allow a unit to navigate the terrain.

Since the tiles are simply made out of 32x32 sprites, I set the tilesize of the pathfinder to 0.32 to produce the above grid.

However when tested out with a unit, the unit often does not align itself to the center of the sprite as shown in the image below.

I am pretty new to unity and would appreciate if someone could input on how I can fix this or advise on an alternate method to allow this "tile to tile" path finding to work.

# Answer
> 0 votes
http://www.arongranberg.com/astar/docs/modifiers.php#simplesmooth

If you're using Aron Granberg's pathfinder, then are you perhaps using one of the smoothing modifiers? This would result in the unit trying to optimize the path which would probably prevent the unit from hitting each node as it steps through the path.

Or is the problem that you have a consistent offset when the unit paths from node to node?

# Answer
> 0 votes
You could check to which tile the player is closer to and then just set the position of the player to the centre of the tile.

---
Tags: unity, path-finding, grid
---


# Question
Title: Do professional 3D modelers use human bases?
I tried to find an answer on google and didn't get much. I wanna know, do professional 3D modelers (Specifically in the video game industry) work off generic base human models to make their own? Or do they make their entire body and face models from scratch?

Bases like these for example:

# Answer
They do whatever it takes to get the job done in the time allotted to the project. If that means working off of reference art or using existing assets that they have the legal right to use (licensing, etc.) then that's what they do.

The kinds of schedules we pulled in game development pretty much required everyone to cut whatever corners necessary to meet deadline.
> 2 votes

---
Tags: 3d
---


title: Location of project.json in Cocos2d-JS

text:
# Question
Title: Location of project.json in Cocos2d-JS
I am learning Cocos2d-JS to develop web-based games with Javascript. In Cocos2d-JS there is `project.json` file which defines game configuration.

Is it possible to place this file in another location than the directory containing `index.html` or `main.js` and if so, where and how should I define the new path?

# Answer
As I found out, the requirement of `project.json` is hardcoded into Cocos2d-JS internals and it should be located at the same directory (path) as the HTML document. There are no configuration settings allowing to overwrite it.

However, it is possible to change the reference to `project.json` in the `cc.game._initConfig` method, as the source of Cocos2d-JS is open.
> 1 votes

---
Tags: cocos2d-x-js
---


# Question
Title: Using Similar Mechanic Names For Attributes
I am working on a pen and paper game and I am wanting to use three core attributes that everything else is based off of. These three attributes being Physique, Skill and Will. However, if you're familiar with Fable, you will know that these were used in the game series.

My question is, could I use these same three core attributes in my games system without legal ramifications later down the road?

I would like to think not because one is from a video game and my project is pen and paper, not to mention that the terms Physique, Skill and Will are highly unlikely be to copyrighted.

And I also know that I shouldn't expect 100% accurate legal advice on this site but if anyone has any legal experience in these sorts of areas, it would at least give me a basis to go off of.

I'll continue doing research and hopefully between all of us, the question can be answered soon.

Thanks in advance.

# Answer
> 1 votes
Yes, you can.

Physique, Skill and Will are just English words. They cannot be copyrighted. Game mechanics in general cannot be copyrighted, which is why you can find umpteen bazillion games that rip off D&D terms; not just generic words like Strength and Constitution but even very D&D-specific terms like THAC0 (and the entire original D&D armor and to-hit system that goes with it).

There can be a *trademark* in play, but those three words alone wouldn't be eligible. If you really ape a lot of Fable, though, you may well run into trouble.

In general, I just recommend that designers like yourself bookmark thesaurus.com. Being original ain't hard.

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


# Question
Title: How do I manually draw a part of a sprite sheet?
I'm working in Unity, and I'm finding that the animator isn't working for what I'm trying to do, in my 2D game. I want to build a specific animation, using sprite sheets, and be able to reuse the same animation with other sprites that are the same size and dimensions by cells. After some research, I find that it is impossible.

Instead, I'm trying to create my own animation script, but I don't understand how to tell Unity to draw only a section of the sprite. Something like in XNA, where you could render only a specific rectangle of a sprite using start and end coordinates.

How do I manually draw a part of a sprite sheet?

# Answer
I think there can be a simpler approach in which you can do this , and still use Unity Mecanim for the animation.

Steps:-

1) You can programatically assign texture 2D sprites from the image, and as it is a grid it wont be much difficult to do so. In the following answer the user has created his own sprite slicer and saved into the directory (optional else just save it in a variable). You don't need the whole code,just check the GetSprites() function and you will get the idea :)

http://answers.unity3d.com/questions/576799/coding-my-own-auto-slicer-getting-islands-of-pixel.html

2) Once you are able to do that, then maintain an Array of sprites, which you got from step 1.

3) Now you need to create an anim file of these sprites which can be plugged into mecanim. For this you need Unity's Set Curve function(check the link provided below). Once you have the clip its upto you whether to save it for future use or just have it in a variable for the current game instance only.

http://docs.unity3d.com/ScriptReference/AnimationClip.SetCurve.html

Hope this resolves your doubt :)
> 1 votes

---
Tags: unity, sprites, rendering
---


title: Generate static 2D Tilemap from array

text:
# Question
Title: Generate static 2D Tilemap from array
How do I generate a 2D tile map from an array like in this tutorial for XNA ? I basicly want to generate a static map based on my tile prefabs.

# Answer
> 1 votes
Its actually very similar to the way it is done in XNA , only a few changes in the syntax and loading approach.

Here is the most basic way in which it can be done. You can build on top of it as per your needs.

Before we start, we need to make some tile prefabs and store it inside the resources folder.

Lets define some variables, and initialise them some default values.

```
    //Your Tile Map
    public int[,] tileMap = new int[,]
    {
     {0,1,2},
     {1,1,0},
     {2,2,2}
    };

    public float TileSize;
    public Vector2 StartPoint;//top left corner of the map

    // Use this for initialization
    void Start ()
    {
        TileSize = 1;
        StartPoint = new Vector2 (1, 1);
        PopulateTileMap ();
    }

```

The StartPoint is the top left corner of the map. So you can define from where it should start populating on the screen.

Now lets look at the core logic behind populating the tiles , as per our tilemap.

```
public void PopulateTileMap ()
{
    for(int i = 0 ; i < 3 ; i ++)
    {
        for(int j = 0 ; j < 3 ; j ++)
        {

            GameObject prefab = Resources.Load ("tile_"+tileMap[i,j].ToString()) as GameObject;
            GameObject tile = Instantiate(prefab, Vector3.zero, Quaternion.identity ) as GameObject;
            tile.transform.position = new Vector3(StartPoint.x + ( TileSize * i ) + ( TileSize/2) , StartPoint.y + (TileSize * j ) + ( TileSize/2), 0);

        }
    }
}

```

Here we instantiate the prefabs from our resources folder. The name is created as per the tile map we have defined earlier. For position, adding the tile size to the starting point will give the top left corner of the individual tile. But as our pivot is in centre we add an extra offset of (TileSize/2).

Hope this resolves your doubt :)

# Answer
> 0 votes
I think you will have a very similar stuff, compared to this tutorial. You will instantiate prefabs in each tile position. I would create prefabs of tiles based on functionality: Ground Tile Prefab, WaterTile Prefab, etc. Each one with options to activate/deactivate game Objects, to change the looking, for example. You rather use something with a little bit more information than a simple array of ids. I would recommend you to check it out: http://www.mapeditor.org/

There is some Unity projects on github integrating with the mapeditor, and you can use it as examples.

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


# Question
Title: Löve2D: Making a random map/city generator
So I'm making a game using love2d where the player will find himself in an zombie infested city but I don't want the city/map to be just the same all the time, so I want to create a random map/city generator, but I don't know where to start, I maybe can make my own but the result would probably be not what I wanted, as I don't want tiles getting placed all over the place messily(it won't look like a city then), I want random set of tiles getting placed in the world/map like buildings get placed randomly throughout the world/map, I hope someone can help me with this as this is really hard for me...

# Answer
> 2 votes
Like stated by Shiro in a comment , it's difficult to give a precise answer. I can suggest a possible starting point.

Use random voronoi generation where , given a set of random points P , each point in space is weighted relative to the distance from the nearest p in P.

Now , instead of considering euclidean distance use Manhattan distance and you get something like this :

then adjoust the gradient to obtain this

# Answer
> 2 votes
There are simple ways to generate cities, depending on your needs.

Some time ago, I wanted to generate cities for a fantasy setting, so I started playing with a generator. Like I said in another SE post: "rough on the edges" is an understatement. But it suits my needs (it may meet your needs too).

**This is what it looks like:**

Some terms I use internally:

* A tile is the smallest unit I handle; on the image one of the small houses fills almost a full tile.
* A block is a group of NxM tiles.

**And this is how I generate it:**

First I generate a central feature, such as the block with the "fountain" (let's call this block a town square). I decide its width and height and place it near the center.

Then I try generating "blocks" for as long as I can:

1. Generate a block size (somewhere between 2x2 and 5x5).
2. Iterate through the image and decide where to place it. For this a weight is assigned depending on adjacency to other blocks (similar to what I explained on this post).
3. Place the block if a suitable location is found. When no suitable location is found, go on to the next step.

Once all blocks have been placed, I can add houses and buildings for each block. I took care of leaving a gap between blocks and another between houses. Some buildings use four tiles (2x2).

Finally, I do the actual drawing in an image.

# Answer
> 1 votes
You should do some research about l-systems, they allow you to specify some basic rules and then procedurally generate the map.

You could for example specify that every building must be surrounded by roads, and every road must continue in a straight line or eventually end, and every road is surrounded by buildings or empty space. Then, the algorithm will start "substituting" a building with a building surrounded by roads, a road piece with a full road... until you have a complete city.

Read the answer to this question for a more detailed explanation: Using L-Systems to procedurally generate cities

---
Tags: tilemap, procedural-generation, maps, random, love2d
---


# Question
Title: How to get a Vector2 location of an object? (Unity2D javascript)
I need to make an "AI" that makes a ball try to touch the player. But `Vector2.MoveTowards()`needs a Vector2 variable but how do i get the location of an object?

# Answer
As Vector2 is a type composed by two numbers which are x and y, then you should be able to get the position by asking both numbers:

```
 Vector2 YourVar;
 YourVar.x;
 YourVar.y;

```

So you should use something like:

```
 SetPositionToMove(YourVar.x,YourVar.y); //if the functions expect x and y or:
 SetPositionToMove(Point2(YourVar.x,YourVar.y)); //if it expects a Point2 for example

```
> 1 votes

---
Tags: unity, 2d, javascript, ai, unityscript
---


# Question
Title: How to use rigitbody2d.AddTorque() in JavaScript? (unity2D)
I just want to know how to use rigitbody2d.AddTorque() and an example script would be great :D. I am trying to rotate a cube forever using it as a test.

# Answer
Make sure that "Is Kinematic" option for rigidbody in the inspector is off.

Here is a very basic example for adding torque.

```
var torque: float;
var rigidBody: Rigidbody2D;

function Start() {
    torque = 20;
    rigidBody = GetComponent.<Rigidbody2D>();
}

function FixedUpdate()
{
    rigidBody.AddTorque(Time.deltaTime*torque);
}

```

Time.delta time is just to make it device independent.

Hope this resolves your doubts :)
> 1 votes

---
Tags: unity, 2d, javascript, rotation, rigidbody
---


title: LWJGL not streching texture to quad

text:
# Question
Title: LWJGL not streching texture to quad
I'm having problems with texturing in LWJGL. The texture is not being stretched to a quad. As you can see, the texture is not being sized to the quad, marked with pink border. The problem doesn't exist when using square quad and square texture. Scaling the texture to 960x320 px doesn't help The texture size is 96px width and 32px height.(1 tile is 32x32, this object is 3 by 1)

The code:

```
//rendering the textured quad. This method also renders everything else
public static void renderTile(Texture tex, int x, int y, int sizex, int sizey) {
    tex.bind();

    glBegin(GL_QUADS);
    glColor4f(1, 1, 1, 1);
    glTexCoord2f(0, 0);
    glVertex2f(x, y);

    glTexCoord2f(1, 0);
    glVertex2f(x + sizex, y);

    glTexCoord2f(1, 1);
    glVertex2f(x + sizex, y + sizey);

    glTexCoord2f(0, 1);
    glVertex2f(x, y + sizey);
    glEnd();
}

//opengl initialization code, called before any rendering
public static void initOGL(){
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    glOrtho(0, 800, 600, 0 , 1, -1);
    Log.info("Display W=" + Display.getWidth() + " H=" + Display.getHeight());
    glMatrixMode(GL_MODELVIEW);
    glEnable(GL_TEXTURE_2D);
    glEnable (GL_BLEND);
    glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
}

```

# Answer
Yes!

I have figured it out. LWJGL texture files must have dimensions equal to powers of 2 (2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048 etc). Otherwise OpenGL will clamp them to nearest power.
> 1 votes

---
Tags: java, textures, lwjgl
---


# Question
Title: Making DirectInput and XInput work together
I have working wrappers for Xinput and DirectInput in my game, but I had problems with xbox controllers, because they are also recognized as generic controllers by directinput.

I have found out that Microsoft recommends to solve this problem like described on this MSDN page (See the IsXInputDevice function in the code sample).

I implemented the suggested function, but sadly it is very slow and I found out that the following call takes about half a minute to finish on my computer:

```
pIWbemServices->CreateInstanceEnum(bstrClassName, 0, NULL, &pEnumDevices);

```

Could anyone solve this problem and if yes, how? I imagine many games use this method to select the correct input method for gamepads, but the problem is not common at all.

For the time being, I began writing a wrapper for raw input but I'd be happy if this also got solved.

# Answer
There's an alternative, but it is in C#:

http://www.gamedev.net/blog/161/entry-1868663-controller-input-updates-to-cogwheel/

```
using System.Globalization;
using System.Management;
using System.Text.RegularExpressions;

namespace CogwheelSlimDX.JoystickInput {
    public class Joystick {

    public ushort VendorId { get; private set; }

    public ushort ProductId { get; private set; }

    public bool IsXInputDevice {
        get {
            var ParseIds = new Regex(@"([VP])ID_([\da-fA-F]{4})"); // Used to grab the VID/PID components from the device ID string.

            // Iterate over all PNP devices.
            using (var QueryPnp = new ManagementObjectSearcher(@"\\.\root\cimv2", string.Format("Select * FROM Win32_PNPEntity"), new EnumerationOptions() { BlockSize = 20 })) {
                foreach (var PnpDevice in QueryPnp.Get()) {

                    // Check if the DeviceId contains the tell-tale "IG_".
                    var DeviceId = (string)PnpDevice.Properties["DeviceID"].Value;
                    if (DeviceId.Contains("IG_")) {

                        // Check the VID/PID components against the joystick's.
                        var Ids = ParseIds.Matches(DeviceId);
                        if (Ids.Count == 2) {
                            ushort? VId = null, PId = null;
                            foreach (Match M in Ids) {
                                ushort Value = ushort.Parse(M.Groups[2].Value, NumberStyles.HexNumber);
                                switch (M.Groups[1].Value) {
                                    case "V": VId = Value; break;
                                    case "P": PId = Value; break;
                                }
                            }
                            if (VId.HasValue && this.VendorId == VId && PId.HasValue && this.ProductId == PId) return true;
                        }
                    }
                }
            }
            return false;
        }
    }
  }
}

```
> 1 votes

---
Tags: directinput
---


title: What causes aliasing?

text:
# Question
Title: What causes aliasing?
I always hear about aliasing and anti-aliasing and I know what it looks like but what I don't understand is what causes it. Is it a physical phenomenon? Or a numerical one?

If it helps to explain, I have some programming knowledge, but not in video games or graphics.

# Answer
> 59 votes
> Is it a physical phenomena ? or numerical ?

This question sorta implies to me that you don't actually know what aliasing/anti-aliasing means. I mean, you say you "know what it looks like" but if you actually knew what the terms mean, you'd probably realize your question is nonsensical. Aliasing is a side-effect of how computer graphics are rendered, and computer graphics are pretty much *by definition* not physical phenomena.

"Aliasing" just refers to the stair-step look on angled lines because computer graphics are actually comprised of lots of tiny squares in a grid. Here's an image to illustrate what I'm talking about:

This is an issue whenever you render the pixels in an image, whether you're drawing freehand or are writing an algorithm to calculate the pixels for a 3D polygon. It's just a side-effect of the fact that the image is a square grid of pixels. "Anti-aliasing" is when you disguise the stair-step look by blending the colors together along the edge pixels.

# Answer
> 124 votes
The accepted answer is not strictly correct, although it addresses the most common usage in computer graphics. Aliasing is a fundamental concept in signal processing and the mathematical theory of it predates computer displays. It is also not really true that "it is a side effect of the fact that pixels are square". Aliasing exists any time you discretely sample a signal at a rate below the Nyquist rate for that signal and affects digital audio as well as images and many other types of discretely sampled signals. Aliasing in computer graphics is a side effect of discrete sampling, not of the shape of the pixels.

Anti-aliasing in computer graphics is a deep and complex topic and there's a lot more to it than just edge anti-aliasing. Again, there's a lot of underlying theory from signal processing and it's an active area of research in computer graphics how to anti-alias effectively, not just for edges but also for temporal aliasing, for aliasing when reconstructing a BRDF in pixel shaders, for shadow edges and in many other areas. Mip-mapping of textures in 3D graphics is a well established anti-aliasing technique that is addressing an important problem other than edge anti-aliasing for example.

It's really a mathematical phenomenon more than a physical one but it shows up in engineering in many areas other than computer graphics. I wouldn't really describe it as a numerical phenomenon either - it's a result of discrete sampling, not of the discrete representation of numerical values on a computer, although that can cause aliasing effects too. Understanding the fundamentals of signal processing is a good foundation for understanding how aliasing manifests in computer graphics and for understanding how to go about reducing it.

# Answer
> 68 votes
Adding to the other two answers, here is a more intuitive explanation of what happens.

The grid squares represent pixels. The red polygon on the left is the shape being drawn, represented internally as a sequence of points. When it is rendered, it is converted from a list of points to a buffer of pixel colors. The discrete sampling determines which pixels are dark and which pixels are light, based on how much of the polygon covers each pixel.

To answer your question, this is a numerical/mathematical phenomenon because information about the original shape is lost due to approximation.

Anti-aliasing is when the rendering attempts to correct for aliasing by making partially-covered pixels less intense.

# Answer
> 3 votes
In signal processing field, aliasing refer to the misidentification of signal frequency. For example, due to the lack of the adequate consideration in under-sampling step it may lead to the generating errors and distortion. It can be generalized to the 2D discrete signal such as an image.

---
Tags: rendering, antialiasing
---


# Question
Title: Unity - Vector3.Reflect not reflecting correctly
I resolved the question on how to draw a line, so here is the result:

https://www.dropbox.com/s/hvc9yr3jjbqdv7r/dc.jpg?dl=0

So, now I want to create a line that shows the possible bounce off the wall (and the other ball).

Some suggested I use the Reflect method but it did not work, here is how I implemented it, script is attached to the white que ball:

```
//
        Ray ray2 = Camera.main.ScreenPointToRay(Input.mousePosition);
        RaycastHit hit2;

        //
        if (Physics.Raycast(ray2, out hit2, 100.0f)){

            //position of white wall
            Vector3 startPos = transform.position;
            //cliked position, translated to the table plane
            Vector3 clickPos2 = new Vector3(hit2.point.x, hit2.point.y, transform.position.z);
             //get direction from ball to clicked position
            Vector3 direction = Direction (clickPos2 - startPos);

              //so I simply should do I reflect, it gives me a bit odd results
            Vector3 reflectDir = Vector3.Reflect(direction, hit2.normal);

            //finally im drawing the line
            lineRenderer.SetPosition(0, startPos);

            Vector3 forward = transform.TransformDirection(direction) * 100;
            lineRenderer.SetPosition(1, forward);

              //reflection?
            lineRenderer.SetPosition(2, hit2.point);

            lineRenderer.SetPosition(3, reflectDir);

```

Here is what this code gives me:

https://www.dropbox.com/s/9dfb3vyqmbknzes/gb.jpg?dl=0

Any ideas on how to make it work?

Mirza

# Answer
Im not 100% sure, because your Dropbox link is dead, but I think your error is in the last line of your code. The lineRenderer connect Points in space and you need to convert your direction to a point.By adding a starting vector to your direction.

```
lineRenderer.SetPosition(3, reflectDir+hit2.point);

```
> 1 votes

---
Tags: unity, game-design
---


# Question
Title: On key press, spawn a collider where my player is facing?
I'm trying to create an attack mechanic to my player hero in my 2D Tower Defense game. When I press the Q button I want my hero to do an animation and spawn a temporary collider shaped as a cone at where the hero is looking at. If this collider collides with a GameObject called "Stone" it will decrease its hpValue with a script I made. If there is multiple Stones in the cone I want it to only effect one Stone, chosen either by random or/and closest to the hero.

How would I go about doing this and how can I detect the direction of where my hero is facing? This is my movement script:

```
public float speed;   //Movementspeed

Rigidbody2D rbody;

void Start () {

    rbody = GetComponentInChildren<Rigidbody2D> ();
    rbody.freezeRotation = true;
}

void FixedUpdate () {

    Vector2 movement_vector = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"));

    rbody.MovePosition (rbody.position + movement_vector * speed * Time.deltaTime);

}

```

A picture visualising what I mean:

# Answer
> 1 votes
To determine the cone you should create some variables like AttackLength, FieldOfViewAngke and get enemy component to determine enemy position

```
lookDirection = enemyPosition - player.transform.position;
lookDirection.y = 0;
attackDirection = Vector3.zero;
float angle = Vector3.Angle(lookDirection, transform.forward);

if (Physics.Raycast(enemyPosition, lookDirection, out hitInfo, AttackLength, layerMask))
{
    if (angle <= FieldOFViewAngle * 0.5f)
    {
     //action
    }
}

```

And instead of spawning collider you can go other way by tagging enemy or stone or whatever like "enemy" and add the check to second if-statement like

```
&&hitInfo.collider.gameObject.tag == "enemy"

```

To clarify:  Green is player, red-enemy. lookDirection Vector is black, gotten from subtraction of playerPos from enemyPos; Yellow is your filed of view, e.g. 170 degrees; Blue is transform.forward Vector from the player; float angle = angle between Blue and Yellow; to check if the enemy is in the FOV, you check if this angle is less then the half of the FOV

# Answer
> 0 votes
To detect the direction that your player is facing you can use `transform.forward` as a vector3 value .

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


# Question
Title: Unity: "Find" can only be called from the main thread, but moving variables to the Start() function causes other errors
```
    #pragma strict

 var collided = false;
 var thrust: float;
 var pizza = GameObject.Find("pizza-small").GetComponent.<Rigidbody2D>();

     function Start() {

     }

     //hand + pizza collision detection
     function OnCollisionStay2D(coll: Collision2D) {
         if (coll.gameObject.tag == "Pizza") {
             collided = true;
             Debug.Log("Hand+Pizza");
         }
     }

     function Update() {

     //Input
     if (Input.GetKey(KeyCode.W)) {
         Debug.Log("Up");
         transform.position.y+= 0.2;

         if (collided === true) {
         //Adding force to the pizza
         pizza.velocity = Vector3(0,15,0);
         }
     }
     else if (Input.GetKey(KeyCode.A) || Input.GetKey("left")) {
         Debug.Log("Left");
         transform.position.x-= 0.1;
     }
     else if (Input.GetKey(KeyCode.D) || Input.GetKey("right")) {
         Debug.Log("Right");
         transform.position.x+= 0.1;
     }
     else if (Input.GetKey(KeyCode.S) || Input.GetKey("down")) {
         Debug.Log("Down");
         transform.position.y-= 0.1;
     }
     else if (transform.position.y > -3.5) {
         transform.position.y-= 0.25;
     }
     else {
         collided = false;
     }

 }

```

Moving the 3 initial variable declarations into Start() removes the "Find can only be called from the main thread" error, but then they cannot be used in the Update() function due to variable scope.

If I declare them initially and then set their values inside of the start function, new errors arise.

```
 var pizza;

 function Start() {

 pizza = GameObject.Find("pizza-small").GetComponent.<Rigidbody2D>();

 }

```

If I do that, then when I use:

```
pizza.velocity = Vector3(0,15,0);

```

It states that velocity is not a member of "object".

I have no idea how to fix this, as the program works with no changes to my initial code, but does still give the error. This could be causing problems, as the rigidbody2D of the "pizza-small" is pulled toward any non-preexisting colliders that I add.

# Answer
> -1 votes
Never mind, I fixed it -

```
 var pizza : Rigidbody2D;

  function Start() {
  pizza = GameObject.Find("pizza-small").GetComponent.<Rigidbody2D>();
  }

```

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


# Question
Title: How to revert to MonoDevelop's old "ctrl-tab" behavior?
I believe MonoDevelop (bundled with Unity3D) has changed its `ctrl-tab` and `ctrl-shift-tab` behavior and I would like to get back to the old behavior, as the new way frustrates my workflow.

`Ctrl-tab` (and `ctrl-shift-tab`) previously (and ought to) go to the "last viewed tab", in a similar way to how `alt-tab` works on Windows. Unfortunately there seems to have been a change and now it goes to the "tab on the left of the current one".

An example of why this is frustrating: quickly looking at a class definition, you hit `F12` to load the definition (perhaps in a new tab), and then you want to go back to the code you were working on. Previously you could hit `ctrl-tab` and you'd be back there. Now you can't do that and you have to actually remember what you were doing, which isn't good for my workflow (read: ailing memory).

I'm not sure when the change happened, or if it's a setting somewhere (I can't find it). I'm running Unity 5.1.2p2 and its bundled MonoDev 4.0.1. Noticed it after a clean install of Windows 10.

How can I fix this to revert to the old behaviour, or is there some other method to jump back to the last viewed tab?

It seems pedantic but it has a major impact on my productivity.

# Answer
http://answers.unity3d.com/questions/613355/document-switcher-is-gone-monodevelop.html

Edit C:\Users\ **USERNAME** \AppData\Roaming\MonoDevelop-Unity-4.0\Config\MonoDevelopProperties.xml

Set the `MonoDevelop.Core.Gui.EnableDocumentSwitchDialog` property to `True`
> 1 votes

---
Tags: unity, productivity, monodevelop
---


title: LibGDX, Box2D , Destroy body into parts

text:
# Question
Title: LibGDX, Box2D , Destroy body into parts
I am developing a game using libGDX game engine and box2d physics engine. There are asteroids in my game, I want to destroy their bodies randomly and fill with texture. How can I do it?

# Answer
> 2 votes
Emanuele Feronato did a tutorial on this some time ago, you can use it as a base: http://www.emanueleferonato.com/2012/03/05/breaking-objects-with-box2d-the-realistic-way/

To sum it up:

* Listen to collisions between your breakable body and the bodies that can break it;
* When collision happens, get the velocity of the body that can break the other and raycast it further;
* Use that raycast to cut the polygon of the breakable body in two;

---
Tags: libgdx, box2d
---


title: Pathing for 2D, sprite-based game

text:
# Question
Title: Pathing for 2D, sprite-based game
I'm making a 2D, oblique-styled sprite based RPG. My game does not live in a 2D matrix (like Tetris), rather it's sprites animating over a tilemap. I am trying to set pathing rules for NPCs. I've considered a few methods to do this but am not sure on the path I should take (no pun intended).

The NPC's trajectory is set by calculating the angle between origin coordinates and next coordinates and moves at that angle. I'm sure this will lead to blocky movements as they move along an array of coordinates along their path.

So, to set pathing rules, I was considering the following approaches and would like some direction given my style of game:

* **Manually define coordinates:** For each NPC, define a set of coordinates for a given destination (a destination location set in my game). This issue with this is it will get tedious to set all the coordinates along the path.
* **Pathing algorithm:** I'd rather simply set the destination coordinates once, and perhaps use a pathing algorithm, such as Dijkstra's Algorithm, that the NPC can use to navigate the map. I am not sure if this will have any ability/effect on smoothing out the movement.

It was also suggested using the Rapidly Exploring Random Tree algorithm, but again... not sure if this is overkill for my game... and what the performance hit would be.

Here is a snapshot of my map. The red arrow is a sample path. The blue lines are collision rules defined around map objects.

I would love some guidance on this. I am not sure if something like a pathing algorithm is a) overkill my game, b) doesn't fit with my game style

# Answer
I'm not sure I completely understand what you are asking, as it's hard to tell what you mean by your "game style", but I will say that a path-finding algorithm is not necessarily overkill, especially if you would like your NPC's to find specific routes around obstacles.

From my own experience with AI navigation, there are a couple of very popular types of pathfinding that are used, some of which use a pathfinding algorithm such as A\* (a very good explanation here: Link) or even just immediate obstacle avoidance (such as seen here), although that's more applicable when using a physics engine I think.

But from what I can tell you're really looking for a pathfinding algorithm, and it would probably be very useful for you. A\* is a fairly fast algorithm, and there are other similar algorithms and numerous variations that can give you great performance. If you only have a few of NPC's navigating at a time, pathfinding is almost certainly not a performance bottleneck for you.

Thinking back on it, if you mean that your game is 2D when talking about your "style of game", you can still think of your map as a sort of 2D matrix, because from what I can see of your screenshot it exists on an XY plane and therefore pathfinding seems to be a completely viable option for you.

As an extra note, since you seem to be using Tiled, this SO post about pathfinding may also be of use to you (even if you're not programming in Java).

I hope I was able to help, though I'm sure there are people here with way more experience on this topic than I have...
> 4 votes

---
Tags: 2d, algorithm, rpg, npc, path
---


# Question
Title: Proper way to handle Movement/Animation/AI functions of an AI character in Unity3D
My team is currently building a 2D game in Unity and we've run into some workflow/script organization blockades for many of our game's characters.

For example, we're not sure what the standard method of encapsulating/organizing a character's movement, animation, and more complex AI code is so that things don't become a behemoth mess.

Originally, we had all a character's code in one file -- movement, animation, and AI decision-making code. Needless to say, this became messy really quickly and horrendous to debug.

Then, we redesigned it so that there were three scripts on the character: a movementHandler, animationHandler, and AIHandler. These scripts would communicate to each other, but encapsulate their own functions. This worked better than before, but also grew to a point where it was a bit messy organizationally and debugging is becoming a nightmare again.

We're interested in knowing how people typically organize their scripts. Is there a way people know to organize these code sections so that they're more scalable and don't become headaches to manage once the project grows and grows?

# Answer
> 1 votes
In my opinion the best is start with a good AI layer that uses a state machine approach (here and here). Making it simple, the current state AI evaluate some inputs, make a decision and eventualy jumps to a new state. The movement and animation layer relay on actual AI state to do their stuff

# Answer
> 1 votes
I'm not experienced programmer, but as for me, I try to divide as much logical parts as I can into different scripts. For ex, for the character you can use something like MVC, model-view-controller pattern. The point is that one script processes user input and communicates with tho other parts which are responsible for animations and actual movement.

In Unity scripting most of the usual programming patterns are true, like using fabric to generate different kinds of creatures with similar logic, or singletons, etc.

Though there are some game-specific things which you can find on forums and in books like Robert Nystrom's 'Game programming patterns'

---
Tags: c#, 2d, unity, architecture
---


# Question
Title: Procedural Dungeon Generation: Is there a simple algorithm to make sure all of these rooms get connected using minimal corridors?
Is it possible to get a hive-like structure, connecting all the rooms without having too many corridors? *(Too many being 3-4+ corridors coming from a single room)*

Below is the output of how my rooms look, basically they randomly placed.

What I'm hoping to get corridor-wise.

# Answer
> 6 votes
Well, the simplest way I can think of starts with making sure all rooms are connected by at least 1 corridor:

1. Start with the last, or first, room.
2. Grab a random room within 1 distance, which is not already connected to some room (all rooms start disconnected, so you'll be keeping track of this as you go).
3. If there is no such room, go to distance +1. If it's ok to tunnel over/under another room this is easier, assuming you don't want connecting corridors.
4. Work your way through pseudo-randomly until all rooms are connected.

Now we know you can get to all rooms, but now if you want more than this strictly linear maze you can just step through your rooms and randomly make a new path to connect rooms, up to a limit per room of 2-3, or until a certain percentage of rooms hits the max connections - etc.

As a final step you can add rules that would alter your results to suite various situations. For instance, you might observe that any room with only 1 corridor is, by definition, a dead-end; You could make more dead ends, or you could eliminate them all by making sure everything has at least 2 connections. You could make dead-ends have a secret passage. You could make sure a boss-room is a dead-end. You can make sure your start room is a dead-end, but then make sure the second room has a minimum of X connections. *Ad infinitum.*

Each assumption and rule can radically shift how your levels look, but that's part of the fun! This should at least get you hive/cave-like rooms to start.

# Answer
> 3 votes
Just build your rooms already connected. Start with one room, then build 1-3 corridors to other rooms. Then recurse until you've added enough rooms.

# Answer
> 3 votes
Since these rooms are Graph vertices embedded in a 2d plain, this could in theory be done by solving the traveling salesman problem (which would be fine with only a few rooms). Obviously, a simple heuristic would be fine and allow reasonable scalability.

You compute the edges (corridor lengths) between all rooms. You sort them by length. You add the shortest corridor unless it creates a cycle or increases the degree of the vertex (room) above your desired max value (3-4) (Repeat). To check for cycles you could apply UnionFind or do a quick BFS on small data.

---
Tags: procedural-generation
---


# Question
Title: When is the right time to save game data in a standalone game?
For standalone game, what's the best time to save game data, such as player's coins, level, skill data and so on?

Should the data be saved before quitting? Or whenever it changes? Or something else?

# Answer
> 5 votes
## Gameplay Design

Technically, it depends on the style of gameplay you are designing. In some game genres, it is almost explicitly expected to have certain "save types".

For instance, in online casual flash adventure/RPG games, you will often save every tiny change into a cookie so if the player accidentally (or intentionally) closes the browser, the game state persists. Another common alternative is frequent auto-saves that will be triggered by certain events such as you win/lose a battle or when the player returns to town.

In MMORPG (not what you're doing specifically), it is expected that all the characters' data is saved immediately with every change.

In casual platformers and shooters, you don't particularly need to save but it's expected that you let the player "unlock" content such as stages / worlds and achievements.

In some oldskul games, you'd let the player save when they want to. This is a feature that lends itself well to long "serious" games that require a substantial time investment like more classical RPG, Adventure, FPS and RTS games. Adding a quick save & quick load option too and possibly an auto-save in addition to that.

In roguelikes, you are expected to save *at least* when the player quits the game if not *all the time* but in this case, saving all the time is not a gameplay feature as much as it's a UX one in case of crashing. The gameplay feature is surprisingly the *lack of* a load button which boosts adrenalin in close call situations. This is a good example since having only one chance to do something can be considered a gameplay feature or a great annoyance depending on the person you ask and the gameplay context like a challenging rare boss fight or a bonus stage (where you can't save or load the game).

If your game is casual, as in you're not going to limit saves / lives for the sake of additional difficulty or to intensify suspense, then saving all the time is a virtue; that is assuming it doesn't hurt performance.

## Performance

You don't have to heavily compensate on performance if you save data asynchronously. You request the disk (or http server) to write some data while you continue running the game. If the game has some kind of "game world" structure like cities -\> stores, mazes -\> levels -\> rooms then you can get away with saving whenever the player enters or leaves a zone. Just remember that when you save asynchronously you still want to make sure the save went through, especially if the play decided to save the game. ;) If for some reason (disk space | online connection issue), you are unable to save, you may wanna notify the player the connection was lost or whatever is relevant in that case.

Also it is important to note you don't *have to* store everything in one file or one DB record. You can save information about the character incrementally. For example, if the character travels across your game worlds and visits many zones, you may want to keep track of visited zones. You don't have to store all that in one file. You can "touch" (create a tiny possibly empty file) inside a designated directory or add a row in a database. You don't have to write all the progress related data at once. The same thing with items, you can add or modify it on the fly with a local sqlite DB, or a designated file folder with one file for equipment, armor, weapons, etc or even one tiny file per item. Obviously, the more complicated it is, the harder it is to maintain so keep it simple.

# Answer
> 0 votes
If your game is addictive as I hope, and after 1 hour plaing, a black-out or a pc crash , make me loose all progress.. i regret you do not added an in game autosave. Basicaly you missed option 1.5 save sometime (time related, level changing)

# Answer
> 0 votes
I'd say the best thing to do would be to save game data when somethings changed as sometimes the game may end up force closing which would result in losing all your data

---
Tags: savegame
---


# Question
Title: Restricting body movement withing a specific length while dragging a gameobject in unity
```
private void OnMouseDrag()
{
    Vector3 screen_sp=new Vector3(Input.mousePosition.x,Input.mousePosition.y,screen_space.z);
    Vector3 cur_pos=Camera.main.ScreenToWorldPoint(screen_sp)+offset;
        if(pendulum_object.gameObject != null && pendulum_object.gameObject.rigidbody!=null)
        {
                transform.position=cur_pos;
                    Debug.Log ("Pendulum is being dragged left"+transform.position);
                    Debug.Log("Mouse position is:"+Input.mousePosition);
                    Debug.Log("Current position is:"+cur_pos);
        }
}

```

**The problem is:The dragging of game object must be restricted to the length of string.** The pendulum is joint using hinge joint to the world.

# Answer
> 1 votes
You should proceed in the following way

1) Get the input mouse position convert it to world co-ordinates

```
Vector3 direction = Camera.main.ScreenToWorldPoint (Input.mousePosition);

```

2) Now calculate the directional Vector3 form anchor of the hinge joint to the input mouse position.

```
Vector3 diff = direction - Anchor.transform.position;

```

3) The last step will be to restrict the Position of the pendulum along this directional vector as per the string length (float) . By normalising we get the direction , then we clamp the magnitude to max String Length.

```
pendulum_object.transform.position = diff.normalized * Mathf.Clamp (diff.magnitude, 0, StringLength);

```

Note: If the pendulum is a child of a game object and if the scale and position differs. Then you need to use pendulum\_object.transform.localPosition and also take care of the scaling factor.

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


# Question
Title: Paper-based prototyping: simulating real time
I was messing around with this game idea where players race along a dangerous road in trucks to deliver their cargo. As they travel along the road (especially if they decide to go at speed) they will run into dangers: landslides where they must dodge/clear terrain, fog so they can't see the cliff sides etc.

I'd love to try this out 'on paper' first with some friends. However I'm not sure how to simulate a real time experience of driving the trucks at various speeds. The most simple solution I have come up with is rolling dice to move however many grid squares; wherever you land you roll again to see if a randomised disaster occurs. To measure speed I could add a modifier, such as if they're going an 'above average speed' they get a +1 to the amount of grid squares they cover but also a +1 to the chance of a disaster happening.

However, in a video game I'd be simulating acceleration (by holding down a key for example) and changing gear for speed. It also would not be turn based and they would have free control of the truck's movement and could accidentally plummet off the edge.

I guess the game can track when a player leaves and enter a new square in the grid and, after so many, roll to see if a disaster occurs. However, I don't think my current idea would really reflect the real time game experience/dynamics I'm trying to create in the video game. Am I looking at this the wrong way?

Many thanks

# Answer
> 0 votes
It's a bit hard to imagine how a pen-and-paper-and-dice version of a game should actually convey the impression of real time *at all*. And admittedly, I doubt that this paper version will provide valuable feedback in regard to the implementation of a real-time game. However, if you think that it may be helpful (maybe just to get a rough idea about the events and variables that are involved, and their effects on e.g. the likelyhood on accidents), there may be some options.

The first one that came to my mind was: Derivation. As you probably know (or as you *should* know when you want to implement such a game)

* Velocity is the first derivative of position
* Acceleration is the first derivative of velocity (and the second of position)
* Force is acceleration times mass

So instead of allowing the player to control the *movement*, you could only allow them to control the *velocity* (or maybe only the *acceleration*, or maybe even only the *force*)

Note that this is actually pretty close to what you would implement in the real game: The player can not directly *move* his truck, say, 10 meters forward. He can only press a key to indicate that he wants to accelerate, and release the key (and press another one) to indicate that he wants to decelerate (or brake). In reality, one actually contains further derivatives. Namely, the *force* via the gas pedal (and even further: How fast one is pressing down the gas pedal etc.)

This could be modeled in a pen-and-paper game as well: You would keep track of (at least) the *position* and *velocity*. The player can change the *velocity* (and maybe the direction, by steering), and the new *positions* are computed from the *velocity* in each turn.

I hope that some ASCII-art will be enough to make the idea clear: Imagine the track to be modeled as a sequence of fields. The player starts, with a velocity of 0, facing right:

```
 __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __
|0>|  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |
|__|__|__|__|__|__|__|__|__|__|__|__|__|__|__|__|__|__|__|__|
                              |  |  |  |                 |  |
                              |__|__|__|                 |__|
                                                         |  |
                                                         |__|
                                                         |  |
                                                         |__|

```

Then he can either actively decide to increase the velocity, or roll a dice to decide how much he wants to accelerate. Let the result be an increase of velocity of 6. This means that the next two rounds would be

```
 __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __
|6>|  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |
|__|__|__|__|__|__|__|__|__|__|__|__|__|__|__|__|__|__|__|__|
                              |  |  |  |                 |  |
                              |__|__|__|                 |__|
                                                         |  |
                                                         |__|
                                                         |  |
                                                         |__|

```

and

```
 __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __
|  |  |  |  |  |  |6>|  |  |  |  |  |  |  |  |  |  |  |  |  |
|__|__|__|__|__|__|__|__|__|__|__|__|__|__|__|__|__|__|__|__|
                              |  |  |  |                 |  |
                              |__|__|__|                 |__|
                                                         |  |
                                                         |__|
                                                         |  |
                                                         |__|

```

Now, he could decide to keep his current speed, or maybe brake or accelerate further. Let him keep the current speed, then the next step will be

```
 __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __
|  |  |  |  |  |  |  |  |  |  |  |  |6>|  |  |  |  |  |  |  |
|__|__|__|__|__|__|__|__|__|__|__|__|__|__|__|__|__|__|__|__|
                              |  |  |  |                 |  |
                              |__|__|__|                 |__|
                                                         |  |
                                                         |__|
                                                         |  |
                                                         |__|

```

Now, some predefined event could happen, which is always to happen at the third time step: A landslide `XX` fills one field!

```
 __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __
|  |  |  |  |  |  |  |  |  |  |  |XX|6>|  |  |  |  |  |  |  |
|__|__|__|__|__|__|__|__|__|__|__|__|__|__|__|__|__|__|__|__|
                              |  |  |  |                 |  |
                              |__|__|__|                 |__|
                                                         |  |
                                                         |__|
                                                         |  |
                                                         |__|

```

Fortunately, the player is already past this obstacle! A player that only had accelerated by 5 in each step would now encounter this situation:

```
 __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __
|  |  |  |  |  |  |  |  |  |  |5>|XX|  |  |  |  |  |  |  |  |
|__|__|__|__|__|__|__|__|__|__|__|__|__|__|__|__|__|__|__|__|
                              |  |  |  |                 |  |
                              |__|__|__|                 |__|
                                                         |  |
                                                         |__|
                                                         |  |
                                                         |__|

```

And he'll probably crash into the obstacle, because he can't brake and steer and take the detour to avoid it.

However, the fast player may now decide to decelerate, because he's heading for a corner. So he decelerates to 5

```
 __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __
|  |  |  |  |  |  |  |  |  |  |  |XX|5>|  |  |  |  |  |  |  |
|__|__|__|__|__|__|__|__|__|__|__|__|__|__|__|__|__|__|__|__|
                              |  |  |  |                 |  |
                              |__|__|__|                 |__|
                                                         |  |
                                                         |__|
                                                         |  |
                                                         |__|

```

giving

```
 __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __
|  |  |  |  |  |  |  |  |  |  |  |XX|  |  |  |  |  |5>|  |  |
|__|__|__|__|__|__|__|__|__|__|__|__|__|__|__|__|__|__|__|__|
                              |  |  |  |                 |  |
                              |__|__|__|                 |__|
                                                         |  |
                                                         |__|
                                                         |  |
                                                         |__|

```

then decelerates to 2, giving

```
 __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __
|  |  |  |  |  |  |  |  |  |  |  |XX|  |  |  |  |  |2>|  |  |
|__|__|__|__|__|__|__|__|__|__|__|__|__|__|__|__|__|__|__|__|
                              |  |  |  |                 |  |
                              |__|__|__|                 |__|
                                                         |  |
                                                         |__|
                                                         |  |
                                                         |__|

```

and

```
 __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __
|  |  |  |  |  |  |  |  |  |  |  |XX|  |  |  |  |  |  |  |2>|
|__|__|__|__|__|__|__|__|__|__|__|__|__|__|__|__|__|__|__|__|
                              |  |  |  |                 |  |
                              |__|__|__|                 |__|
                                                         |  |
                                                         |__|
                                                         |  |
                                                         |__|

```

Now turn the steering wheel, to avoid rushing out of the track, giving

```
 __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __
|  |  |  |  |  |  |  |  |  |  |  |XX|  |  |  |  |  |  |  |2 |
|__|__|__|__|__|__|__|__|__|__|__|__|__|__|__|__|__|__|__|v_|
                              |  |  |  |                 |  |
                              |__|__|__|                 |__|
                                                         |  |
                                                         |__|
                                                         |  |
                                                         |__|

```

and

```
 __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __
|  |  |  |  |  |  |  |  |  |  |  |XX|  |  |  |  |  |  |  |  |
|__|__|__|__|__|__|__|__|__|__|__|__|__|__|__|__|__|__|__|__|
                              |  |  |  |                 |  |
                              |__|__|__|                 |__|
                                                         |2 |
                                                         |v_|
                                                         |  |
                                                         |__|

```

Of course, there may be rules, e.g. like

> "Changing the direction is only possible with velocity smaller than X"

or

> "Changing the direction will take X turns when the velocity is X"

All this also depends on how exactly you want to model the track and the directions in the paper version. One can imagine generalizations of this, e.g. by using tracks that are 5 fields wide, and 8 directions (including diagonal movement). But I think that it will allow to model some behaviors that are similar to that of a real-time game:

> "Oh sh..! I'm to fast for this curve! I should have braked earlier..."

---
Tags: game-design
---


# Question
Title: Unity 5 Server Side Physics - Alternative to constant position update?
I am looking into reducing load in client server games for a uni project and am looking at physics. The idea is that if a very low powered device tries to carry out some physics heavy action that it will be very slow, therefore the power of the server can be used.

So using the power of the server, in Unity, an RPC can be sent to the server, the server carries out the physics (say throwing a box into the air) and then transmits the position of the box as it moves back to the client. But this seems to me to be putting alot of pressure on the network.

What I am getting at is, is there a way to have a server carry out physics reactions and send the results of those back (such as a jumping box) in a way that doesn't pressure the network?

All I can think of is that when the box is moving on the server that the position code is sent to the client, and then when there is a new position that is sent to the client again. If an object is moving alot this seems to be alot of position updates sent across the network, taking up bandwidth.

So is there another method instead of constantly sending position updates?

# Answer
Per a comment to the above question State Syncing seems to be the way to go. Saves me updating every frame.
> -1 votes

---
Tags: unity, physics, networking
---


# Question
Title: JAVA: Unformed Sprite When trying to Read SpriteSheet
So Im a beginner experimenting with ImageIO. Can someone tell me why im getting this pixelated-incomplete sprite?

Here's the code

```
public BufferedImage getImage(String location)
{
    try
    {
        File file = new File(location);

        image = ImageIO.read(file);
    }
    catch (IOException e)
    {
        System.err.println("It don't work!!");
        e.printStackTrace();
    }
    return image;
}

```

And Im using this method to display it

```
public void paint(Graphics g)
{
    g.drawImage(getImage("Numbers/icon0.png"), 0, 0, 32, 32, null);
    repaint();
}

```

THANK YOU IN ADVANCE

# Answer
your code actually draws a scaled image, have a look at Chris Campells article, it's really useful...

what you have to do to simply draw the whole image without scaling...

```
g.drawImage(getImage("Numbers/icon0.png"), 0, 0, null);

```
> 1 votes

---
Tags: java, sprites, image
---


# Question
Title: How can I dynamically load the correct sprite from a sprite sheet?
I am making a simple card game in unity. The game is based on a standard 52-card pack, with identical backs for unique faces. In my particular game different cards are worth different values and have various special abilities. The game will have 52 cards on the table (on the draw position or in the face-down deck or in someone's hand) at all times, so this number won't change.

I thought that making a `Card` prefab and instantiating 52 of these manually would be a bad idea. Even doing it in code, I thought, would be a bit OTT, and that I should just instantiate visual cards when they are face-up to the player.

I have a sprite sheet of the 52 cards and the back, which is imported as a Sprite in multiple mode, sliced in to a grid containing all the cards needed to play the game.

The problem I now face is that, through my `GameController` script I want to generate a shuffled pack of cards, deal some to each player and then show those cards to a player. However, I am not sure of the best way, or even if it's possible, to do this dynamically with the sprite sheets as they are. For instance if I have the following:

```
private CardRank rank;
private CardSuite suite;
private GameObject visualCard; // the card in the scene

private void Start()
{
    this.rank = CardRank.Ace;
    this.suite = CardSuite.Spades;
}

```

This class would be instantiated by the game manager. I would have 52 of these in code.

Whenever I have to visually show a card in the scene, I would use a card prefab, which is essentially a game object with a `SpriteRenderer` on it. I would need to dynamically load the correct sprite for this object from the sprite sheet. Something like this:

```
SpriteRenderer spriteRenderer = this.visualCard.renderer as SpriteRenderer;
spriteRenderer.sprite = ...

```

The sliced sprites from the sprite sheet actually have names in the format `AS` (Ace of Spades), `7H` (Seven of Hearts), etc - though this was a manual thing I did myself of course.

I have also tried various alternative solutions, including creating animations, having separate sprites not in a spritesheet and having an array of available sprites in an array with a specific index for each card, but none seem as elegant as trying to load the correct sprite at runtime, as I'm trying to.

So, **how do I load a specific sprite from a spritesheet at runtime?** I'm open to suggestions, even those that make me think differently about how to approach the problem.

# Answer
> 2 votes
my approach will be almost similar but I will prefer to use a full sprite sheet of cards to avoid the extra naming problems.

Before we get started here is the link to the sprite sheet. https://i.stack.imgur.com/gnv4Q.jpg

We need to create one script named Card which can hold its value and type. It should look like this:-

```
using UnityEngine;
using System.Collections;

public class Card : MonoBehaviour
{

    public enum Suit { Hearts = 0 , Spades , Diamonds, Clubs };
    public Suit mySuit;
    public enum Value { Ace = 0 , Two , Three , Four , Five , Six , Seven , Eight , Nine , Ten , Jack , Queen , King };
    public Value myValue;

}

```

Now import the image into resources folder and slice it using default grid option. You will get nicely numbered sprites which we can use :)

Note that the enum in Card script are arranged as per the order of sprites in the sheet.

We need one prefab to be stored in Resources folder which will have a Sprite renderer and the Card script

The last part is the core logic to populate the cards.

* Load the Sprites into an array from resources folder.
* Run 2 nested for loops for the cards.
* Make it a child of the current game object (optional)
* Assign the card sprite , use i and j to calculate the index
* Assign the enums for Suite and Value.
* Then finally the name :) (optional)

Code:-

```
void PopulateCards()
{
    Sprite[] card_sprite = Resources.LoadAll<Sprite>("Cards");

    for(int i = 0 ; i < 3 ; i++)
    {
        for(int j = 0 ; j < 13 ; j++)
        {
            GameObject prefab = Resources.Load ("Card") as GameObject;
            GameObject card = Instantiate(prefab, Vector3.zero, Quaternion.identity ) as GameObject;
            card.transform.parent = this.gameObject.transform;
            card.transform.localPosition = Vector3.zero;

            card.GetComponent<SpriteRenderer>().sprite = card_sprite[(i*13)+j] ;
            card.GetComponent<Card>().mySuit = (Card.Suit)i;
            card.GetComponent<Card>().myValue = (Card.Value)j;
            card.gameObject.name = ((Card.Suit)i).ToString()+"_"+((Card.Value)j).ToString();

        }
    }
}

```

# Answer
> 1 votes
Using Unity SpriteEditor cut out the sprites from the texture. In your script, add:

```
public Sprite[] cardSprites;

```

In script inspector set the size of 52. Then just fill it with sprites. You do that by going to project window and mouse-moving all sprites from sprite sheet. Now you have all your sprites individually.

Having said that, you absolutely shouldn't be having 52 scripts, each for a card. One script is enough. Have sprite list in your manager and just make a function GetSprite(CardRank, CardSuite) which will return sprite you want. You can use int values from enum to make it painless, like:

```
public enum CardSuite { Spades = 0, Clubs = 1, Hearts = 2, Diamonds = 3 } // enums get assigned ints from 0 automatically but it's nice to have them written down so you know you depend on it

public Sprite GetSprite(CardRank rank, CardSuite suite)
{
    // suit goes 0-3, rank goes 0-12
    return cardSprites[((int)suite + 1) * (int)rank]; // probably not correct but you get the point
}

```

You just have to place the sprites in inspector in a sorted way, like you have your enums.

# Answer
> 1 votes
You could Create one Sprite Card Object. Give it the the four suit textures, face card textures, and card background texture. Example : for the 7 of spades you would draw the spade texture at 7 different locations with a white texture of a card in the background, and use DrawString to Draw the 7. That way you could (in your game class) say Card card = new Card(7,spades), and it would then create an instance of a Card class you set up, and draw 7 spades on the card, with a 7 in the top right and bottom left upside-down.

---
Tags: 2d, unity, spritesheet, card-game
---


# Question
Title: How can I debug _why_ glDrawArrays is very slow?
I'm working on a game that uses CEGUI and Ogre. Recently, we've discovered that some of our customers with GeForce4 MX 4000's, performance is terrible.

After a night spent debugging, I've tracked the issue down to a glDrawArrays call inside the Ogre GL Renderer. Most executions of this call are pretty quick (\<10ms, which still sucks but is ok for this terrible card). But one execution of the GLRenderSystem::\_render function takes 3500ms every single frame.

It's only drawing a 54-element TRIANGLE\_LIST. All the other calls to it are drawing similar-sized TRIANGLE\_LISTs, so it's not the size of the array or its type that is the problem.

I've:

* disabled fragment shaders (the GF4 MX doesn't support them)
* disabled vertex shaders (it supports them, but CEGUI can only do all types of shaders or none of them)
* attempted to disable a nearby call for multitexturing
* massively simplified the UI that I'm drawing so that it is only a single CEGUI::Window

But I'm really just shooting in the dark. I'm in a windows environment. What's a good tool to figure out the OpenGL state at the time of a function call? I'm guessing that there's a particularly piggish texture or a fragment shader somehow slipping through and getting rendered.

If there aren't any tools to do what I need, can anyone suggest ways that glDrawArrays could be made really slow on an old card?

Update:

* I grabbed GLTrace and compared the calls that precede both a fast glDrawArrays and a slow one. They're absolutely identical, they're even binding the same texture IDs.
* One consistent difference however, is that the call that executes slowly is the first one in each OGRE/cegui render frame. Perhaps there is some copying-over of texture data to the video card each frame (which would be ridiculous and clearly doesn't happen on other cards...). Update: this isn't the case - no matter where in the queue I draw the offending object, it still takes forever. See below.
* There are 3 main objects being drawn: a full-window background (plain white, gets textured with a 128x128 texture), a smaller rectangular label, and text in that label. The ratios between their draw speeds are approximately the same the ratios between their areas
* If I force the slow object to be drawn several times instead of drawing the entire render queue, it is slow every time, which means it's not a one-time-loading issue.

Update for current theory: this is somehow a fill-rate issue. Is there a way to configure a window so that the card has issues filling it? Since I'm drawing in windowed mode, will that mess up a card sometimes? My window doesn't have power-of-two dimensions (or dimensions similar to any standard resolution), could that be a chokepoint?

# Answer
Got it:

1. The Geforce4 MX with the newest-available nVidia drivers (circa 2006) doesn't support the glTexEnv approach to blending source and destination textures. At least, not in hardware. Drawing the simplest shapes results in crippling slowness.
2. However, it does appear to support GL\_BLEND combined with glBlendFunc in hardware.

Solution: Instead of the complicated cegui setup show below:

```
glTexEnvi(GL_TEXTURE_ENV,GL_TEXTURE_ENV_MODE,GL_COMBINE_EXT)
glTexEnvi(GL_TEXTURE_ENV,GL_COMBINE_RGB_EXT,GL_MODULATE)
glTexEnvi(GL_TEXTURE_ENV,GL_SOURCE0_RGB_EXT,GL_TEXTURE)
 glTexEnvi(GL_TEXTURE_ENV,GL_SOURCE1_RGB_EXT,GL_PRIMARY_COLOR_EXT)
glTexEnvi(GL_TEXTURE_ENV,GL_SOURCE2_RGB_EXT,GL_CONSTANT_EXT)
glTexEnvi(GL_TEXTURE_ENV,GL_RGB_SCALE_EXT,GL_LINES)
glTexEnvi(GL_TEXTURE_ENV,GL_OPERAND0_RGB_EXT,GL_SRC_COLOR)
glTexEnvi(GL_TEXTURE_ENV,GL_OPERAND1_RGB_EXT,GL_SRC_COLOR)
glTexEnvi(GL_TEXTURE_ENV,GL_OPERAND2_RGB_EXT,GL_SRC_ALPHA)
glTexEnvi(GL_TEXTURE_ENV,GL_OPERAND0_ALPHA_EXT,GL_SRC_ALPHA)
glTexEnvi(GL_TEXTURE_ENV,GL_OPERAND1_ALPHA_EXT,GL_SRC_ALPHA)
glTexEnvi(GL_TEXTURE_ENV,GL_OPERAND2_ALPHA_EXT,GL_SRC_ALPHA)
glTexEnvi(GL_TEXTURE_ENV,GL_TEXTURE_ENV_MODE,GL_COMBINE_EXT)
glTexEnvi(GL_TEXTURE_ENV,GL_COMBINE_ALPHA_EXT,GL_MODULATE)
glTexEnvi(GL_TEXTURE_ENV,GL_SOURCE0_ALPHA_EXT,GL_TEXTURE)

```

I'm going to do this: `glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA)`

If you, future reader, are modifying your OgreGLRenderSystem as well, I'm going to do this change in GLRenderSystem::\_setTextureBlendMode in OgreGLRenderSystem.cpp.
> 6 votes

# Answer
I got it, too. For me it was an issue with the Texture. On NVIDA things worked out fast. But my optical optimisation caused an ATI card to nealy resign.

I work with a texture of size 4720 x 5600 (about) and modern cards work well with it.

I tried to optimize borders using Wrapmode=GL\_CLAMP\_TO\_BORDER\_ARB . Therefore I need to supply the border argument to glTeximage2D as at least == 1. Since the questionable Card did not support border in HW, it turned out to take 20 sec for one frame. Going back to GL\_CLAMP\_TO\_BORDER + border param==0 made it speed up again.
> 1 votes

---
Tags: opengl, windows, ogre
---


title: LibGDX how to change animations

text:
# Question
Title: LibGDX how to change animations
I have a Player Class and i have 3 different Animations for it. I can render them perfectly but i don't know how to change from one animation to another. For exmaple i have 3 animations, one for Running, one for Jumping and one for Rolling down. Now i want to to change from running animatioon to Jumping when user presses a button. Inpout is not the problem. I am using the same code at LibGDX wiki to create to sue animation just like in this link: https://github.com/libgdx/libgdx/wiki/2D-Animation

It would be very helpful if you could give an example too but its not necessary though.

# Answer
> 2 votes
An animation is just a group of frames which are drawn sequentially. If you were able to render one animation, to change it you just have to change the frames.

That example splits a Texture into TextureRegions by splitting it in a grid, I recomment you create a TextureAtlas instead, its easier to access the different TextureRegions in it.

To change the Animation, you just create a new instance of Animation with a different set of frames. That is really just it.

# Answer
> 0 votes
Well, just a simple way to do it, in your player class create the 3 textures for each animation if you're not using a TextureAtlas, then use a int playerState to specify the state of the player (1 for running, 2 for jump, 3 rolling down),and finally in the draw method use a bool to check playerState and draw each animation.

# Answer
> 0 votes
I have to agree with Xkynar on this, but I'd like to add something. In order to keep track of the different animations, you can use the libGDX Hashmap in order to store each Animation object under a string name, like "running" ,"walking", or whatever. Each animation can then be accessed by requesting the name of the animation in the Hashmap. If you'd like more information I can probably find an example somewhere.

---
Tags: java, libgdx
---


# Question
Title: How can I render "two-sided" clouds like in Minecraft?
The clouds in Minecraft are semi-transparent and are rendered on both sides. If you fly into the cloud you can see inside of the cloud. If I render clouds the inside faces would be visible on the outside. How can I prevent that? Z-Ordering the faces and render near to far with depth test on? There must be a better, easier way. Could the accum or stencil buffers be used somehow?

UPDATE : I think the crucial point everyone is forgetting is that these clouds and semi-transparent and "blended" into the scene as each face is rendered. If two faces are rendered on top of each other the "white" texture will double up which is undesired. The faces also seem to have slight lighting variations which would rule out using a stencil.

UPDATE2: Just another note. Each cloud is 12x12x4 blocks (roughly). Larger clouds are just a group of the base clouds stuck together.

Here's showing clouds from above. They are translucent and the chunks below can be seen.

And here's the view from inside them.

# Answer
> 1 votes
Set culling to cull front faces first, then render your clouds. This will render the backfaces. After that, switch culling to cull backfaces, and render the clouds, which will render the front faces on top of the back faces.

This will prevent rendering your backfaces on top of the front faces, but still keep back faces visible all times.

**Update:** From the pictures, I see that the backfaces are only visible when you are inside. ~~Just switch the order of the above instructions: Render front faces first, backfaces later so they are discarded by the z buffer if you are outside.~~ Just render with culling disabled in that case.

# Answer
> 0 votes
Sounds like the clouds have both inside and outside faces. Make your cloud double sided but don't turn off backface culling.

# Answer
> 0 votes
I think the only solution is to do a 2 pass rendering (as Janos said). But the clouds first need to be Z-Ordered. Then render the outside faces of all clouds (back culling), and then render all inside faces (front culling). This will prevent seeing the inside faces from outside, and the sorting will prevent seeing a cloud behind another cloud. Remember the clouds and semi-transparent and "blended" into the scene as each face is rendered.

UPDATE : "Each" cloud must be rendered in 2 passes individually. Do outside faces, then inside faces. Then repeat that for each cloud. Clouds must still be z-ordered.

Here is some pseudo code:

```
void renderClouds() {
  Cloud clouds[] = getClouds();
  clouds = sortClouds(clouds);
  for(int a=0;a<clouds.length;a++) {
    glCullFace(GL_BACK);
    clouds[a].render();  //render outside faces
    glCullFace(GL_FRONT);
    clouds[a].render();  //render inside faces
  }
}

```

That works for me now. But I'm open to better ideas.

# Answer
> 0 votes
I think there's a special shader for that. To lighten the alpha calculation, it might only consider the first alpha from the mesh from the POV, and blend everything else behind it that has no alpha (or that is not clouds).

From the inside of a cloud, other clouds are no longer visible.

# Answer
> 0 votes
I suggest another approach:

First you render your world and sky, etc. just like you would do normally.

Then you have to sort the clouds (or the vertices of the clouds) from closest to the camera to furthest from the camera. You then test if the camera is inside a cloud, if this is the case, you will have to turn off back face culling so that the insides of the cloud will be rendered.

Then you render your clouds (from near to far) and if you have depth test enabled you will not have any clouds overlapping.

This is my theory. If it is wrong, please let me know so I can learn from it.

---
Tags: opengl, minecraft-modding
---


# Question
Title: How to achieve a for loop without Unity crashing?
I want to make a for statement that repeats constantly until a *stop* variable becomes "1". But wherever you type a "for" statement in any way or even without anything in the statement, Unity just crashes without even a report. So is there a way to achieve the same effect without using the for statement?

(Here's an example script that would crash.)

```
#pragma script
var stop : int;

fucntion Start()
{
  for(stop=0;stop<2;stop++ )
  {
    Debug.Log("Hi");
  }
}

```

No matter where you put it, or what you do with it, or how you change it, it just crashes. So my question is: **Is there an alternative to for statement?**

# Answer
> 1 votes
The example you have posted should work fine. I would suggest there is something else wrong in your project if that is not working.

If your loop repeats too many times, or indefinitely as you have suggested in your question then you might cause Unity to hang, since it will wait for the loop to complete before it updates the next frame. You will need to use a coroutine and put your loop in there instead, if that is the case.

http://docs.unity3d.com/Manual/Coroutines.html

---
Tags: unity, java
---


# Question
Title: How to draw a BitmapFont every user click
Im starting learning the libgdx framework and I want to "clone" some games. I know how to handle touch with

```
if(Gdx.input.isTouched())

```

But how do I render new fonts every time user clicks on the screen? (Like the Numbers going up and desapearing) I tried creating new objects, and made a array to store all "y" positions, but both no success.

# Answer
> 1 votes
**There is no exact (and short) answer for what you are asking, but I'll try to help you for some parts that you need to know in order to achieve this.**

*for simplicity, I'll skip and resume a lot of code* *

---

First part is ***How can I render text?***. There are plenty of tutorial in internet. A fast example is the `Scene2D` library (already in libGDX yei!) using the `Label` class or an easiest option using the `BitmapFont`.

I'll follow the second one. To render text with `BitmapFont` you could follow this tutorial. I'll resume it skipping parts like adding the font to your project blablabla in order to create a class like the following:

```
public class MyText {
    // flag to know when the text expired
    private boolean stillAlive = true;
    private String text;
    private Vector2 position;
    // random lifetime...
    private float life = 1f;

    public MyText(String text, Vector2 position){
        this.text = text;
        this.position = position;
    }

    public void update(){
        // You could move your text here...
        position.y += 1;

        // we will need something like this to remove old text
        life-=0.01f;
        if(life <= 0){ stillAlive = false; } // <-- kill text
    }

    public void draw(SpriteBatch batch, BitmapFont font){
        font.draw(batch, text, position.x, position.y);
    }
}

```

So now, in my principal game class I'll create a container of `MyText` objects called `text2show`, then in the `render()` method, I'll iterate through this object to update my text (move, expire, blablabla) and then draw it:

```
public class TestGame implements ApplicationListener {
    private SpriteBatch batch;
    // Default font...
    private BitmapFont font;
    // This object will contain all my text to render...
    private Array<MyText> text2show = new Array<MyText>();

    // ... constructor, create, dispose, resize, pause, resume ...

    @Override
    public void render(){
        // some code...

        // First iterate through all your available text to update them
        for(Iterator<MyText> it = text2show.iterator(); it.hasNext();){
            MyText t = it.next();
            t.update();
            // Check if some of them has expired, if true, remove them
            if(!t.isStillAlive()){ it.remove(); }
        }

        // Now you can render all your text items
        batch.begin();
        for(MyText t : text2show){
            t.draw(batch, font);
        }
        batch.end();
    }

    // ... rest of code
}

```

So, here we have create a container and a class that can handle the draw and update of my text. Next question is ***When do I will add a new text?***. For this, there are two approach: **by polling** and **by handling events**. There are a lot of tutorials about this, an example is this one.

What you wrote is polling:

```
@Override
public void render(){
     // If a touch has occur, then add a new text item to draw...
     if(Gdx.input.isTouched()) {
         text2show.add(new MyText(
             "test", new Vector2(Gdx.input.getX(), Gdx.input.getY())));
     }

     // rest of the code (update text, draw text blablabla)...
}

```

Basically you just ask every loop if a touch has been made. The other option is using the `InputProcessor` and/or `GestureListener` interfaces to separate this part and let a listener to handle it:

```
public class TestGame implements ApplicationListener, InputProcessor {
    // variables...
    // ... constructor, create, render, dispose, resize, pause, resume ...

    @Override
    public boolean touchDown(float x, float y, int pointer, int button) {
        // If a touch down has occur, add a new item to draw...
        text2show.add(new MyText("test", new Vector2(x, y)));
        return true;
    }

    // keyDown, keyUp, keyTyped, touchUp, touchDragged, mouseMoved, scrolled...
    // ... rest of code
}

```

There are pros and con for both approach, use whatever you want.

For the last part. ***How can I handle smooth transitions?***. In the code that I post I just made horrible animations changing the position linearly. But what if you want a smooth transition? a smooth movement or a smooth fade-out before remove your text? what if you want to remove your text in a certain amount of time?

You will need an interpolator. An option is the Universal Tween Engine but you can made your own, this tool helps with the interpolation maths and is very easy to implement it, for simplicity I'll let the rest to you.

I hope this could help you to achieve what you are looking for! :)

---
Tags: java, libgdx
---


# Question
Title: How to remove a component of an object in a script?
I want to remove a *Sphere Mesh Renderer* component from a certain gameobject. I want to do this in a script. How do I do it? **I do not want to destroy the sphere itself, just the component**

# Answer
> 5 votes
You can `Destroy` the component.

Be careful about which object you destroy, though. If you pass a GameObject to `Destroy`, you will destroy the entire thing. To destroy the component, you must pass a reference to that component specifically.

```
//example: destroys the MeshRenderer attached to this GameObject
var sphereMesh = GetComponent(MeshRenderer);
Destroy(sphereMesh);

```

---
Tags: unity, javascript, 3d-meshes, gameobject
---


# Question
Title: Can't give my pictures the right location in libGDX
I have this code here

```
 sb.draw(title, (PPlane.WIDTH / 2) - (title.getWidth() / 2), (float) (PPlane.HEIGHT / 10));
 sb.draw(playBtn, (PPlane.WIDTH / 2) - (playBtn.getWidth() / 2), PPlane.HEIGHT / 2);

```

This gives me a picture in the middle (playBtn) and a picture beneath it (title). But I want the picture title to be above picture playBtn. So what i did was:

```
 sb.draw(title, (PPlane.WIDTH / 2) - (title.getWidth() / 2), (float) (PPlane.HEIGHT / 1.2));
 sb.draw(playBtn, (PPlane.WIDTH / 2) - (playBtn.getWidth() / 2), PPlane.HEIGHT / 2);

```

I changed the number that divide PPlane.HEIGHT in draw.title so it would appear above playBtn, but instead it just dissapeared.

I also tried to change the cam.setOrtho to True with the first code but that didn't work either.

What should I do to fix this?

# Answer
> 1 votes
In order to make the title appear with the image you need to use the location of the image plus an offset. The reason (PPlane.WIDTH / 2) - (title.getWidth() / 2) works to center the image is because you're finding the midpoint of the PPlane and then subtracting an offset equal to half of the title's width which has the effect of centering the image horizontally.

So to find the correct vertical positioning of the title you need to use the vertical position of the playBtn (which in this case is PPlane.HEIGHT / 2) and add an offset of the height of the playBtn so that the title is positioned just above it.

The final code should look like:

```
sb.draw(title, PPlane.WIDTH/2 - title.getWidth()/2, PPlane.HEIGHT/2 + playBtn.HEIGHT );
sb.draw(playBtn, PPlane.WIDTH/2 - playBtn.getWidth()/2, PPlane.HEIGHT/2);

```

You may need to adjust the offset by a few pixels to account for transparency around your title text.

---
Tags: java, libgdx
---


# Question
Title: 2D Rectangle/Circle Continuous Collision Detection
I'm looking for a fast 2D continuous collision detection algorithm for circles and rotated rects. *It needs to determine the time of collision.* Both shapes may be moving at high speed, so the algorithm should not assume that one is stationary.

***What I found so far (what I'm not looking for):***

* I've found several tutorials for swept tests for AABB's, but these all involved axis-aligned (not rotated) rects.
* I've found and implemented a separating axis theorem (SAT) algorithm to determine if rotated rects are intersecting with other rects or circles, but obviously that is not continuous.
* I'm not looking for reduced-time-interval-based tests here; the objects' speeds are potentially very high so that kind of inelegant solution is impractical due to computational costs.

***What I already have:***

* I already have continuous collision detection between circles implemented (Small, High-Speed Object Collisions: Avoiding Tunneling). Now I just need the circle/rect and rect/rect versions.
* As I said above, I also already have the SAT implemented to detect circle/rect and rect/rect intersection (but obviously that's not continuous).

Thank you very much for your time and help!

*Edit: I'm not worried about rotational velocity over the space of a frame.*

# Answer
> 4 votes
I forgot to come back to this question when I arrived at an answer, but this has gotten a decent amount of views over time, so better late (even 2 years late) than never! First, prerequisites:

# Prerequisites:

First, one has to be able to calculate the time of collision (TOC) of two circles. Step 3 of this question Small, High-Speed Object Collisions: Avoiding Tunneling provides an adequate formula.

Next: be able to find a point/circle TOC: simply take the equation linked above and set one of the circles' radii to 0 to represent the point.

Next: be able to find a point/line segment TOC. A simple way to do this (I'm sure there are better ways, this is just a starting point):

* Shift all relative motion to the point, so you have a moving point and a "stationary" line.
* The point's path (described by a line) intersects the line containing the line segment (or it is parallel). For line/line intersection, takes equations Ax + By = C (for line segment...A=y2-y1, B=x1-x2, and C = x1\*y2-x2\*y1) and paramaterized equation Px + Vx*t and Py + Vy*t for moving point and solve for t: (C - A*Px - B*Py) / (A*Vx + B*Vy). I chose these forms so I don't have deal with horizontal/vertical cases. If the denom is 0, the lines are parallel.
* Once you have a time/point of intersection, check and see if that point lies on the line segment.

# The Solution:

### Circle/Rect:

"Reduce" the circle to a point, and "grow" the rectangle by radius r of the circle. The result is that the 4 sides (red) of the rect are translated out (orange) and the corners are expanded out and rounded by radius r. We know how to find the TOC for point/circle and point/line segments, so find the earliest TOC of the point with those 8 shapes representing the surface of our new shape (the 4 orange lines and the 4 blue circles). That is your answer. (There may the collisions with parts of the circles that are not on the surface, but your algorithm will ignore those automatically since the point will already have penetrated the surface at an earlier time). If there is no TOC, then there is no collision. Beware of "past" collisions when the objects are moving away from each other.

### Rect/rect:

Start with one rect as the "point" rect and the other as the "side" rect. Find the TOC (if it exists) with each point on the point rect compared to each side of the side rect. That's 16 checks. Switch the rects and repeat for a total of 32 checks. The earliest non-imaginary and non-past TOC (if it exists) is the TOC. Note that any "side-side" collision of two rects can be treated as a "point-side" collision, and that is how this algorithm handles it.

### Considerations:

This may all seem extremely inefficient, but keep three things in mind:

* Good broadphase and medium-phase collision detection is important to make sure you are doing all of these expensive calculations as little as possible
* Directional optimizations are possible (e.g. only check a few of those 32 rect/rect pairs that are facing in the appropriate directions)
* These are extreme algorithms, designed for small objects colliding at extraordinary speeds. If the situation truly calls for an algorithm like this (e.g. 2 meter-sized objects colliding at relative speeds of 1000's of km's per second), these "inefficient" algorithms will be much better than most traditional alternatives.

# Answer
> 3 votes
If you already have SAT working, then you can pretty easily extrude an OBB along its linear velocity for a frame (i.e. create a swept OBB). The result will be a polyhedron, so you can use SAT with it. This only handles linear velocity, though, not rotational velocity. That's quite a bit harder because a rotating OBB sweeps out a volume that isn't a polyhedron.

Another thing to look into is the GJK algorithm. It uses a different representation of shapes (i.e. not polygonal) so it may be easier to use with rotational velocity. I'm not familiar with the state of the art here though.

One problem with using swept shapes and high-speed objects is that a collision may be detected even when the objects should miss each other, if their trajectories during the course of a frame happen to intersect. I'm not aware of any approach to solve this other than using finer timesteps, or using 4D (spacetime) collision detection.

---
Tags: 2d, collision-detection, collision-resolution, efficiency, separating-axis-theorem
---


# Question
Title: Connecting 3d corridors created by procedural generation?
The 2d case is simple. You generate the segments. You find the intersections. Then you can easily outline the shape of the connecting joint in the 2d embedded graph.  However, in 3d or n-d with a whole new variety of directions (corridors from above and bellow), it is more complicated and I'd like to hear some advice. The corridors themselves are simple. The challenge is the "connecting room" between them (you can imagine that room as convex hull of the red in blue dots). This is the goal here.

One way to overcome this, is using voxels and then leaving only the exterior of the connected corridors. This is not optimal however. Is there any simply way to generate the room in the center without complex binary operations?

# Answer
Your observation about the convex hull of intersection points still works in 3d & can be computed relatively quickly.

You could simplify things by restricting the the orientation of the corridors.
E.G. restricting to 90 degree turns reduces the 3d problem to a series of 2d problems.
> 1 votes

---
Tags: 3d, procedural-generation, 3d-modeling
---