# Question
Title: How to avoid texture bleeding in a texture atlas?
In my game there is a Minecraft-like terrain made out of cubes. I generate a vertex buffer from the voxel data and use a texture atlas for looks of different blocks:

The problem is that the texture of distant cubes interpolates with adjacent tiles in the texture atlas. That results in lines of wrong colors between cubes (you may need to view the screenshot below at its full size to see the graphical flaws):

For now I use these interpolation settings but I tried every combination and even `GL_NEAREST` without mipmapping doesn't provide better results.

```
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);

```

I also tried added an offset in the texture coordinates to pick a slightly smaller area of the tile but since the unwanted effect depends on the distance to the camera this cannot solve the problem completely. At far distances the stripes occur anyway.

How can I solve this texture bleeding? Since using a texture atlas is popular technique there might be a common approach. Sadly, for some reasons explained in the comments, I cannot change to different textures or texture arrays.

# Answer
> 7 votes
After struggling a lot with this issue, I finally came up with a solution.

To use both, a texture atlas and mipmapping, I need to perform the downsampling myself, because OpenGL would otherwise interpolate over the boundaries of tiles in the atlas. Moreover I needed to set the right texture parameters, because interpolating between mipmaps would also cause texture bleeding.

```
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST_MIPMAP_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);

```

With these parameters, no bleeding occurs.

There is one thing you have to notice when providing custom mipmaps. Since it doesn't make sense to shrink the atlas even if each tile is already `1x1`, the maximal mipmap level must be set according to what you provide.

```
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 7); // pick mipmap level 7 or lower

```

Thanks for all other answers and very helpful comments! By the way I still do not know how to use linear up scaling, but I guess there is no way.

# Answer
> 41 votes
Okay, I think you have two problems going on here.

The first problem is with mipmapping. In general, you don't want to naively mix atlasing with mipmapping, because unless all your subtextures are exactly 1x1 pixel sized, you will experience texture bleeding. Adding padding will simply move the problem to a lower mip level.

As a rule of thumb, for 2D, which is where you usually do atlasing, you don't mipmap; while for 3D, which is where you mipmap, you don't atlas (actually, you skin in such a way that bleeding won't be a problem)

However, what I think is going on with your program right now is that you're probably not using the correct texture coordinates, and because of that your textures are bleeding.

Let's suppose an 8x8 texture. You're probably getting the top-left quarter by using uv coordinates of (0,0) to (0.5, 0.5):

And the problem is that at u-coordinate 0.5, the sampler will interpolate the destination fragment using half of the left texel and half of the right texel. The same will happen at u-coordinate 0, and the same for v-coordinates. This is because you're addressing the borders between texels, and not the centers.

What you should do instead is address the center of each texel. In this example, these are the coordinates you want to use:

In this case, you will always be sampling the center of each texel and you should not get any bleeding... *Unless you use mipmapping, in which case you will always get bleeding starting on the mip level where the scaled subtexture doesn't neatly fit inside the pixel grid*.

To generalize, if you want to access a specific texel, the coordinates are calculated as:

```
function get_texel_coords(x, y, tex_width, tex_height)
    u = (x + 0.5) / tex_width
    v = (y + 0.5) / tex_height
    return u, v
end

```

This is called "half pixel correction". There's a more detailed explanation in here if you're interested.

# Answer
> 19 votes
One option that'll be a lot easier than fiddling with mipmaps and adding texture coordinate fuzz factors is to use a texture array. Texture arrays are similar to 3d textures, but with no mipmapping in the 3rd dimension, so they're ideal for texture atlases where the "subtextures" are all the same size.

http://www.opengl.org/wiki/Array\_Texture

# Answer
> 5 votes
Looks like the issue could be caused by MSAA. See this answer and the linked article:

> "when you turn on MSAA, it then becomes possible for the shader to get executed for samples that are inside the pixel area, but outside of the triangle area"

The solution is to use centroid sampling. If you are calculating the wrapping of the texture coordinates in a vertex shader, moving that logic to the fragment shader could also fix the issue.

# Answer
> 1 votes
This is an old topic, and I had a similar problem to the topic.

I had my texture coordinates just fine, but by lerping the camera position (which changed my element's positions) like so:

```
public static void tween(Camera cam, Direction dir, Vec2 buffer, Vec2 start, Vec2 end) {
    if(step > steps) {
        tweening = false;
        return;
    }

    final float alpha = step/steps;

    switch(dir) {
    case UP:
    case DOWN:
        buffer = new Vec2(start.getX(), Util.lerp(start.getY(), (float)end.getY(), alpha));
        cam.getPosition().set(buffer);
        break;
    case LEFT:
    case RIGHT:
        buffer = new Vec2(Util.lerp(start.getX(), end.getX(), alpha), start.getY());
        cam.getPosition().set(buffer);
        break;
    }

    step += 1;
}

```

The whole problem was Util.lerp() returns a float or double. This was bad because the camera was translating off-grid and causing some weird issues with texture snippets that where \> 0 in X and \> 0 in Y.

TLDR: don't tween or anything using floats

---
Tags: opengl, textures, interpolation, texture-atlas, mipmaps
---


# Question
Title: Calculate the best route for racing games
I'm trying to structure a system for rating player's performance in my arcade-style racing game. So I'm thinking about calculating the best route possible, and trying to guide the player towards the best way of driving. Is there any work into such problem? Links to papers/implementations would be awesome.

# Answer
I think the easiest way is to split track in sections and measure the time in each section as performance indicator. (That they do in real racing events)

As stated here what you're asking is not an "exact science".

A very hard way may be developing some sort of genetic algoritm or neural network , develop an AI that try to run the track minimizing the time, like here.
> 1 votes

---
Tags: racing
---


# Question
Title: Is it legal to develop a game using other games skill names/flavor/mechanic?
I am starting to develop a new game and i'm thinking about using some names for some features coming from other games (such as WoW and D&D).
I have already read this Is it legal to develop a game using D&D rules? and i know about Beholders and Mind Flyers (before reading this question) which i'm not going to use anyway in my game (neither specific D&D rules nor those monsters) and i'm not going to use an aready existing game system as i'm developing mine (which will use some classical RPG concepts but will have its unique flavor, at least i hope so...).

What i'm interested in is to know if i can legally use names those games use for skills, statistics, classes, enemies and so on...

I'm not talking about classic names such as Wizard, Mage, Warrior but more specific names you will find almost exclusively in that game (such as Bladesinger, Charisma, Power Attack or Warbringer...which apparently is a metal band and a monster in WoW and nothing else), these features won't be an exact copy of what you can find in other games, but will inherit just the "flavor" (sometimes not even that) of that feature

for example can i make a skill called "Power Attack" which gives you more damage per attack but a lower chance to hit (which is similar to D&D's power attack, though not exactly the same since mine will have a fixed % of damage increase and lowered chance to hit)?
What if this skill gives you more damage when using a weapon two-handed (which is a key feature of D&D's power attack in the 3.5 edition)?

I am aware that those are simple words and they can't be under copyright, what i'm more worried about is the flavor of a skill, statistic and so on and using a mechanic very similar to those found exclusively in other games

# Answer
I wish I could add a comment, but I can't since I have under 50 Rep, so I guess I'll put it here.

A question very similar to this was asked and answered on the RPG Stack Exchange and I think you'd benefit a lot from reading it.

---

First and foremost, **I AM NOT A LAWYER**, so nothing I say, should be taken as solid legal advice.

### IN GENERAL:

That linked answer says, from what I understand, you should usually steer clear from copying exact game mechanics, names, or phrases. Although, in the US Copyright registration for games page, it is clearly stated that Copyright does not protect the idea for a game:

`Copyright does not protect the idea for a game, its name or title, or the method or methods for playing it. Nor does copyright protect any idea, system, method, device, or trademark material involved in developing, merchandising, or playing a game.` \[...\] `Copyright protects only the particular manner of an author’s expression in literary, artistic, or musical form.`

So taking precise skill, class, or weapon names from another game could be viewed as a violation of the literary side of the agreement. I would assume that a skill name such as "Giru-gameshi Naput Flame" would be an infringement, but something as generic as "Strong Punch" or "Claw Swipe" isn't, since it is very generic.

---

> What i'm interested in is to know if i can legally use names those games use for skills, statistics, classes, enemies and so on...
>
> I'm not talking about classic names such as Wizard, Mage, Warrior but more specific names you will find almost exclusively in that game (such as Bladesinger, Charisma, Power Attack, Warbringer).

Even though you might think that these are "exclusive" names, you can always think of it this way, Bladesinger, is a Blade Singer, nothing more. I highly doubt you'd get into trouble with extremely generic stuff like that. Though, to stay on the safe side, I'd recommend just creating your own names, it makes your game much more unique when someone sees "Heavy Hunter Hippo" as a class and not the generic "Ranger".

---

> For example can I make a skill called "Power Attack" which gives you more damage per attack but a lower chance to hit (which is similar to D&D's power attack, though not exactly the same since mine will have a fixed % of damage increase and lowered chance to hit)?

Things like that, I would have to say you can, since "Power Attack" is a very, very generic name, it is as if saying you can't use a "Healing Potion" because it has the same name and same effect as other games.

---

> I am aware that those are simple words and they can't be under copyright, what I'm more worried about is the flavor of a skill, statistic and so on and using a mechanic very similar to those found exclusively in other games.

`Nor does copyright protect any idea, system, method, device, or trademark material involved in developing, merchandising, or playing a game.`

So I'd say you *could* use some mechanics from other games, but if you'd like my advice, I'd say take lots of inspiration from many other games, and not just one, then tweak them, fix them, improve on them, and throw them all together to make something new and unique. You're game won't go anywhere being a D&D or WoW clone, the people want something *new* something they have never seen before, so instead of taking some generic name or class from another game, create your own! I really like the name "Flying Monkey Princess of Doom". That's a bit nicer than "Paladin".
> 3 votes

---
Tags: rpg, legal
---


# Question
Title: How to resize the child node fit inside SKSpriteNode when resizing?
I am creating a virtual gamepad for my game, It has one main SKSpriteNode with circle image and four child node(up, down, left, right) with image. When I am using default size for all it looks perfect but it's big in size and when I tried to resize the main circle SKSpriteNode all it's child node are bigger then it's parent and I am unable to calculate size for child node that will fit for every condition(different size of Main node).

```
-(id)initWithJoystickImage:(NSString *)baseImage
                   upImage:(NSString *)upImage downImage:(NSString *)downImage leftImage:(NSString *)leftImage rightImage:(NSString *)rightImage
{
    if((self = [super initWithImageNamed:baseImage]))
    {
        SKSpriteNode *up = [[SKSpriteNode alloc] initWithImageNamed:upImage];
        up.position = CGPointMake(0, up.frame.size.height/2);
        [self addChild:up];

        SKSpriteNode *down = [[SKSpriteNode alloc] initWithImageNamed:downImage];
        down.position = CGPointMake(0, -down.frame.size.height/2);
        [self addChild:down];

        SKSpriteNode *right = [[SKSpriteNode alloc] initWithImageNamed:rightImage];
        right.position = CGPointMake(right.frame.size.width/2, 0);
self.size.height/2.5);
        [self addChild:right];

        SKSpriteNode *left = [[SKSpriteNode alloc] initWithImageNamed:leftImage];
        left.position = CGPointMake(-left.frame.size.width/2, 0);
 self.size.height/2.5);
        [self addChild:left];
    }
    return self;
}

```

# Answer
> 1 votes
You have two solutions:

1 - Set scale of your gamepad:

```
self.gamepad.scale = 0.5f

```

This will make all the gamepad look smaller (the main circle and the direction sprites, as they are child of the main circle).

2 - Create a init method with a size, and calculate there the size of your childs:

```
-(id)initWithJoystickWithSize:(CGSize) size andImage:(NSString *)baseImage upImage:(NSString *)upImage downImage:(NSString *)downImage leftImage:(NSString *)leftImage rightImage: NSString *)rightImage {
    if((self = [super initWithImageNamed:baseImage])) {
        self.size = size;
        SKSpriteNode *up = [[SKSpriteNode alloc] initWithImageNamed:upImage];
        up.position = CGPointMake(0, up.frame.size.height/2);
        up.size = CGSizeMake(self.size.width / 4, self.size.height / 4);
        [self addChild:up];

        SKSpriteNode *down = [[SKSpriteNode alloc] initWithImageNamed:downImage];
        down.position = CGPointMake(0, -down.frame.size.height/2);
        down.size = CGSizeMake(self.size.width / 4, self.size.height / 4);
        [self addChild:down];

        SKSpriteNode *right = [[SKSpriteNode alloc] initWithImageNamed:rightImage];
        right.position = CGPointMake(right.frame.size.width/2, 0);
        right.size = CGSizeMake(self.size.width / 4, self.size.height / 4);
        [self addChild:right];

        SKSpriteNode *left = [[SKSpriteNode alloc] initWithImageNamed:leftImage];
        left.position = CGPointMake(-left.frame.size.width/2, 0);
        left.size = CGSizeMake(self.size.width / 4, self.size.height / 4);
        [self addChild:left];
    }
    return self;
}

```

You may need to change the proportions, but this is a good way to solve your problem and will help you when you want to resize it at any size. In my opinion, this is the best solution.

---
Tags: objective-c, spritekit
---


# Question
Title: Collectible card game, cards and effects
Based on Design of a turn-based game where actions have side-effects

I am building a card-game where cards can have side-effects be triggered under different circumstances.

I was given a good idea on how to handle different phases by having hooks (events) that different cards can be triggered to do something, like when a card is played, draw an additional card, etc.

I am not sure how I should compose all these things to work together, I have a GameState object which handles the state of the game (who's turn, player objects, timers) checking if a move is legal etc.

I am having a Card class that currently just has a type and a name getter/setters and properties. I believe the best way to store cards would be to use .JSON files, because that would let you simply write a new card.

To achieve side-effects I am thinking of having "components" that is configured through a cards JSON-file.

```
{
    "name": "Ocean Humans",
    "type": "Creature",
    "components": {
    }
}

```

However, I am not sure how I should compose these JSON-files to some actually working object. How do I call these components when I invoke a hook\_event (draw a card, phase begin). And make sure right components are run?

# Answer
I would create a bytecode interpreter for this, see: http://gameprogrammingpatterns.com/bytecode.html for a lot of details. Keep in mind that the bytecode is an example, but you can easily write something similar on your own using more readable instructions. The basic idea is the same though.

So you write a bunch of small programs for each card effect. Then for each small component an events should be triggered from your gamecode. In your card JSON you could create the various available hooks with the corresponding bytecode to that hook. For example:

`{
 "name":"Healing Potion",
 "description":"When a friendlycard is damaged, ignore the damage.
 Then this card is removed from play",
 "components":{
 "friend_is_damaged":"bytecode",
 }
}`

The bytecode is executed when the event "friend\_is\_damaged" is thrown. The bytecode has the instruction "remove myself", which in turn throws the event "friendly\_card\_removed". Any card that hooks to that event will then fire.

You could create a stack of events, if you want the effects to be resolved after completing all effects from one card, instead of fire each event immediately.
> 1 votes

# Answer
Consider adding scripting to your game. Then you can store code snippets in the scripting language in the cards themselves. That will give you a lot of flexibility. This could, for example, look like this:

```
{
    "name": "Ocean Humans",
    "type": "Creature",
    "description": "When Ocean Humans dies, you lose half of your hit points"
    "components": {
        "onDie": "this.owner.damage(this.owner.currentHitPoints / 2);"
    }
}

```

Options for scripting languages are:

* Use any stock scripting language like LUA or Javascript. This is quite easy to do, because you can just use a library and you have a well-tested and optimized implementation of the language.
* invent your own domain-specific languge. This will be lots and lots of work. It *might* pay off in the long run because you can optimize your syntax for your requirements. But be pessimistic in your cost/benefit analysis. Inventing and implementing a new programming language is no trivial task.
* Or you can even use C# code you compile at runtime. This has the advantage that you can use your existing C# know-how.
> 1 votes

# Answer
I think the trick here is that a lot of cards have the same kind of effects with some variations while some cards have totally unique effects.

Imo, what you should do is to do this. This is written in typescript, but you can get the idea.

```
class Effect extends {

    static fromArray(game, card, data) {

        if (data.type == "SelfDestructEffect") {

            return new SelfDestructEffet(card, data.damagePerTurn);

        }

    }

}

class SelfDestructEffect extends Effect {

    constructor(game, card, damagePerTurn) {

        this.card = card;
        this.game = game;

        this.game.on("new-turn", () => { this.onNewTurn() });

    }

    onNewTurn() {

        this.card.damage(1);

    }

}

```

You create components that describes one effect of a card. You try to make them as customizable as possible so you can re-use them as much as possible between cards. You can still create "unique" components (i.e. that will only be used by one card) for really special effects.

Here is cards.json

```
{
    name: "Berzerker",
    type: "Human-beast",
    components: [

        {
            type: "self-destruct-effect",
            damagePerTurn: 1
        }

    ]
}

```

**Note:** The way I de-serialize the json to make the components isn't really scalable. If you're interested in how I would de-serialize the components, you can ask me, I'll write the code.
> 1 votes

---
Tags: architecture, javascript, card-game
---


# Question
Title: I can't import player relative controls in unity
I'm developing a mobile game in Unity 5 but I can't find player relative control asset anywhere.Can you help me with this?

# Answer
> 1 votes
It is called the Character Controller (I think this is what you are asking).

http://docs.unity3d.com/Manual/class-CharacterController.html

---
Tags: unity
---


# Question
Title: best way to creating card game on Android
I have a new idea for creating a new Uno like card game. I have Java programming experience but not in Android.

What is the best way creating card game on Android ? I mean handling cards easily as graphics objects.

Thanks advance for your answers.

Csaba

# Answer
> 0 votes
1, Libgdx

It's Java, and Google's ingress use this game engine.

2, cocos2d-x

Very good for 2d game, but coding language is c++ or Lua.

3, Unity3D

Good for 3d, and language is C#.

---
Tags: android, card-game
---


title: 2D Coordinate Based Game

text:
# Question
Title: 2D Coordinate Based Game
I want to make a game for Android that has a 10x10 Grid Plane as UI.In this game users going to touch on a grid and tihs grid will be painted.

My question is how do I understand which gird or tile was clicked ? I thought maybe I will make this grid on a coordinate system so that if the user touchs a point on the gamescreen aapp will take this point and will find out in which coordinate interval is in.

Like so:

I touched -\> \[-2.68,3.85\]
The grid -\> \[-3,4\] will be painted.

How do I do this in Android Studio?

# Answer
For a grid system, I haven't yet implemented this code in anything other than an engine, but I'd imagine it would be similar.

I implemented the Tetris clone in Unity 5, using this website: http://noobtuts.com/unity/2d-tetris-game

The grid section of this webpage might be of some use to you. I will try my best to convert it into java code, and make it android relevant though.

For setting up the grid I'd imagine a 2D array would be best, so you can keep track of the positions inside of the grid:

```
public class Grid
{
    public static int width = 10;    // The width of the grid.
    public static int height = 10;   // The height of the grid.
    public static GameObject[] gridObjects; // What the grid will be filled with, the paint objects? You might want to change this array type.

    // If you want a variable width and height, just pass them in here, instead of declaring values above.
    // Whenever you want to make a grid, sets up the 2D array (and width and height if you want).
    public Grid()
    {
        // Creates a 2D array for the grid structure based on width and height.
        gridObjects = new GameObject[width * height];
    }

```

To round out the coordinates, you would need to make use of Android's Math.round() function, this function can either take a double (which returns a long) or a float (which returns an int) - I assume you would want to pass in a float and gain an int.

```
    // This will round out any decimal coordinates.
    public Vector2 roundVec2(Vector2 gridPosition)
    {
        // Create your own Vector2 class in Android?
        // Or just pass in two floats, x and y!
        // Math.round() can take either a double or a float in android.
        return new Vector2(Math.round(gridPosition.x),
                           Math.round(gridPosition.y));
    }

    // This will round out any decimal coordinates.
    // Use this twice, once for the x coordinate and once for the y coordinate.
    // If you're dealing with floats instead of Vector2.
    public int roundFloat(float gridPosition)
    {
        return (Math.round(gridPosition));
    }

```

Finally, all you would need to do is setup your grid check to see if the new position is inside of the grid, so when a touch occurs on the screen, you can check to see if it is a valid grid position! A bool function which checks the borders (like on the website I linked above) should do.

Then wherever you have used onTouch for your controls, in this function I assume:

```
public boolean onTouch(View v, MotionEvent event)

```

You can use the grid functions like so, maybe use a pointer to the grid class, in the same class you handle your touch input.

```
Vector2 touchPosition = new Vector2(event.getX(), event.getY());
grid.roundVec2(touchPosition);
// Then pass in this point to your border checking function to see if the touch is within the grid boundaries.
// If it is within the bounds, PAINT the cell.

// If you are using floats instead.
int roundedTouchX = grid.roundFloat(event.getX());
int roundedTouchY = grid.roundFloat(event.getY());
// Then pass these two integers into your border checking function.
// If it is within the bounds, PAINT the cell.

// Make the array element at that coordinate equal to the PAINT object!
// If you are using a boolean array instead of a GameObject array, just switch the element to true, might be easier?

// Replace touchPosition.getX() with roundedTouchX and touchPosition.getY() with roundedTouchY if you are using floats instead of Vector2
// If you are using an array of GameObjects.
grid.gridObjects[touchPosition.getX() * touchPosition.getY()] = paintObject;

// If you are using an array of booleans.
grid.gridObjects[touchPosition.getX() * touchPosition.getY()] = true;

```

Hope this has helped in some way!
> 0 votes

# Answer
If you are going to just paint the grid, you can check out GridLayout provided by android UI. I have tried for 3X3 grid and used ImageView to set some images. To understand gridLayout , http://developer.android.com/reference/android/widget/GridLayout.html
> 0 votes

---
Tags: 2d, android, coordinates, touch, android-studio
---


# Question
Title: Unity5 - A Shader to blur far plane edges?
I need some help. In my Unity5 game I'm using two cameras, First camera renders the actual terrain and game objects (wich has a far plane of a 1000 units) and the Second camera renders a 3d skybox of sorts, a miniature of the actual terrain (it's far plane is 3200 units, but it covers the entirety of the miniature). With this setup I'm able to fake the illusion of having a very far horizon, as in the image below:

*

However, the far plane's edge is very harsh, and doesn't blend well with the 2nd camera's background. Is there anyway to blur this edge, so it trasition seamlessly with the backdrop, as in the image below (a mockup I made in photoshop)?

\*The blue line on the left image is just to outline the boundaries of the two cameras, it's not like this in the actual game nor is this the problem I'm talking about.

# Answer
> 1 votes
Here is how I would do it :

1. Modify the material used by the terrain rendered with first camera to enable alpha blending (Blend SrcAlpha OneMinusSrcAlpha).
2. So now the fragmentshader needs to output something to the alpha component (`gl_FragColor.a`, or the equivalent in Unity), for now use 1.0.
3. Modify the vertex shader to compute view space depth and store it into a varying, ex: `varying float vViewSpaceDepth`.
4. Modify fragment shader to output an alpha of 1.0 most of the time, except when `vViewSpaceDepth` is near your border; in this case you lerp() an alpha value between 1.0 and 0.0.
5. Make sure to render the terrain AFTER the skybox (Unity should in theory handle that automatically if Skybox has no alpha blending enabled, otherwise use render layers)

For example the fragment shader would do something like this :

```
if (vViewSpaceDepth > 900.0)
   final_alpha = (1000.0 - vViewSpaceDepth) / (1000.0 - 900.0);
else
   final_alpha = 1.0;
gl_FragColor.a = final_alpha;

```

What I present here is a naive and non optimized solution, but you should start anyway with a simple solution as a "proof of work" before thinking about optimizing.

---
Tags: shaders, camera, unity
---


# Question
Title: add the variation of the angle to its current angle: trouble with 180 and -180
I need to rotate a character, I would like to add the variation of the angle to its current angle. But my values are between 180 and -180. So if my character is at -179, then he goes right, it arrives at 179. how to compare that it turned by 2 degrees on his right? The goal is to say : "turn only 2 degrees on your right no matter where you are in the world". Same thing from 179 to -179 : 2 degrees to the left.

Thanks

# Answer
Based on the question, assuming that turning to the right is going a negative angle, and going to the left is going a positive angle.

Here is a small graphical reminder:

To determine what is the difference in the input, you need to constrain the delta to the same range you use:

This is the excel formula I used (row 8, with the "old" value in column A and the "new" value in colum B):

```
=IF((B8-A8)>180, B8-A8 - 360, IF((B8-A8)<=-180,(B8-A8)+360,B8-A8 ))

```

This can be translated to pseudo-code:

```
getInputDelta(oldAngle, newAngle)
  delta = newAngle - oldAngle
  return constrain180Deg( delta )

// Constraint any angle to the range ]-180, 180]
constrain180Deg(angle)
  newAngle = angle

  while newAngle > 180
    newAngle = newAngle - 360

  while newAngle <= -180
    newAngle = newAngle + 360

  return newAngle

```
> 0 votes

---
Tags: mathematics, angles, trigonometry
---


title: c++ graphics and pixels help?

text:
# Question
Title: c++ graphics and pixels help?
Is there a way to change the color of a specific pixel in C++? I've made an example project where I used graphics.h's bar to change every pixel on the screen:

```
#include <graphics.h>

int main( )
{
    initwindow(600, 600, "Example");
    for (int x = 0; x <= 600; x++) {
        for (int y = 0; y <= 600; y++) {
            bar(x,y,1,1);
        }
    }
    while (!kbhit( ))
    {
        delay(200);
    }
    return 0;
}

```

But this takes way to long like maybe 30 seconds. I was wondering if there was a way to do it faster, under a second. btw I'm using dev-c++.

# Answer
You could try `putpixel` (`void putpixel(int x, int y, int color)`)

Although I'm not really sure that's going to be fast enough. You're using `<graphics.h>` which is a very old library designed for when many computers were running DOS and had resolutions like 320x200 - a quarter of your target. On Windows it would be using GDI under the hood, not exactly the fastest option.

If you want to stick with this library, try to use shape drawing or image drawing routines as much as possible, and avoid single pixel drawing.

There are a few suggestions on more modern graphics libraries here, which you ought to learn instead: https://stackoverflow.com/q/7860569/2038264
> 2 votes

# Answer
First of all

Do not use that deprecated library ( unless you know why you r using it eg. For assignments)

You want fast graphics but the problem here is the old drivers used on a modern machine. For the fast rendering you should prefer either directx(only on windows) or opengl(available on multiple platforms).

If you choose to use opengl then go to nehe's tutorials and there you can start understanding the modern libraries.

In opengl putPixel sets pixels on screen w.r.t array provided
> 0 votes

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


# Question
Title: Using glm to rotate the modelview matrix based on the cursor position
I am rendering a 3D model of an object, and I want the user to be able to rotate around that object by dragging the mouse. To do this, I want to use the cursor position to continually update the modelview matrix.

To start with, my modelview matrix is:

```
1 0 0 0
0 1 0 0
0 0 1 -100
0 0 0 1

```

So the camera is looking at the origin of the object, and 100 units away from it. Let's say the mouse now moves onto the right-hand side of the screen. This means I want the camera to rotate around the object -- by 90 degrees, for example.

In order to compute the new modelview matrix, I take the identity matrix, rotate it by 90 degrees, and then move away from the object along the camera's z-axis by using `glm::translate()`.

However, the problem I am having is that `glm::translate()` seems to move the matrix with respect to the world coordinate system, not the camera coordinate system. Therefore, "moving away from the object along the camera's z-axis" does not hold, because the z-axes of the world and camera coordinate systems are no longer aligned after the rotation.

Please could somebody explain how I should be achieving this?

Thank you :)

# Answer
Rotations occur relative to the origin, so you want the camera to be 100 units away already before you rotate it if you want the camera to stay focused on the origin.

This image will hopefully make it clear (source page):

The view matrix you would use is then (I apply the transformations from right-to-left):

```
view = inverse( rotate(90) * translate(100) * identity )

```

Which follows from the fact that the view matrix is the inverse of the camera's world coordinate matrix.
> 1 votes

---
Tags: opengl, graphics, matrix, coordinates, glm
---


title: How to have real time (blood) traces?

text:
# Question
Title: How to have real time (blood) traces?
https://www.youtube.com/watch?v=Tzf3zjPJYw4

In this game, Ink, color blobs fall then they create pretty color spots.

The color traces are unlike any other game.

For an example, in Super Meat Boy https://www.youtube.com/watch?v=snaionoxjos

The red traces of SM Boy was more of sprites aligned across the surfaces of the object.

The trace in game Ink is different from those traditional traces of other games because...

1. They stack infinitely.
2. Come in many different shapes.

The approaches I can think of are...

1. Prepare many different shapes sprites, then put then where traces should be.
2. Assign each block with their own texture, then draw the traces on that texture.

The issues I see however are...

1. First solution will lead to having many-MANY-*MANY* sprites being generated to look as if the traces are being drawn upon the object.
2. Heavy calls between GPU and CPU. Keep drawing traces while uploading drawn new texture onto the GPU to be rendered. Significantly slowing down the game.

I don't have a good computer. My computer cannot handle either approach 1 or 2. But it can the run the game Ink.

So I am assuming Ink must use some sort of clever approach to handle this crucial visual aspect of the game. But I am out of ideas.

# Answer
Actually the author of Ink wrote a blog post explaining just that !

He is using Game Maker "surfaces" which are I think the equivalent of Framebufer Objects with color texture attachments in OpenGL.
> 4 votes

# Answer
You could use a large texture for procedurally generating those decals on the GPU.

You could draw them in a way where they take the angle, density, viscosity, velocity (whatever you want) into account when drawing them.

A 1024×1024 surface would give you 256 different 64x64 decals at any given time. You choose to use 2 blocks for longer "smears" if that's worth it. Should be more than enough though if you are expiring them?
> -1 votes

---
Tags: graphics, rendering, graphic-effects, gpu, image-effects
---


# Question
Title: Is there anyway I can make a plane visible from both sides?
In Unity i have a model of a tree with leaves made of a plane and a texture, when I upload it to unity the texture is only visible on one side so how can I change it to be visible from both sides without increasing the polygons. And I am not familiar with complicated shader programming and stuff so could you please explain in detail. Thanks I'm advance.

# Answer
> 2 votes
Try turning off backface culling.

In your shader, put "Cull Off" in the "SubShader" section.

---
Tags: unity, shaders, textures, blender, low-poly
---


# Question
Title: WorldToGUIPoint seems always off by about 2 pixels
I'm trying to draw small boxes at each vertex of a mesh, in the editor. My OnSceneGUI code looks like this:

```
foreach (Vector3 vertex in _mesh.vertices) {
    Vector3 worldVertex = _meshTransform.localToWorldMatrix.MultiplyPoint3x4(vertex);
    Vector2 guiPoint = HandleUtility.WorldToGUIPoint(worldVertex);
    var rect = new Rect(guiPoint, Vector2.one * BOX_SIZE);
    EditorGUI.DrawRect(rect, Color.red);
}

```

I want the upper-left corner of each box to align with the mesh vertices. With the above code, the boxes are drawn at the wrong location, as you can see in the picture below. If I apply an offset of (2, -2) in GUI coordinates, however, the boxes are drawn at the correct location.

I'd like to avoid having to hard-code this (2, -2) offset into each draw call. Why is Unity off by a few pixels here? I also tried using `GUI.Box` to do the drawing, but it was off by the same amount. What is going on?

**Incorrect**

**Correct. With constant (2, -2) offset**

**Update:** I have an untested hypothesis as to why this is happening. I am rendering a GUI rect with the default `GUIStyle`. The default `GUIStyle` has the `padding` and `margin` values set. I bet that if I created a custom `GUIStyle` with zero `padding` and `margin` the rects would draw where I want them to.

# Answer
I am not sure about the 2 pixel displacement , but try putting the camera in orthographic projection this might fix the problem.
> 1 votes

# Answer
The `GUI` and `EditorGUI` drawing functions seem to not be the best solution for the level of drawing precision that I need. They seem to be influenced by `GUIStyle`, which has dozens of properties that may interfere with positioning. The better solution I found was to use `GL` combined with the built-in shader `Hidden/Internal-Colored` to get the screen-space positioning that I wanted:

```
    var shader = Shader.Find("Hidden/Internal-Colored");
    var material = new Material(shader);
    material.hideFlags = HideFlags.HideAndDontSave;
    material.SetInt("_ZWrite", 0); // Don't write to depth buffer
    material.SetInt("_ZTest",  (int)UnityEngine.Rendering.CompareFunction.Always); // Always draw on top of other elements
    material.SetPass(0);

    GL.PushMatrix();

    GL.LoadPixelMatrix();
    GL.Begin(GL.QUADS);
    GL.Color(Color.red);

    // For each vertex, convert it to screen-space with
    // Camera.current.WorldToScreenPoint, then use
    // GL.Vertex3 to draw a quad around it

    GL.End();

    GL.PopMatrix();

```
> 0 votes

---
Tags: unity, gui
---


title: Special Pathfinding Algorithm

text:
# Question
Title: Special Pathfinding Algorithm
I need help with following pathfinding Task:

I have a grid (7x7 squares) and the starting square is always on the far left side (column 0) and its target is to reach the far right side (column 6). Between col 1-5 are some walls where the path should "walk" around.

The special thing about the task is, the path can only walk straight,diagonal up, diagonal down, so its column increases += 1 for each movement.

For Example: (row/col) Start:(1/0) Path:(1/1) straight :(2/2) daigonal down :(3/3) diagonal down :(3/4) straight :(4/5) diagonal down :(4/6) straight (reached col 6 , finish)

I'm not sure about A\*, maybe its also working for my task? can anyone help me to find a good algorithm for this task? I would prefer C++ as code.

# Answer
> 8 votes
A\* would work fine for this task, but since your map is small, Breadth First Search would work too, and it's even simpler than A\*. These are “graph search” algorithms, which require you to tell them what the allowed moves are. They are not limited to grids. In your case you would tell it that the allowed moves from (x,y) are to (x+1,y-1), (x+1,y), and (x+1,y+1).

As part of my A\* tutorial I have some C++ code for Breadth First Search and A\* that works for any graph. Look at the SquareGrid class; you will want to write your own `neighbors` function that looks at the three possible steps (straight, diagonal up, diagonal down) and checks that they're in the 7x7 map area, and that they're also not blocked by a wall.

# Answer
> 2 votes
A\* will certainly work for this.

Linked below is an excellent tutorial on how to implement it.

```
1) Add the starting square (or node) to the open list.

2) Repeat the following:

a) Look for the lowest F cost square on the open list. We refer to this as the current square.

b) Switch it to the closed list.

c) For each of the 8 squares adjacent to this current square …

If it is not walkable or if it is on the closed list, ignore it. Otherwise do the following.

If it isn’t on the open list, add it to the open list. Make the current square the parent of this square. Record the F, G, and H costs of the square.

If it is on the open list already, check to see if this path to that square is better, using G cost as the measure. A lower G cost means that this is a better path. If so, change the parent of the square to the current square, and recalculate the G and F scores of the square. If you are keeping your open list sorted by F score, you may need to resort the list to account for the change.

d) Stop when you:

Add the target square to the closed list, in which case the path has been found (see note below), or
Fail to find the target square, and the open list is empty. In this case, there is no path.
3) Save the path. Working backwards from the target square, go from each square to its parent square until you reach the starting square. That is your path.

```

Link

# Answer
> 0 votes
a\* will work fine. In the selection of neighbor cells consider forward, forward\_up, forward\_down

# Answer
> 0 votes
Well if you don't want to use A\* for some reason, try "Dijkstra’s algorithm" or "Greedy best first search".

---
Tags: c++, algorithm, path-finding
---


# Question
Title: How can I make a gameObject "stick" to another gameObject after it has collided with it?
How can I make a gameObject "stick" to another gameObject after it has collided with it? Right now the gameObject just passes through! \[C#\]

# Answer
In the future, you could have easily found this with a search. It has been asked many times before and is a pretty simple thing to do. You will usually not get many good answers (or any at all) if you dont search some first =-)

However, with that said:

IIRC, if both of your game objects have colliders attached to them and you catch that collision, you can use:

```
object1.transform.parent = object2.transform

```

Your collison code would look something like the following (I havent tested this and havent used unity in a while so it may be off a little)

```
void OnCollisionEnter(Collision collision) {
    collision.gameObject.transform.parent = gameObject.transform;
}

```

What the above does is takes the collided object and sets its transform to your current object. That way when your current object moves, the other one should follow along. You may get unexpected results if you have a rigid body attached to these objects too, but from what it sounds like, you dont
> 0 votes

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


# Question
Title: How can I implement screen transitions like in the 2D Zelda games?
I want to implement a screen transition in the style of the 2D Legend of Zelda games (like this). That is, I'd the screen to remain static until the player moves to an exit, at which point the next screen smoothly scrolls into view as the old screen scrolls out of view.

How can I accomplish this?

# Answer
> 3 votes
If you're using a tilemap, this transition is fairly easy to do. You will probably already have some sort of camera class. The thing is you only move the camera when the player reaches the edge.

Suppose your screen is 20 tiles wide and 10 high, the camera shows 0, 0 to 19,9. If the character reaches the border of tile 19-20 set the camera to a 'transition state' now move the camera while moving your character to tile 20. So increment camera x until it reaches 20 (the tile you character is). The camera should show 20,0 to 39,9. Return the game to the normal state and play resumes.

So no need to render the entire map, just control your camera movement.

Edited to reflect the comment made below.

# Answer
> 2 votes
First, your entire map needs to be loaded (all "rooms/zones") like a single image. Next, you have a viewport that displays the Zone your in, say 0,0 to 50,50. next, you set collision to if player collides with zoneWallRight start a render loop that will render the map scroll in that direction. (move the view port x,y)

at least, this is how I would do it. That way you could also do zoneWallDown or up.

---
Tags: xna, camera, monogame
---


title: 2D grid based game merging boxes

text:
# Question
Title: 2D grid based game merging boxes
Basically what i have at the moment is a tile based game with a grid containing a number of colored cells.

this is what i've done so far

---

The prinipal idea of the game is that the user has to connect all the shapes with the same color. but when two (or more) cells of the same color join they cannot be separated.

**for example:**

* the player cannot go from **image 1** to **image 2** because the blue cells are attached, it should become what is in **image 3**

i need help how to make the attached cells move as a unit not separately one by one (like in image 2 which is what i have right now).

each cell is a Cell object and they are held in an array like this:

```
private Cell[][] grid;

```

and this is the code i'm using to move the cells around.

```
public void move(int dx, int dy) {
  // if (dx == -1) ==> move left
  // if (dx == 1) ==> move right
  // if (dy == -1) ==> move down
  // if (dy == -1) ==> move up
    if (clickedCell == null) {
        return;
    }
    if (dx > 0) {
        if (clickedCol < numCols - 1) {
            Cell temp = grid[clickedRow][clickedCol];
            grid[clickedRow][clickedCol] = grid[clickedRow][clickedCol + 1];
            grid[clickedRow][clickedCol + 1] = temp;
            grid[clickedRow][clickedCol].setPosition(x + clickedCol * Cell.SIZE,
                    y + (numRows - clickedRow - 1) * Cell.SIZE);
            grid[clickedRow][clickedCol + 1].setPosition(x + (clickedCol + 1) * Cell.SIZE,
                    y + (numRows - clickedRow - 1) * Cell.SIZE);
            clickedCell = null;
        }
    } else if (dx < 0) {
        if (clickedCol > 0) {
            Cell temp = grid[clickedRow][clickedCol];
            grid[clickedRow][clickedCol] = grid[clickedRow][clickedCol - 1];
            grid[clickedRow][clickedCol - 1] = temp;
            grid[clickedRow][clickedCol].setPosition(x + clickedCol * Cell.SIZE,
                    y + (numRows - clickedRow - 1) * Cell.SIZE);
            grid[clickedRow][clickedCol - 1].setPosition(x + (clickedCol - 1) * Cell.SIZE,
                    y + (numRows - clickedRow - 1) * Cell.SIZE);
            clickedCell = null;
        }
    } else if (dy > 0) {
        if (clickedRow > 0) {
            Cell temp = grid[clickedRow][clickedCol];
            grid[clickedRow][clickedCol] = grid[clickedRow - 1][clickedCol];
            grid[clickedRow - 1][clickedCol] = temp;
            grid[clickedRow][clickedCol].setPosition(x + clickedCol * Cell.SIZE,
                    y + (numRows - clickedRow - 1) * Cell.SIZE);
            grid[clickedRow - 1][clickedCol].setPosition(x + clickedCol * Cell.SIZE,
                    y + (numRows - clickedRow - 0) * Cell.SIZE);
            clickedCell = null;
        }
    } else if (dy < 0) {
        if (clickedRow < numRows - 1) {
            Cell temp = grid[clickedRow][clickedCol];
            grid[clickedRow][clickedCol] = grid[clickedRow + 1][clickedCol];
            grid[clickedRow + 1][clickedCol] = temp;
            grid[clickedRow][clickedCol].setPosition(x + clickedCol * Cell.SIZE,
                    y + (numRows - clickedRow - 1) * Cell.SIZE);
            grid[clickedRow + 1][clickedCol].setPosition(x + clickedCol * Cell.SIZE,
                    y + (numRows - clickedRow - 2) * Cell.SIZE);
            clickedCell = null;
        }
    }
}

```

thanks in advance and by the way this game is built using LibGDX.

# Answer
> 0 votes
First, you need to find which blocks should move move, given a particular clicked cell. You'll probably want to use a floodfill algorithm of some sort for that. Once you have your list of tiles, move them all one after the other before doing anything else.

The way I would do that would be to change the move function so that it takes another parameter indicating which tile to move, instead of moving the clicked one then call the function on each of the tiles in the list.

```
List<Cell> movingCells = floodfill(clickedCell, /*maybe more parameters*/);
for(Cell cell : movingCells) {
  move(cell, dx, dy);
}

```

Also, you could move `Cell temp = grid[clickedRow][clickedCol];` out of all the inner `if` blocks and put it just above the large `if` block (the one with `if (dx > 0) {`) and save some code duplication.

---
Tags: 2d, libgdx, movement, tiles
---


# Question
Title: How to implement constant velocity and collisions without gravity
I am learning game development and i am trying to implement the AndEngineBox2D Extension such that my character is always moving at a constant velocity, when it collides with a body sprite, the character automatically changes direction (is deflected) and moves in the new direction until another collision has happened and the same is done repeatedly.

My Question: Is it possible to implement the changes in trajectory with AndEngineBox2D's physics world or i have to to handle it manually is java code.

# Answer
You will need to do it manually for best effect. Unless you want a less polished looking deflection.
> -1 votes

---
Tags: android, andengine
---


title: Are shaders always faster?

text:
# Question
Title: Are shaders always faster?
Will using shaders or some other way of talking directly to the GPU always be faster than drawing to the screen in whatever language a game is being (mainly) written in? I guess that code with lots of conditionals is slower on many, (most? all?) GPUs but is that the only heuristic that can be reasonably applied? I understand that there will be edge cases with different hardware and measuring is the only way to know for sure, but I'm trying to figure out whether I should do everything that looks feasible to do in a shader, in a shader, given I don't want to implement it twice to find out which is faster.

# Answer
> 1 votes
In the context of a highly parallelizable section of execution, like drawing pixels to the screen rendered from a some 3D/2D scene, GPUs are almost always likely to be faster because of their architecture. The decision, in a broad sense, for what programs will execute faster on a GPU vs. CPU should be thought of as how many different execution contexts can be run simultaneously without dependency, or basically how parallelizable is the program. In the general case, there definitely are other factors that make the decision more complicated, like branch divergence which you mentioned.

In the specific case of drawing pixels to the screen however, the decision in practice is very simple: GPUs will be faster at, just because it's a ton of tiny operations. You mention other methods of drawing things to the screen within a specific language as a comparison to work done on a GPU or in a shader. More than likely the language will make good use of the GPU when doing these drawing tasks, for example drawing simple shapes, or static images. All of those tasks are likely offloaded to the GPU to be executed quickly in parallel. If instead you mean drawing specific pixels from code executed on the CPU, then certainly you would be better off writing a shader that can execute those tasks in parallel.

---
Tags: shaders, performance, gpu
---


# Question
Title: Unity - Determine direction vector3 from a point in space and an angle in eulers
I have a ball positioned as Vector3(x, x, x).

I was able to get the direction of the ball to the mouse clicked position with:

Code (csharp):

```
Vector3 direction = Direction (clickPos2 - startPos);

```

Where the method is:

Code (csharp):

```
public Vector3 Direction(Vector3 position) {
        return new Vector3(position.x / Length(position.x, position.y), position.y / Length(position.x, position.y), position.z);
    }

```

Now I have an angle in eulers and I want that the ball goes to the direction of the angle.

But how I calculate it?

The game is played in 2d so actually only x and y is needed, z stays the same.

Mirza

# Answer
> 0 votes
if I understood :

"Now I have an angle in eulers and I want that the ball goes to the direction of the angle. But how I calculate it?"

You need :

```
dirx = cos(angle);
diry = sin(angle);

```

# Answer
> 0 votes
You don't need your `Direction()` function. It also doesn't return euler angles.

Unity's Vector3 class has all the functions you need.

See the code below.

```
Vector3 pos1; // start position
Vector3 pos2; // click position
Vector3 moveDistance = 3.0f; // move 3 units in the calculated direction

Vector3 delta = (pos2 - pos1); // delta is the vector difference between pos1 and pos2
float length = delta.magnitude; // distance in a straight line from pos1 to pos2
// direction is delta scaled to a normalized (unit) vector
// A unit vector has all components reduced so that it has a length of 1
Vector3 direction = delta.normalized;

direction.z = 0.0f; // don't move in z direction

// move the object from pos1 towards pos2 by the desired distance
pos1 += direction * moveDistance;

```

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


# Question
Title: How can determine the number of instances of an object in Game Maker?
I am making a small puzzle based game. I want the number of instances of an object to be equal to the ammo count plus 2.

Each time a new room is loaded, the main object's creation method with run this script:

```
var ammo = instance_count(jellyfish)+2;

```

Then each time a bullet is fired, I subtract one. When there is no ammo left, the player goes to the 'failure' room.

However, I get the error: `Unknown function or script: instance_count`.

I have see this script on Google, but am not sure if it has deprecated or not. Is there a way I can do this?

# Answer
The function you want is `instance_number(obj)` (documentation found here).

> This functions returns the number of instances of a object that exist in the current room.
> 5 votes

# Answer
if you used `instance_count` you could do

```
jellyfish.instance_count+2

```
> 0 votes

# Answer
You should use `instance_number(jellyfish)` instead of `instance_count`. `Instance_count` are ALL objects and `instance_number(obj)` is the count of A SPECIFIED object.
> 0 votes

# Answer
I think it is because there is no jellyfish instances in the failure room. What you can do (I don't think this works in gamemaker 8.1, you actually have to use the room number, which is an integer (1, 2, 3, etc.)), but assuming you are using gamemaker studio you should use this, where failureroom is the name of the failure room:

```
if room != failureroom
    {var ammo = instance_count(jellyfish)+2}

```

In this script the curly brackets are not necessary, but if you have more lines of code in the test like maybe you set the health as well, you have to use it.

Example:

```
if room != failureroom
    {var ammo = instance_count(jellyfish)+2
    var health = instance_count(jellyfish)+2}

```

If you do:

```
if room != failureroom
    var ammo = instance_count(jellyfish)+2
    var health = instance_count(jellyfish)+2

```

It will always change the health, even if you're in the failure room, but it will only change the ammo if youre not in the failure room.
> 0 votes

---
Tags: game-maker
---


title: AI Random Path Genenrating

text:
# Question
Title: AI Random Path Genenrating
I would like to make an enemy walk randomly around a map I have made and if the player is in his zone of sight the enemy to change state to attacking/following. So how would I accomplish something like this? Currently I have no idea how I would generate random paths with collision avoidance.

EDIT: I am making a 3D Game.

# Answer
Use waypoints in your map.

1. The enemy AI in "patrol" state chose a random visible waypoint as target.
2. Reached the waypoint repeat step 1. (eventualy excluding current waypoint)

If you don't want to place manualy waypoints you can generate them at the corners via script : here follow an example:

cons: the enemy will patrol in straight lines from waypoint to waypoint. pros: the patrol state grants walls collision avoidance
> 1 votes

# Answer
You may be interested in Nodal Pathfinding. The concept is similar to placing waypoints, except you generate these way points on top of your world. The waypoints are then used with an A\* pathfinder, to determine the optimal path.

Have a look at the blog here:

http://www.jgallant.com/nodal-pathfinding-in-unity-2d-with-a-in-non-grid-based-games/

Another option, is to use Navigation Meshes. Unfortunately, you cannot use the Unity NavMesh, as it does not work in 2d. You either have to buy one from the Asset store, or create one yourself.
> 1 votes

# Answer
Pick a random point on the map which is not blocked. Then Calculate a path from the current position to the destination using a stock route finding algorithm like Dijkstra's Algorithm or A\*. When no route can be found, then the random destination is either unreachable. Pick another point in that case.

To avoid a deadlock in case there is *no* possible move the actor can make, limit the maximum number of attempts to find a destination. When none is found, just let the actor stay where it is.

Every game logic frame, have the AI actor perform another step along the calculated path. When it reached the destination, pick a new random destination as explained above.
> 0 votes

---
Tags: unity, ai, path-finding, random, navmesh
---


# Question
Title: How to Slice the external Spritesheet programmatically by using C# in Unity
I have a sprite sheet like this:

I am using Unity Engine to develope my game. I would like to load this external spritesheet outside and slice it as Grid type programmatically instead of using Sprite Editor in Unity. I would like to find a way to do it by using C# scripting. Because my game would have more than 5 heroes with 10 animations per hero for next updates in my game.

# Answer
> 1 votes
You can do this if you use Sprite.Create

You would typically use this along with a Sprite Atlas, as setting the Rect properly without one would be pretty tedious.

---
Tags: c#, scripting, spritesheet, unity
---


# Question
Title: Creating a Static function inside my class to handle small housekeeping tasks
I have used Unity 3D for quite some time, and a lot of my game programming experience originates from using UnityEngine.

Writing in XNA, I am setting up a nested list of objects. Each object will be an instance of a class, GameObject. At the point of creation, I will have to perform some administration on each element, to sort through them and allow correct operation.

My understanding is that if I have the administration function inside the class, each instance will contain the instructions to perform the task, effectively having N times the same instructions. I have seen some functions instead use the static identifier, in UnityEngine. My understanding is that each instance will instead reference the **same copy** of the instructions, tidying everything up a bit better.

From what research I have done, all I can find supports that creating static functions inside instantiated instances of a class is impossible. However, I have functions inside UnityEngine that are static, and linked to instantiated copy's of a single class.

My question is: **How do I contain a static function inside my class**, to perform routine administration function? I am wanting it to be able to crunch numbers derived from the instance calling it, in order to set up other fields within the instance. **Would I have to send a ref type** of that field, to ensure I am editing the exact instance of it, **or do I have a keyword that automatically points to the instance calling the function?**

# Answer
> 10 votes
In C#, having an instance (non-static) method in a class does not copy the instructions for each object created from that class. Static or not, the data that represents the instructions only exist in one place.

The member variables, or state, of each of the instantiated objects do get their own space in memory. When you write a non-static method on a class, the compiler adds a first parameter to that method which is the location of memory where the specific instance's state is stored.

In general, but no where near always: If you need a method on a class to access the state of an object, make it a non-static method. If you need a method that does something without needing state, make it static.

---
Tags: c#, xna-4.0, component-based
---


title: A* Path Finding Loops Forever

text:
# Question
Title: A* Path Finding Loops Forever
For, hours, I've been following these instructions.

```
public PathFinder(IntegralLocation loc, final int dest_x, final int dest_y) {
    boolean found = false;
    final List<Node> open = new ArrayList<>();
    final List<Node> closed = new ArrayList<>();

    // 1. Add starting node to open list
    open.add(new Node(loc.getX(), loc.getY(), Math.sqrt(Math.pow(dest_x - loc.getX(), 2) + Math.pow(dest_y - loc.getY(), 2))));
    Node current = null;

    final int[] axs = new int[] { -1, 1 };
    final int[] ays = new int[] { -1, 1 };

    while(!open.isEmpty() && !found) {
        // 2a. Select current node
        for(Node n : open) {
            if(current == null) {
                current = n;
            } else {
                if(n.g < current.g) {
                    current = n;
                }
            }
        }

        // 2b. Switch it to the closed list
        open.remove(current);
        closed.add(current);

        // If this is the destination, we've found it
        if(current.x == dest_x && current.y == dest_y) {
            found = true;
        }

        // 2c. Handle surrounding squares
        for(final int ax : axs) {
            for(final int ay : ays) {
                final int x = current.x + ax;
                final int y = current.y + ay;
                if(!isNodeInList(x, y, closed)) {
                    Node n = getNodeFromList(x, y, open);
                    if(n == null) {
                        open.add(new Node(x, y, Math.sqrt(Math.pow(dest_x - x, 2) + Math.pow(dest_y - x, 2))));
                    } else {
                        if(n.g < current.g) {
                            n.setParent(current);
                        }
                    }
                }
            }
        }
    }

    canAccessDestination = found;
    System.out.println("This won't get printed.");

    // Save the actual path
    while (current != null) {
        nodes.add(new Point(current.x, current.y));
        current = current.getParent();
    }
    System.out.println(nodes.size());
    inverse_stage = nodes.size() - 1;
}

```

The code above is supposed to be an implementation of the A\* path finding algorithm but it's an infinite loop.

The loop always ends up stuck at `n.setParent(current)`.

It is assumed, in this implementation that all nodes can be walked over.

I am sure that there is a tiny error somewhere but I can't quite find it.

# Answer
Your algorithm only looks at the diagonals:

```
final int[] axs = new int[] { -1, 1 };
final int[] ays = new int[] { -1, 1 };
...
for(final int ax : axs) {
    for(final int ay : ays) {
        final int x = current.x + ax;
        final int y = current.y + ay;

```

You need to also check the orthogonal tiles: (x+0, y+1), (x+1, y+0), (x+0, y-1), (x-1, y+0).

In addition, the loop variable `current` isn't reset. It should be reset at the top of the main loop so that you always grab a new node from the open list each time. This should happen around your comment:

```
// 2a. Select current node

```
> 2 votes

---
Tags: java, path-finding, path
---


title: Getting the Volume of an Uneven Mesh

text:
# Question
Title: Getting the Volume of an Uneven Mesh
Let's say I have a cube, and that cube breaks apart into 100 different unevenly sized pieces.

How can I get the volume of each of those pieces compared to the cube's volume?

Using this in order to get the mass of each piece; for example, if the large cube is 100 mass, then the largest piece might be 30 and there might be some that are 0.2, etc...

Using C# and Unity with Rigidbodies

# Answer
From here, this can be used to calculate the volume of an arbitrary 3D mesh.

```
public float SignedVolumeOfTriangle(Vector3 p1, Vector3 p2, Vector3 p3)
 {
     float v321 = p3.x * p2.y * p1.z;
     float v231 = p2.x * p3.y * p1.z;
     float v312 = p3.x * p1.y * p2.z;
     float v132 = p1.x * p3.y * p2.z;
     float v213 = p2.x * p1.y * p3.z;
     float v123 = p1.x * p2.y * p3.z;
     return (1.0f / 6.0f) * (-v321 + v231 + v312 - v132 - v213 + v123);
 }

 public float VolumeOfMesh(Mesh mesh)
 {
     float volume = 0;
     Vector3[] vertices = mesh.vertices;
     int[] triangles = mesh.triangles;
     for (int i = 0; i < mesh.triangles.Length; i += 3)
     {
         Vector3 p1 = vertices[triangles[i + 0]];
         Vector3 p2 = vertices[triangles[i + 1]];
         Vector3 p3 = vertices[triangles[i + 2]];
         volume += SignedVolumeOfTriangle(p1, p2, p3);
     }
     return Mathf.Abs(volume);
 }

```

With `VolumeOfMesh` you can calculate the volume of each piece, and then sum them up to get the volume of the original shape.
> 2 votes

---
Tags: unity, c#, physics, rigid-body-dynamics
---


title: How to create rope?

text:
# Question
Title: How to create rope?
I'd like to re-create this game, but I have no idea how to create the rope, or its influences on the ball.

Basically, there is a rope, "attached", at one end, to the mouse pointer, and at the other end attached to a massive ball. As the user moves their mouse, the rope and ball follow, as if swinging a flail or such in real life.

How would I go about creating a rope as in the above game?

I need to know the basic concepts and physics behind the creation of such a rope, not how to use a pre-existing library to create one. I'd like to be able to implement a rope from scratch, so need to know how it can be done.

Thanks!

# Answer
> 3 votes
The rope in your example is probably just a simple physics-joint that limits the distance of the ball to the mouse-cursor. These joints are typically called "Rope joint" or "Spring joint".

It seems like the ripples in the string are not based on an actual physics-simulation. Most likely this is a bezier-curve where the control points get further pushed away from the central axis when the ball is closer to the mouse-position.

While the accepted answer explains how to create a realistic rope within the physics-engine, it's sometimes preferable to have a much simpler solution (as outlined above). The simpler solution (with just one joint) greatly improves the stability of the simulation. Multiple connected joints that have large forces applied tend to jitter and can result in broken and erratically moving chains of joints.

Of course you can also combine both methods, by creating your rope as such:

1. A chain of nodes, connected by joints
2. A rope/spring joint from the first to the last node of the chain that ensures that you can't pull the chain further apart than a given max-distance (one of the main reasons these chains become unstable).

This will result in a more realistically moving chain (that can even react to other objects in the physics-engine) but will require more processing-power than just a spring-joint with "fake" chain-behavior.

# Answer
> 11 votes
Basically, you'll need to create a physics engine. A rope is conceptually a bunch of "nodes" connected together with springs.

Basically, every tick, each nodes will exert a force on the nodes above and below it proportional to their distance apart (or how far from their comfortable stretch length they are). If you want to attach a ball, just connect it with a spring joint to the bottom node of the rope.

This is a great tutorial for creating a physics engine, but it doesn't really go into constraints or joints.

Here is a tutorial covering basic springs, which should be all you need for a rope like that.

This is a rope created in my (very basic) physics engine. It obviously has some quirks (the weird vibration) but it's generally what you're looking for. When you draw the rope, just don't draw the nodes.

**Edit:**

To make a good looking rope, a "string joint" is actually much nicer looking and closer to your example. A string joint is basically a spring, but it only corrects the objects when they are too far apart (not when they're too close).

This is my rope with a string joint instead:

---
Tags: physics, game-mechanics, rope-physics
---


title: What exactly are "tight controls"?

text:
# Question
Title: What exactly are "tight controls"?
I hear in many game reviews, how gamers complain about the controls of a game, when they hate it, or how they praise them when they work right. This expression comes up: "Tight controls".

It seems like when it comes to games, "controls" is a critic point for a game to succeed, so I was wondering if we could have a discussion about what **exactly** are *tight controls*.

* What makes "controls" feel good?
* What kind of things do gamers hate when it comes to "controls"?
* What examples could be given?

# Answer
> 5 votes
"Tight" controls are the opposite of "loose" controls. Generally speaking, these terms are used to indicate whether or not a control scheme responds quickly and appropriately to a player's actions. If the controls lag or otherwise cause slowdown and other undesired behavior, they're not tight. (Another term for "tight" would be "responsive").

For example, I played a PC game recently (not naming any names) where the mouse cursor did not immediately update onscreen as I moved the mouse, and on top of it the cursor was slow, with no option to speed it up anywhere in the game's options. This led to the cursor lazily "floating" around the screen about a half-second behind my actual movements, which was a royal pain when you're trying to click on moving objects with any kind of precision.

It's usually a sign of poorly optimized/programmed control routines, and definitely affects a game's playability.

# Answer
> 6 votes
There is no cut and dry definition for tight controls. So while sandalfoot's answer is not wrong, I would give it a different answer.

Tight controls mean less momentum affecting change. If a character is moving in one direction, turning them in another direction very rapidly would be tight controls. If you need more time to get them moving in the desired location, the controls would be looser.

Let's take FIFA for example. If you change directions 180 degrees, it takes time to stop and gain momentum in the other direction. If it was instantaneous, the controls would be too tight. If it took too long to turn around, the controls would be too loose. You can also turn in a semi circle to maintain your momentum, while taking longer to turn around. The momentum lost while turning this semi circle can be adjusted to change the tightness/looseness of the controls. Or for other games, such as Mario, how drastically you can change your direction while mid air reflects the tightness/looseness of the controls.

You do not want tight or loose controls - you want balanced controls. If they are too loose, and it takes too long to change direction, the game can feel unwieldy. If they are too tight, and you can immediately change directions, they can see unrealistic. You want to hit a middle ground.

# Answer
> -2 votes
After playing a lot of games you simply start preferring a certain type of controls for certain genres, it's a learned bias.

When someone makes a game with different controls it just feels like something is wrong.
It's not like players can't get used to it, it's just that it will bother them for a while.
This mistake often comes from people who are working on a genre that they aren't used to playing or it's just their first time making a game from that genre.

And I'd disagree that controls are a critical point for the game. Sure the reviewers might complain if you make a mistake with controls, but they will talk more about other aspects of your game.

---
Tags: control
---


title: A Star pathfinding on oblique map

text:
# Question
Title: A Star pathfinding on oblique map
I'm making an RPG and want to make npc ai to navigate the city. I am using polylines for collision detection, and my map is 2D, but oblique styled. I am considering using the A\* algorithm to help them navigate.

I've gotten the A\* algorithm to work with a top-down 2D array of nodes:

But am not sure how to go about implementing this in my game.

The overall world is 100x100 64x64px tiles, but the viewport (red box) only shows a small portion of them:

My questions are as follows:

* Do I make a 2D 100x100 array, each cell size 64x64 px to mimic the real map?
* How do I account for the polyline barriers/collision if 1's (unwalkable) and 0's (walkable) can only be assigned to a square cell?
* Performance: is it better to just created a pathing grid for the viewport, or always generate one for the entire 100x100 map?
* Barriers/Collision: I create my collision barriers directly in Tiled. Is there a way to programmatically insert `unwalkable` into the matrix for a given location of the barrier?

I am lost as to where to go next in translating this to my game.

Thanks!

# Answer
For the **A-star** algorithm you must provide a data structure that, for vey legal current position of the agent, provides the set of possible moves from that location along with the cost of making that location change.

The most common means of providing such a data structure, especially for a rectangular grid, is a 2D array of lists.

However for more complex graphs, such as road networks, a more complex data structure might be required.

The visual representation of your map is (or at least should be) completely separate from, and irrelevant to, the data structure presented to A-star.

For your example a 2D array (or list of lists) of nodes, each node having a list of the cost to move in each orthogonal and diagonal direction would be sufficient. You could for example choose to have the list of possible moves for each node be an ordered list of the legal moves, starting at North and stepping CW 45 degrees each time to NE, E, SE, S, SW, W, NW. A common choice in this case would be to use either a cost of 0 or -1 represent an illegal move, as no actual cost would ever be one of those values on a graph with an admissible heuristic.
> 2 votes

---
Tags: game-design, algorithm, path-finding
---


title: Camera controll in Libgdx

text:
# Question
Title: Camera controll in Libgdx
I've a condition in my game where, I want my camera to follow the Player(its a body from Box2d) and in some not.
This is the start screen of my game:

Now, when i press a button(space) the player get an LinearVelocity in x,y direction and starts flying..

As soon as it reaches the end. The box is now out of the camera.
To fix this I made my camera centered the box.

This is where I screwed. I dont want my ground to come in the center it should always needs to be at bottom.. like in Picture 1 and the player should also needs to be at the left-bottom at the start of the game. And when player flies away ... the x and y coordinates should be moved as my player moves ... i have certain height where player can fly so camera should be able to move in y-axis also.. and the game is endless running game so x- cordinates also keeps comming in.

# Answer
> 2 votes
When centering the camera using `lookAt` you need to clamp the `y` value to be the max of the body's `y` and the `y` of the ground plus half the viewport height (possibly adjusting for the height of the ground).

Something like this might make sense;

```
float x = body.getWorldCenter().x;
float y = Math.max(body.getWorldCenter().y, ground.getWorldCenter().y + camera.viewportHeight / 2.0f);

camera.lookAt(x, y, 0.0f);

```

(Note that I might have gottent some the api calls wrong, it's from memory)

# Answer
> 1 votes
I had this class in previous project

```
public class ExtendedCamera extends OrthographicCamera {
    public Player player;

    public ExtendedCamera(Player player) {
        super(Constants.WORLD_WIDTH, Constants.WORLD_HEIGHT);
        this.player = player;
    }

    public void followPlayer() {
        if (player.body.getPosition().x - position.x > Constants.CAMERA_FOLLOW_LINE_X) {
            position.x = player.body.getPosition().x
                    - Constants.CAMERA_FOLLOW_LINE_X;
            update();
        } else if (player.body.getPosition().x - position.x < -Constants.CAMERA_FOLLOW_LINE_X) {
            position.x = player.body.getPosition().x
                    + Constants.CAMERA_FOLLOW_LINE_X;
            update();
        }
        if (player.body.getPosition().y - position.y > Constants.CAMERA_FOLLOW_LINE_Y) {
            position.y = player.body.getPosition().y
                    - Constants.CAMERA_FOLLOW_LINE_Y;
            update();
        } else if (player.body.getPosition().y - position.y < -Constants.CAMERA_FOLLOW_LINE_Y) {
            position.y = player.body.getPosition().y
                    + Constants.CAMERA_FOLLOW_LINE_Y;
            update();
        }
    }
}

```

It's a bit verbose but it works. Just call `camera.followPlayer()` after updating player's position. Basically player has free movement zone and if he moves out this zone, camera follows him. Play with `CAMERA_FOLLOW_LINE` to achieve best result.

---
Tags: libgdx, box2d, camera
---


title: libGDX fileHandle cannot readString()

text:
# Question
Title: libGDX fileHandle cannot readString()
I have created a text file called "useraccounts.txt". All I want to do is to read the file using the filehandle class but I always get this exception:

```
Exception in thread "LWJGL Application" com.badlogic.gdx.utils.GdxRuntimeException: Cannot open a stream to a directory: useraccounts.txt (Local)

```

Here is my code:

```
FileHande accountsFile = Gdx.files.local("useraccounts.txt");
String text = accountsFile.readString();

```

Any explanation is appreciated!

# Answer
After much frustration, I found out that I had made a folder the same name with the text file by mistake!! After deleting the folder all works fine, thank you for replying!
> 1 votes

---
Tags: java, libgdx
---


# Question
Title: Predictive Collision Detection - Find Time Of Impact
I have a green box at a starting position A. It can move along two paths

* A to B is linear motion
* A to C is under the influence of gravity (non-linear)

The thin vertical line is a fixed colliding wall. All objects are represented with axis-aligned AABB bounding boxes.

For the path A to B, if my understanding is correct, ~~I (think I) can determine the time of impact (T0) on the wall based on swept-AABB collision techniques.~~ this case simply reduces to motion along x-axis, and time of impact can be calculated easily.

My question is for path A to C. Under the influence of gravity how can I determine the time of impact (T1) relative to the starting time T at location A. (The motion of A to C can be predicted using the standard equations of motion)

Are there any techniques/algorithms available for this?

**EDIT** To clarify the vertical wall is illustrative - walls can be arbitrarily **vertical** or **horizontal** or **both** (like a corner). They will be stationary, and axis aligned though.

# Answer
> 1 votes
Assuming A at position 0,0

free fall equations (with starting velocity on x (Vx) , and g=gravity constant ) are:

(1) `x=Vx * t`

(2) `y= (1/2)*g * t^2`

substitute t in second eq. you get

(3) `y= (1/2) * g * (x/Vx)^2`

where `g` and `Vx` are known.

This is a parabola equation :

Intersect (3) with each wall segment to get the eventualy collisions point cX,cY

If there are solutions For each collision points sobstitute (1) with cX to get time T. Choose the minimum T.

---
Tags: collision-detection, physics
---


# Question
Title: Problem with ID3D11DeviceContext::CopyResource method - How to properly read a texture CPU-side?
I am trying to make a full copy from a render target texture to a staging one but it seems my data length ends up being only 4 in length instead of 921600 (1280 * 720).

Here is my textures initializaion code :

```
// Setup the step count texture description.
D3D11_TEXTURE2D_DESC stepCountTextureDesc;
ZeroMemory(&stepCountTextureDesc, sizeof(stepCountTextureDesc));
stepCountTextureDesc.Width = g_clientWidth;
stepCountTextureDesc.Height = g_clientHeight;
stepCountTextureDesc.MipLevels = 1;
stepCountTextureDesc.ArraySize = 1;
stepCountTextureDesc.Format = DXGI_FORMAT_R32_UINT;
stepCountTextureDesc.SampleDesc.Count = 1;
stepCountTextureDesc.Usage = D3D11_USAGE_DEFAULT;
stepCountTextureDesc.BindFlags = D3D11_BIND_RENDER_TARGET;
stepCountTextureDesc.CPUAccessFlags = 0;
stepCountTextureDesc.MiscFlags = 0;

// Create the step count texture
hr = g_d3dDevice->CreateTexture2D(&stepCountTextureDesc, NULL, &g_StepCountTexture);
if (FAILED(hr)) return false;

// Setup the description of the render target views.
D3D11_RENDER_TARGET_VIEW_DESC stepCountRenderTargetViewDesc;
stepCountRenderTargetViewDesc.Format = stepCountTextureDesc.Format;
stepCountRenderTargetViewDesc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2D;
stepCountRenderTargetViewDesc.Texture2D.MipSlice = 0;

// Create the render target view.
hr = g_d3dDevice->CreateRenderTargetView(g_StepCountTexture, &stepCountRenderTargetViewDesc, &g_StepCountRenderTargetView);
if (FAILED(hr)) return false;

// Setup the step count staging texture description.
D3D11_TEXTURE2D_DESC stepCountStagingTextureDesc;
ZeroMemory(&stepCountStagingTextureDesc, sizeof(stepCountTextureDesc));
stepCountStagingTextureDesc.Width = g_clientWidth;
stepCountStagingTextureDesc.Height = g_clientHeight;
stepCountStagingTextureDesc.MipLevels = 1;
stepCountStagingTextureDesc.ArraySize = 1;
stepCountStagingTextureDesc.Format = DXGI_FORMAT_R32_UINT;
stepCountStagingTextureDesc.SampleDesc.Count = 1;
stepCountStagingTextureDesc.Usage = D3D11_USAGE_STAGING;
stepCountStagingTextureDesc.BindFlags = 0;
stepCountStagingTextureDesc.CPUAccessFlags = D3D11_CPU_ACCESS_READ;
stepCountStagingTextureDesc.MiscFlags = 0;

// Create the step count staging texture
hr = g_d3dDevice->CreateTexture2D(&stepCountStagingTextureDesc, NULL, &g_StepCountTextureStaging);
if (FAILED(hr)) return false;

```

Then the copy performed on each frame :

```
g_d3dDeviceContext->CopyResource(g_StepCountTextureStaging, g_StepCountTexture);
D3D11_MAPPED_SUBRESOURCE msr;
HRESULT hr = g_d3dDeviceContext->Map(g_StepCountTextureStaging, 0, D3D11_MAP_READ, 0, &msr);
if (FAILED(hr)) return;
g_StepCount = countSteps((BYTE*)msr.pData);
g_d3dDeviceContext->Unmap(g_StepCountTextureStaging, 0);

```

And the `countSteps` function :

```
unsigned int countSteps(BYTE* data) {
    return sizeof(data) / sizeof(data[0]); // -> 4 !?
}

```

The idea of the `countSteps` function is to iterate each texture pixel and add their unsigned int value together. The expected result would be above 1m, for now I get 17 sometimes 18 :)

How do I actually read my whole texture ?

# Answer
There's three members of a `D3D11_MAPPED_SUBRESOURCE`:

1. a pointer to the beginning of the data;
2. the number of bytes from the beginning of one row of data to the next row of data;
3. the number of bytes from the beginning of one depth slice of data to the next depth slice of data.

As none of these members communicate anything about the actual extents of a row of data, you need to query your texture resource for a DESC or remember the column and row counts from when you created it.

The 2D layout of the data is such that there are solid rows of data with the potential of padding at the end. The row pitch in the mapping indicate the offsets you need to use to jump between rows.

Assuming you know those quantities, you would iterate your mapped data similiar to this:

```
{
    uint32_t partialSum = 0u;
    // Point at the beginning of the first row
    BYTE const* rowPtr = msr.pData;
    for (size_t row = 0u; row < rows; ++row) {
        // Take the current row pointer and interpret as sequence of U32
        uint32_t const* p = reinterpret_cast<uint32_t const*>(rowPtr);
        for (size_t col = 0u; col < cols; ++col) {
            partialSum += *p;
            // Advance one U32
            ++p;
        }
        // Advance the row pointer to the beginning of the next row
        rowPtr += msr.RowPitch;
    }
}

```

The in-place reinterpret of the data is fine as feature levels 10\_0 and up guarantee 16-byte alignment of mappings, and feature levels below guarantee 4-byte alignment, which is enough for U32. If this would not be the case, a byte-wise copy would have to be made into a properly aligned value on the CPU side before touching it.
> 1 votes

---
Tags: c++, textures, directx11
---


title: Check if object is overlapping

text:
# Question
Title: Check if object is overlapping
I have two objects, both of them with polygon colliders. When I click on one of the objects, I want the player to drag it on top of the other object (without collision). If there is overlap when he drops the object, it snaps to the same position as the other object. Otherwise, it resets its position.

How do I: 1) make the colliders not prevent movement 2) make it so that it detects if they're overlapping when I let go 3) Make it snap to a very specific place depending on if they're overlapping or not

# Answer
Unity let you set a collider "as trigger". You can set the isTrigger property true on the collider of the object you start to drag. Then use Collider.OnTriggerEnter(Collider) to check if the objects overlaps some other collider. When you stop to drag an object can switch to false its collider.isTrigger.
> 1 votes

# Answer
Without more details I can't be certain if this is an acceptable solution but you might instead take the approach of scrapping the colliders completely and simply comparing the distance between the 2 objects `transform.position` on drop.

Alternatively, you may be able to use the information from the bounding boxes (available via the renderers) to work with the Physics library's casting capabilities. I'd look into `Physics2D.BoxCastAll`
> 0 votes

# Answer
i would, in order:

1. create an instance of the object you want to drag
2. set its collider to is trigger
3. change its rgba channel values to give it different color/transparency
4. on mouse button release check if overlap with OnTriggerEnter 4.b. you can optionally if objects overlap change color from blue to red, for instance
5. if they don't then move the original to the new position and destroy the dragging copy
> 0 votes

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


# Question
Title: A* Pathfinding math for 2D, oblique style game
I'm making a 2D, oblique-styled RPG game and am implementing A\* pathfinding for NPCs. The game is on canvas, using melonJS engine and sprites not confined to a 'grid'. I'm having a hard time converting my path (array of x,y coordinates) to my game world x,y coordinates for the sprite.

My game world is a 100 x 100 Tiled tilemap of 64x64px tiles.

I'm using Qiao's A\*, which has me create a grid of 0's (walkable) and 1's (unwalkable):

```
var matrix = [
    [0, 0, 0, 1, 0],
    [1, 0, 0, 0, 1],
    [0, 0, 1, 0, 0],
];
var grid = new PF.Grid(matrix);

```

Then create the path based on a starting position of 1, 2 (x,y) and ending position of 4, 2 (x,y):

```
var finder = new PF.AStarFinder();
var path = finder.findPath(1, 2, 4, 2, grid);

```

Which returns an array of coordinates:

`[ [ 1, 2 ], [ 1, 1 ], [ 2, 1 ], [ 3, 1 ], [ 3, 2 ], [ 4, 2 ] ]`

Obviously, since my game world consists of 100x100 64x64px tiles, the NPC's coordinates might be something like (1000, 1500). So my thought was to

* get the start world coordinates of the NPC (let's say 1000, 1500),
* divide by 64 to account for px width of grid,
* choose a end location (startX+500, startY+200), divide those by 64 too
* when the path is generated for the 100x100 grid, convert the paths back to world coordinates by multiplying each path coordinate x,y by 64

```
A_Star : function () {
    var api = {};

    api.init = function () {

        this.grids = this.createGrid();

        this.grid = new PF.Grid(this.grids[0]);

        var finder = new PF.AStarFinder();

        var converted_start_x = Math.floor(game.data.NPCX/64);
        var converted_start_y = Math.floor(game.data.NPCY/64);

        //arbitrary end location at x+500, y+200
        var converted_end_x = Math.floor(500/64);
        var converted_end_y = Math.floor(200/64);

        /*
            thePath returns array of x,y coordinates
            Passing in grid coordinates for x, y (so grid[1][2]... etc
            Need to translate the NPC's x,y world coordinates (2000, 1700) to grid coordinates

         */

        var thePath = finder.findPath(converted_start_x, converted_start_y, (converted_start_x+converted_end_y), (converted_start_y+converted_end_y), this.grid);

        /*
            Convert pathing back to actual world coordinates (*64)
         */

        for (var i = 0; i < thePath.length; i++) {
            thePath[i][0] = thePath[i][0] * 64;
            thePath[i][1] = thePath[i][1] * 64;
        }
        game.data.getPath = thePath;

        game.data.STARTPATH = true;
    };

```

**Create the grid:**

```
        api.createGrid = function () {
            var grid = [];
            var xLoc = 50;
            var yLoc = 50;

            for (var y = 0; y < 100; y++) {
                grid[y] = [];
                nodeGrid[y] = [];
                for (var x = 0; x < 100; x++) {
                    var type = 'walkable';
                    var val = 0;

                    //Set an arbitrary wall of unwalkable tiles in grid
                    if (x === 4 && (y === 3 || y === 4 || y === 5 || y === 6)) {
                        val = 1; //1 means unwalkable
                    }
                    grid[y][x] = val;
                    xLoc+=64;
                }
                xLoc = 50;
                yLoc += 64;
            }

            return [
                grid,
                nodeGrid
            ];
        };

```

**NPC update method:** Then, in my NPC class,

* set a counter to keep track of each path coordinate...
* once that path coordinate is reached by the NPC, increment `counter` so the player will start heading to the next path coordinate in the array

...

```
NPC class {
...
  update: function(delta) {
    var angle = 0;
    /*
        Keep loading next set of path coordinates to angle
     */
    if (game.data.STARTPATH) {
        if (this.counter < game.data.getPath.length) {
            angle = this.angleToPoint(new me.Vector2d(game.data.getPath[this.counter][0], game.data.getPath[this.counter][1]));
            if (this.pos.x <= game.data.getPath[this.counter][0] && this.pos.y <= game.data.getPath[this.counter][1]) {
                this.counter++;
            }
        } else {
            console.log('NPC has reached destination...');
        }
        this.body.vel.set(Math.cos(-angle) * .9, -Math.sin(-angle) * .9);

        this.body.update(delta);

        return (this._super(me.Entity, 'update', [delta]) || this.body.vel.x !== 0 || this.body.vel.y !== 0);
    }
},

```

**My questions:** The pathing seems quite wonky... so I'm obviously doing something wrong.

* Am I correct in dividing by 64px to convert to possible grid coordinates in the 100x100 matrix, getting path of coordinates, then multiplying back by 64px?
* What other recommendations would you have to convert path coordinates then set the path for the player?

# Answer
To make it easier for you to switch between world coordinates and grid coordinates, you should make two functions, *projectToWorld* and *projectToGrid*.

pseudo code:

```
/**
* returns the topleft position of a given grid coordinate.
*/
function projectToWorld(gridX, gridY) {
    return new Vector2(TILE_WIDTH * gridY, TILE_HEIGHT * gridY);
}

/**
* returns a grid coordinate by a given world position
*/
function projectToGrid(worldPosX, worldPosY) {
    int x = Math.Floor(worldPosX / TILE_WIDTH);
    int y = Math.Floor(worldPosY / TILE_HEIGHT);
    return new Vector2(x, y)
}

```

Now you can translate forth and back when generating the path, for example:

pseudo code:

```
var endPos = new Vector2(1440, 2020); // world end position to walk to
Vector2 endPosGrid = projectToGrid(endPos.X, endPos.Y);
Vector2 startPosGrid = projectToGrid(NPC.Pos.X, NPC.Pos.Y);

List<Vector2> nodes = finder.findPath(
    startPosGrid.x, startPosGrid.y, endPosGrid.x, endPosGrid.y, grid
);

// since we floored values, the projection gives us a corner but we want the npc to walk to the center :
float offsetX = TILE_WIDTH / 2f;
float offsetY = TILE_HEIGHT / 2f;

foreach(Vector2 node in nodes) {
    Vector2 worldPos = projectToWorld(node.x, node.y);
    NPC.WalkToPos(worldPos.x + offsetX, worldPos.y + offsetY);
}

```

Additional info: this is pseudo code (actually a mix of at least three different languages)
> 1 votes

---
Tags: game-design, javascript, algorithm, path-finding
---


title: Unity Button Without an Image?

text:
# Question
Title: Unity Button Without an Image?
I want to create a button whose clickable area is only specified by a BoxCollider with Unity's new UI (similar to how you would do it from within NGUI). I can't get a Unity Button to work without the presence of an Image component (which ultimately represents the clickable area of the button).

# Answer
> 1 votes
There are two options for you.

1) Keep the image component on the button with a sprite, then set the transparency/alpha on the color to 0.

2) Write a separate script that you attach to a gameobject (Or image/button) that implements the Unity event interface: IPointerClickHandler and inherits from UIBehaviour. IPointerClickHandler is the interface Buttons use to register a mouse click.

# Answer
> -1 votes
If I'm reading this correctly, I think all you need to do is remove the Sprite Renderer component(s) from the GameObject in question. Or -- what if you had a Sprite whose Alpha value was 0? Would that work?

---
Tags: unity, ngui, gui
---


title: three.js objects disappear

text:
# Question
Title: three.js objects disappear
I haven't got a lot of experience with 3D Frameworks - but was playing around with three.js and came across something that (to me) is a bit odd and I wondered why this happened. I am rendering the number "1" on screen with the following code.

```
shapes = THREE.FontUtils.generateShapes("1", {
    font: "helvetiker",
    weight: "normal",
    size: 0.25
});

geom = new THREE.ShapeGeometry(shapes);
mat = new THREE.MeshBasicMaterial();
mesh = new THREE.Mesh(geom, mat);
mesh.position.set(1.5, +2.5, 0);
scene.add(mesh);

```

Now I also implemented camera movement, so I can rotate and move along the z/x/y axis. When I move the camera past the number "1", and turn the camera 180° around - the number is gone. So the camera is behind it but I did change the point the camera is facing - yet the object is gone.

\[Well, if I put the camera sideways and slide past it, it also stops rendering. So I'm 100% sure it's not rendered\].

I was wondering two things. 1) Is this the normal approach in 3D? To not render things that lie behind you on the Z-axis (even though the camera is turned.) 2) I'm assuming it's not the standard, as it surely isn't the expected behaviour. So how would I, in Three.JS, have the object rendered when the camera faces it, even though the camera is behind it.

Just an explanation would already be a huge help, but if you can provide a code snippet it would be even better. Thanks!

# Answer
> 2 votes
I solved it!

A friend of mine told me it's pretty standard if the material is not set to doublesided. (Or I could make a billboard out of it). But in code I had to add

```
 mat.side = Three.DoubleSide;

```

Sorry guys for bothering you with this - it was probably quite basic but I'll leave it on just in case someone else encounters this problem!

---
Tags: 3d, javascript, three.js
---