# Question
Title: Unity 2D - Object following target instead of moving towards it
I'm making a 2D game with Unity that's based on avoiding/evading enemies. The problem i'm facing right now is i can't get the enemies to move towards the target/player, but instead they follow it. So they never actually "attack" because they only follow it around and don't even come close to it. Also if the target/player stops moving, they stop moving.

I'm wondering if it could be something in my scene, since i've asked this question on multiple forum threads in the unity forums section and everyone seems to answer with the same lines of code.

Extra information:

My enemy has a box collider on it with no rigidbody 2D. My player has a box collider on it with a rigidbody 2D.

Kind regards.

```
using UnityEngine;
using System.Collections;

public class BeeBehaviour : MonoBehaviour {

  public Transform target;
  public float moveSpeed = 3;

  void Start () {
    target = GameObject.Find("MainObject").transform;
  }

  void Update () {
    Chase();
  }

  void Chase () {
        Vector3 targetDirection = target.position - transform.position;
        transform.position += targetDirection * moveSpeed * Time.deltaTime;
  }
}

```

# Answer
> 2 votes
You have:

```
void Chase () {
    Vector3 targetDirection = target.position - transform.position;
    transform.position += targetDirection * moveSpeed * Time.deltaTime;
}

```

One problem is that your `targetDirection` is not normalized but rather has magnitude equal to the distance between the objects. By multiplying this unnormalized vector to determine the frame's movement you are producing movement that proportional to the distance between objects i.e. the following GameObject will slow down as it get closer and depending on the value of `moveSpeed` may never reach the target.

You could fix this with:

```
void Chase () {
    Vector3 vectorToTarget = target.position - transform.position;
    transform.position += vectorToTarget.normalized * moveSpeed * Time.deltaTime;
}

```

This still leaves the problem of overshooting if the frame's movement is greater than our distance from the target. For this we can check the distance to the target and if it is less than the usual movement for that frame set the our position equal to the target.

```
void Chase () {
    Vector3 vectorToTarget = target.position - transform.position;
    float moveDistance = moveSpeed * Time.deltaTime;
    if (vectorToTarget.magnitude > moveDistance ) {
        transform.position += vectorToTarget.normalized * moveDistance;
    }
    else {
        transform.position = target.position;
    }
}

```

However stepping the values of a vector towards another is a common problem and unity has provided a convenience method `Vector3.MoveTowards()` to help us with the heavy lifting:

```
 void Chase () {
    float movementDistance = moveSpeed * Time.deltaTime;
    transform.position = Vector3.MoveTowards(transform.position, target.position, movementDistance);
}

```

# Answer
> 0 votes
I use this simple script I whipped up to get mobs to follow on the X axis (but you could easily add a couple of lines to include Y axis as well because it already calculates that distance I just don't use it because I'm building a side scroller) I just created these functions in a MobAIMovement script and then called TotDistance from the Update function.

```
void TotDistance (){
    var testX = transform.position.x;
    var testY = transform.position.y;

    var pTestX = target.transform.position.x;
    var pTestY = target.transform.position.y;

    var xDistance = testX - pTestX;
    var yDistance = testY - pTestY;

    var totDistance = Mathf.Pow (xDistance, 2) + Mathf.Pow (yDistance, 2);
    totDistance = Mathf.Sqrt (totDistance);

    Debug.Log ("Total Distance: " + totDistance);

    FacePlayer (xDistance, totDistance);

}

void FacePlayer(float xDistunce, float tutDistunce){
    if (xDistunce < -0.5) {
        transform.localScale = new Vector3(-1, 1, 1);
        if (tutDistunce > mobRange){
            transform.Translate(1 * Time.deltaTime, 0, 0, Space.World);
            anim.SetBool ("isMoving",true);
        }
        else{
            anim.SetBool ("isMoving",false);
        }

    }
    if (xDistunce > 0.5) {
        transform.localScale = new Vector3(1, 1, 1);
        if(tutDistunce > mobRange){
            transform.Translate(-1 * Time.deltaTime, 0, 0, Space.World);
            anim.SetBool ("isMoving",true);
        }
        else{
            anim.SetBool("isMoving",false);
        }
    }
}

```

Very simple. It basically follows it on X, but stops once it is within range.(easily changed or removed.) It also flips the sprite to face and move left or right. The "isMoving" bool is just there to trigger the moving animation state and can be removed as well.

If I were you, I would change the (1 * Time.deltatime to 1 * mSpeed * Time.deltatime) and then set an mSpeed variable for the mob. That way if it isn't catching you, then you can speed up the mob by changing that variable.

If you want death to come from contact use OnCollisionEnter2D(collision2D coll) to detect collisions with player and destroy. If you want attack, then modify the script a bit. In the section where it stops within range you can change it to attack when it's within a totDistance instead of stop completely (which is all mine does at this second.)

One more thing, I'm pretty sure transform.forward won't work they you want in the 2D engine. You'll need transform.up or transform.right etc.

I'm no professional and still new to this all myself. Maybe this will help out. (I know my programming is probably archaic and not very efficient. Just figuring it out as I go along.)

---
Tags: unity, ai
---


# Question
Title: (Unity) Physics based movement vs Straight position change
Unity provides a cool physics engine for game development and I want to utilize it in my game.

**Shorter version**

I want to use physics engine for everything else other than character movement because trying to use physics engine for player movement doesn't yield the perfectmovement speed that I want; move x units per second.

If I use physics engine for character movement, it gets complicated. I would rather just add "moved distance" to the position to have things done simple. Is doing something like this wrong? All the learning sources I read recommend to use physics engine for movement if the game incorporates physics engine. I am nervous; am I wrong?

**Longer version**

The following description is where I use "physics", why I need physics engine.

In my game a player fires a bullet. When enemies collide with bullet, they get pushed back slightly. A strong blast can push enemies far back so that they even bounce back from hitting wall.

A recommend, a proper way, I was told, to utilize this physics engine for character movement is to add force to the direction I want to move.

But doing so(adding force to the direction I want to move) will result in truck-like; slowly warming up by adding velocity. To avoid "truck like movement" I was told to apply greater force at the beginning. Doing so result in change in velocity like the below picture.

However problem is not over yet, you must consider a situation where you change direction of movement while the character is running.

If you started to move backward, all of the sudden while running forward, you will need to slow down forward movement **burn velocity** by adding backward force. Thus rotation burns velocity.

So a solution is to find out perpendicular velocity to your desired direction, then find out needed amount of force to "burn off" the undesired velocity.

This seems way too complicated for a character to simply move around. I would rather just move character to desired direction by simply adding "constant X distance" to the character's position.

But I can't find a source of example where it utilizes both "simple movement by directly adding moved distance to the position" and "using physics engine for the game". All the sources of learning(using Unity physics) I find say use this complicated way of having character to move around. I wonder is there a reason why people don't just add moved distance to the position?

# Answer
> 1 votes
AFAIK the standard way of doing things in Unity is to assign a (non physical) Character Controller to your player. The character controller just sets the velocity of a body with some simple rules (exactly as you want). Collisions with physical objects are faked by treating the character as a kinematic object that can't be affected by forces.

This can lead to some undesirable results, such as non-physical interactions between your player and physics objects. For instance, if your player is colliding with a dynamic physical object wedged in a static door, the fact that the player doesn't obey Newton's third law means that the dynamic object will get pushed into the static objects, resulting in physics glitches like teleports or very large forces.

To avoid things like this, you can force the character to maintain Newton's laws and behave as a dynamic object, but, as you say, it makes the character much more difficult to control.

# Answer
> 0 votes
I'm not entirely certain this will help with your physics problem, but I remember reading about two different types of force options when you use AddForce. One adds a ramping force and the other is an instantaneous impulse force. Might be worth reading into. :)

---
Tags: unity, physics, movement
---


# Question
Title: Jumping higher when the player touches a trigger collider in Unity
Im using Unity engine to create a 2D platformer. My character can single/double jump, this works fine everywhere except when i am in range of a collider with a IsTrigger set to TRUE, then my character can triple jump if jump is pressed repeatedly. This can used as an exploit in my game when collecting pickups :( How can i stop this from happening? Please assist

```
void FixedUpdate()
    {
        // This is the Jump code
        grounded = Physics2D.OverlapCircle (groundCheck.position, groundRadius, whatIsGround);
        anim.SetBool ("Ground", grounded);
        anim.SetFloat ("vSpeed", rigidbody2D.velocity.y);

        if (grounded)
        {
            doubleJump = false;
        }

void Update()
    { //This is pressed to get the player to jump
        if((grounded || !doubleJump) && (Input.GetKeyDown (KeyCode.Space) || didPlayerJump || wasEnemyStomped == true))
        {
            JumpAction(); // rigidbody2D.AddForce(new Vector2(0,jumpForce)) triggered in this function
            if(!grounded && !doubleJump)
            {
                doubleJump = true;
            }

```

# Answer
> 1 votes
I had this same problem for a while. I was able to actually jump forever when I attacked. It turns out the problem was with the "whatIsGround" layer. Make sure everything is layered and the things you don't want to restart the jumpprocess are not checked in that mask layer. It solved my problem and might solve yours.

# Answer
> 0 votes
I dont know what you are quite trying to do when the `collider with a IsTrigger` is true. But if you want to limit the character's jumps to a number, instead of using boolean, why not use an int to represent the number of jumps the character has left?

For example: On jump:

```
if (jumpsLeft >0){
    jumpsLeft -= 1;
    jump();
}

```

On hitting ground again:

```
jumpsLeft = 2;

```

# Answer
> 0 votes
The code looks sound but the effect you're describing could indicate that the item collection is on the same layer as the ground - thus calling that same code and resetting `grounded` and `doubleJump` on contact. I'd put them on their own `Collectible` layer.

---
Tags: c#, unity, platformer, rigid-body-dynamics, jumping
---


# Question
Title: The Validity Of "Else-IF" in Unity (Or any C# for that matter)
While I'm speaking specifically for my use in Unity, I'm sure this question probably applies to C# in general. I've seen a lot of debate on the use of the "else if" statement. Particularly, I'm testing for input in my update. Is it more efficient to have

if (input blah blah)

If (input other blah)

if (input more blah)

OR

if (input blah)

else if (input more blah)

else if (input other blah)

Personally, I don't really understand the difference between if and else if though I've read about it many different times and in different languages. So I'm asking just from your personal experiences and not what you've read on the internet. Do you have a preference? Does it even matter?

Update: Thanks for the answers. Actually does make more sense now. I don't know why I wasn't seeing it that way. Sorry for the off topic thing. (Can't upvote as of now because reputation)

# Answer
> 1 votes
To better understand `else if`, consider the following **code A**:

```
if (condition_1)
{
    DoA();
}
else if (condition_2)
{
    DoB();
}

```

The above code is exactly the same as **code B**

```
if (condition_1)
{
    DoA();
}
else
{
    if (condition_2)
    {
        DoB();
    }
}

```

Compare this to **code C**:

```
if (condition_1)
{
    DoA();
}
if (condition_2)
{
    DoB();
}

```

In code A and B, if `condition_1` is true, `DoB()` will never run, regardless of whether `condition_2` is true or not. In code C, `condition_2` will be evaluated regardless of whether `condition_1` is true or not.

General programming questions are more suited for Stack Overflow though...

# Answer
> 1 votes
I'm not sure what debate you are speaking of, but else if is a required construct in most programming languages, including C#. How else do I express the following?

```
if ( i == 0 )
{
   DoPrimaryAction();
}
else if ( i < 2 )
{
   DoSecondaryAction();
}
else if ( i < 4 )
{
   DoTertiaryAction();
}

```

if it were rewritten as

```
if ( i == 0 )
{
   DoPrimaryAction();
}
if ( i < 2 )
{
   DoSecondaryAction();
}
if ( i < 4 )
{
   DoTertiaryAction();
}

```

Then PrimaryAction(), SecondaryAction() and TertiaryAction() would be called whenever i is zero.

You might rewrite it as a function:

```
void Action::DoAction( int i )
{
    if ( i == 0 )
    {
       DoPrimaryAction();
       return;
    }
    if ( i < 2 )
    {
        DoSecondaryAction();
        return;
    }
    if ( i < 4 )
    {
        DoTertiaryAction();
        return;
    }
}

```

Where each if case returns to prevent the following case from being called. While this is done often it is cumbersome to require it.

You could use switch statements, but those don't work if unrelated conditional cases.

Can you cite what debate you are talking about?

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


# Question
Title: Update animation based on distance traveled instead of elapsed time?
2D sprite Animation is supposed to be based on the elapsed time from the previous update so that it runs (and looks the same) no matter the speed of the machine/device it's running on.

The method that moves my game objects already takes into account the elapsed time. The distance the object moves during updates is the elapsed time (delta) * the objects velocity.

Because the object's location changes based on the elapsed time, would it look (/run the same on all machines) passing the "*distance* delta" to my Animation update method instead of the delta time? The distance delta would be a number of pixels. Using the distance would ensure my frame animation lines up with how far the object has traveled.

# Answer
> 1 votes
Yeah that would work. Commonly when a game wants to have the animation and location synchronized like this, they will have a fixed time delta that is passed to both their simulation (what moves the object) as well as the animation system. Your idea would also work though (:

---
Tags: animation, sprites
---


# Question
Title: How to figure out if I'm on the right path
I'm a software developer from Israel, I've been programming professionally since 2011, my first job was in HP software and lasted 2 years after which I decided that I want to pursue my dream in working in game development and focusing on C++. for a year an a half I worked for a mobile kids games company, doing small mobile games for kids using C++ and Cocos2d-x. Unfortunately I was laid off last December and since then I've been focusing my free time on studying Unreal engine 4, studying openGL and computer graphics and working on my C++ skills while searching for a new job.

I'm very passionate about computer & console games and especially the rendering part and my dream job would be to work on AAA games and to be a graphics programming specialist. The problem is that there aren't any AAA game companies in Israel so I started looking at positions in Europe and also in other jobs that involves computer graphics but aren't necessarily in games.

Last week I got a job offer for a small start up making a game in the "Clash of Clans" genre, the company seems nice, its not my type of games but I'm sure it presents all kinds of challenge but my biggest concern is the fact that the game is implemented in Unity and Python, which are two technologies I'm not so crazy about.

I wonder if I should take the job or keep looking for something that involves more C++,OpenGL,DirectX etc. Do you think that taking a Unity\Python job will take me too far from the OpenGL\DirectX goal I'm trying to reach?

I know that good software developers aren't supposed to limit themselves to a certain programming language but I think its good to become really professional at something specific instead of changing language every 2 years. I guess its being a specialist vs. a generalist question.

What do you guys think? should I take this job even though I have some concerns? should I keep searching? maybe doing some freelance work in the meantime?

any advice will be appreciated.

# Answer
> 0 votes
My take on this is that if you can find a job closer to where you want to be than where you currently are, you should take it. Since you currently are not employed and this offer is for a game development position I'd say go for it. Being employed as a game programmer, even if its for the "wrong technologies" makes you a lot more hireable by the places you would like to work for, versus a hobbyist game Dev who has no job. If you take this job, keep honing the skills you want to grow (in your spare time if needed) and feel free to keep searching for other jobs and if a better one comes along, take your step up. Of course, try your best to be respectful to the folks who have given you a chance at their company and don't leave at a critical time if you can help it. I'm a self taught game programmer who is technically a high school drop out, but am now an engine programmer at Blizzard working on StarCraft 2 and heroes of the storm. Took about 14 years of hard work, and I had to start off in business software, but using the above advice I crawled my way up to a respectable position (: most importantly though, learn everything you can about everything you can. You need to improve your skills constantly to be able to take those steps up. It sounds like you are on the right track though if you keel it up!

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


title: Strategy game tile and unit storage

text:
# Question
Title: Strategy game tile and unit storage
I've recently started working on a turn based strategy game much like games from the Fire Emblem or Final Fantasy Tactics series. However, I'm running into a few problems concerning the storage of the tile data and unit data. For example, just like in Fire Emblem I want to show all possible movement when you click on one of the units. Here is an image showing what I mean.

In this image the possible fields to move to have been indicated with a blue color. Fields that are in range for an attack have been indicated with the red color. Normally the tile the enemy unit is on would be in range to move to, however since there is someone standing on the tile the game has recognized that you can't move there.

I understand the need for an algorithm like Breadth-First Traversal to find out all possible fields to move to, but I'm unsure how to exclude fields occupied by an enemy. In order to avoid circular dependencies between fields and units I only store a reference to field in the unit class and not the other way around. So when I work my way through the fields to check all possible moves, how do I best find out if that field is actually valid?

I could of course just loop through the list of all enemies for each field that I process to see if it's occupied. Another way to potentially solve it would be to loop through the list of possible fields and removing fields occupied by enemies from that list, but I think that wouldn't work properly because occupied fields can also have the effect that empty fields around them are no longer reachable (due to the enemy blocking access to them). The easiest way to solve it would be to also store a reference to the unit within the field class. This would of course introduce a circular dependency.

I feel like there should be a much better solution than the ones I can think of, but I just can't figure it out.

Thanks in advance!

# Answer
> 2 votes
It sounds like you already have a walk-map which says which tiles are walkable and which are non-walkable based on the terrain: the static walkmap.

What you need is a second walkmap which tells you which tiles are non-walkable because of object presence: the dynamic walkmap. This map only needs to be recalculated when there is a change, so you can keep it in memory and only need to update it when an object changes its position, is removed or added.

When you calculate paths, check both the static and the dynamic walkmap to determine if a field is walkable.

In a real-time game with lots of actors it would be faster to have the dynamic walkmap keep count of all effects which affect a tile, so when an object moves you remove its old effect and add the new one. This is a cheap constant-time operation for every position change. (it might also make the static walkmap redundant, because any blocking tiles can be represented by an effect on the dynamic map which is added once but never removed).

But because your game is turn-based, performance is not of such a great concern. A small hickup after a unit makes a move would likely not be noticed by the player. And even when it is noticeable, it might in fact add to the suspense. So I would go for a much simpler solution which has linear time complexity but is easier to implement and less error-prone: When an object makes a move, just throw the old dynamic walkmap away and recalculate it from scratch by iterating all objects and mark the fields they occupy as blocked.

When you have a game with two (or more) factions, then you might have a rule that units block tiles only for the enemy faction(s). You might also have units which are bound to different move rules (for example, a flying unit can move through fields occupied by enemy units, unless they are also flying). That means you should not just store *if* but *how* a tile is blocked - whether it's blocked for faction A, faction B or both. You could do this by either calculating a separate walkmap for each faction and each movement mode, or by having the walkmap store a bitset for each tile where each bit says for which faction it is blocked.

# Answer
> 1 votes
First go though your list of obstacles an compile a list of fields that are currently unavailable for movement. This list could contain field IDs or grid references or some other way to identify a field that works for your data structures.

Next perform your Breadth-First Traversal and for each field perform a check to see if it is on the list of fields that contain obstacles.

Creating this list will be a low complexity task so it shouldn't matter if it is recreated between each turn.

# Answer
> 0 votes
If you want to store a reference from the tile to the unit(s) occupying it, then just do it. As long as you remember to remove the reference whenever a unit leaves a tile (as you should do anyway, to mark the tile as unoccupied), the circular references will not affect the garbage collection of destroyed units in any way.

The one situations where circular references *might* be a problem is when you discard the whole level, with its tiles and units and all. In that case, if you don't first unlink the references by hand, the garbage collector may have to work a bit harder to determine which tiles and units are no longer reachable. However, most modern languages (including e.g. Java, JavaScript and C#) feature tracing garbage collectors that can do this, even in the presence of circular references.

---

If you wish to make the garbage collector's job easier, one alternative to manually breaking the references would be to use weak references, which most modern languages also support. These don't contribute to the (strong) reference count of the referenced object, and thus allow it to be garbage collected as soon as there are no more strong references to it. (However, there's no *guarantee* that an only weakly referenced object will be garbage collected immediately, so you should not rely on it; in particular, you'll still need to manually mark tiles as vacant when a unit is moved or destroyed.)

---

Finally, if your units have unique IDs (and you have some way to efficiently look up a unit by ID), you can simply store the unit ID instead of a reference to the unit. In fact, such "symbolic references" are often a more natural choice for game world models than hard references anyway, since they decouple the existence of game objects from the existence of references to them. After all, in the real world, an object does not disappear simply because everyone forgets about it, nor does a destroyed object linger as some sort of a ghost just because somebody *believes* it's still there.

(Of course, if you *do* want to sometimes keep references to units or other game objects that may not actually exist in the world any more (or do not yet exist), then in such cases, hard references may indeed be appropriate.)

Or you could just do as Philipp suggests, and not store actual unit IDs on the map, but simply some flag indicating that this tile is occupied by a unit (of faction *X*). This may well be enough for your pathfinding purposes.

---
Tags: movement, turn-based-strategy, tiles
---


# Question
Title: Unity 5: Error when everything is okay(Object reference not set to an instance of an object)
i'm getting this error when the collider colides with something:

Object reference not set to an instance of an object

It's referencing to the gamecont.Death(); from this script:

and the death method is on this one:

# Answer
I changed:

gameCont = GetComponent();

to:

gameCont = GameObject.FindObjectOfType();

and worked!
> 1 votes

# Answer
If gamecont is null, then probably the assignment from GetComponent failed which means either the component is not attached to the same GameObject as the one using the ObstacleMove script, or that the instance of GameController is disabled (see the component's check box).
> 0 votes

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


# Question
Title: Creating polygons with separate outline/fill colors in OpenGL
## Subject

I am creating a terrain map with triangle strips and I would like to make the bodies of the triangles black, but have their outlines be colored.

---

## Problem

The solution appears to be to draw the triangles twice, once in solid black, using `GL_FILL` and once in color using `GL_LINE`.

The problem with this approach is that, since I am using depth testing and the vertices are at the same position each time, my color lines end up blending with the black lines

---

## Attempted Solution

According to the OpenGL docs, and other sources, it looks like I should be able to utilize the glPolygonOffset() function to give polygons that are drawn with `GL_LINE` "precedence" in the depth buffer by offsetting their comparison value by the argument to the function. (so I would think 1.0 would be sufficient)

This, however, does not appear to be working for me.

---

## My Code

I have placed `glEnable(GL_POLYGON_OFFSET_LINE);` in my init function.

Here is the code in my draw loop where I do the actual rendering. `col` is the array that hods the real colors, `col2` is filled with black.

Please excuse the mess.

```
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

glPolygonOffset(1.0,0.0);

glDeleteBuffers(1,&vertex_buffer);
vertex_buffer = createBuffer(GL_ARRAY_BUFFER, vert, sizeof(GLfloat)*(buffer_size), GL_STATIC_DRAW);
attributeBind(vertex_buffer, 0, 3);

glDeleteBuffers(1,&color_buffer);
color_buffer = createBuffer(GL_ARRAY_BUFFER, col2, sizeof(GLfloat)*(buffer_size), GL_STATIC_DRAW);
attributeBind(color_buffer, 1, 3);

glPolygonMode(GL_FRONT_AND_BACK,GL_FILL);
glDrawArrays(GL_TRIANGLE_STRIP,0,s);

glDeleteBuffers(1,&color_buffer);
color_buffer = createBuffer(GL_ARRAY_BUFFER, col, sizeof(GLfloat)*(buffer_size), GL_STATIC_DRAW);
attributeBind(color_buffer, 1, 3);

glPolygonMode(GL_FRONT_AND_BACK,GL_LINE);
glDrawArrays(GL_TRIANGLE_STRIP,0,s);

```

I'm not sure if I need to call `glPolygonOffset()` each frame or not.

These are the `attributeBind()` and `createbuffer()` functions:

```
void attributeBind(GLuint buffer, int index, int points)
{
    glBindBuffer(GL_ARRAY_BUFFER, buffer);
    glVertexAttribPointer(
        index,              // position or color
        points,             // how many dimensions?
        GL_FLOAT,           // type
        GL_FALSE,           // normalized?
        0,                  // stride
        (void*)0            // array buffer offset
    );
}

GLuint createBuffer(GLenum target, const void *buffer_data, GLsizei buffer_size, GLenum usageHint)
{
    GLuint buffer;
    glGenBuffers(1, &buffer);
    glBindBuffer(target, buffer);
    glBufferData(target, buffer_size, buffer_data, usageHint);
    return buffer;
}

```

# Answer
**Edit:**
We tried many combinations of the following and got many, many, equally-disappointing results. OP has resigned to using his backup plan of physically moving the geometry slightly toward the camera before drawing it as wireframe. Link to chat.

> A typical use might be to set factor and units to 1.0 to offset primitives into positive Z (into the screen) and enable polygon offset for **fill mode**. Two passes are then made, once with the model's solid geometry and once again with the line geometry. Nearly edge-on filled polygons are pushed substantially away from the eyepoint, to minimize interference with the line geometry, while nearly planar polygons are drawn at least one depth buffer unit behind the line geometry.
> Source

check out this link, waaaaaaaaay at the bottom; the very last thing is a code sample.
They just:

```
glDisable(GL_POLYGON_OFFSET_FILL);

```

before going to line mode

glLineWidth also covers anti-aliasing

A sample wireframe pixel shader:

```
return float4(0, 1, 0, 1);

```
> 1 votes

---
Tags: opengl, c++, depth-buffer
---


title: Instantiated Prefab Facing Wrong Way

text:
# Question
Title: Instantiated Prefab Facing Wrong Way
Here's a Youtube video of my problem in action ((in the video I am clicking in various directions, yet the fireball is always created facing down in some direction.))

I've been having a lot of trouble wrapping my brain around Quaternion rotations in Unity2D.

What I'm trying to do is so simple, yet it keeps beating me. I simply want to instantiate a prefab of fireball when I click the button. The problem is that I want the fireball to be facing in the direction of the mouse before firing along. I haven't gotten to the fire and velocity part because I can't get it face the right direction when it's created.

In my playercontrollerscript attached to the player Object I have this (In C#)

```
        if (Input.GetMouseButtonDown (0) && anim.GetBool ("canAtk")) { //Basic attack controls

        curTarget = Camera.main.ScreenToWorldPoint(Input.mousePosition);

        if(classState == "Cutter"){
            anim.SetTrigger ("attacking");
            anim.SetBool ("canAtk", false);
            StartCoroutine (AttackTiming ());
            anim.SetFloat ("animCombo", playerCombo);
        }
        else if(classState == "Flame"){
            Debug.Log (curTarget);
            var worldTarget = Input.mousePosition;
            Quaternion rot = Quaternion.LookRotation(transform.position - curTarget, Vector3.right);
            Rigidbody2D fballClone = (Rigidbody2D) Instantiate(fireBallz, transform.position, rot);

```

(You can safely ignore the cutter class part. The problem is when I'm in Flame class. I also have a script attached to the prefab object, but at this moment all it does is control Euler angles so it doesn't rotate along the weirdness axis.

Anyways, each time I hit the button it creates a fireball, but it's like they are 90 degrees behind where they should be. I say "like" because that's not always the case. If I click under my character, then the fireball is pointing up. If I click sort of "Down/right" it points "up/right".

This would be easier if I could visually wrap my head around how the rotations work. Any advice would be appreciated. If you need any more information or screenshots let me know as well. Thanks again.

Update: so previously I had left a line setting curTarget.z to 1 because it was returning -10 for the camera Z and I thought that was related to the problem. Oddly, when I removed that line it halfway fixed the problem. Now, if I click in the down/right or down/left or down it will create the fireball facing correct direction, but if it's "up" any, then it will pretty much face the opposite direction. Also, directly left or directly right causes the fireball to face down.

New Update: (Sort of just updating as I try to work it out.) I turned on Debug.Log(rot) just so I could see the rotation values when I create the fireball.

If I click bottom right I get (0.0, -0.6, -0.4, 0.7) the fireball is facing the correct position as it does always as long as I'm clicking in the "downish" area. When I click top right I get (-0.6, 0.0, 0.7, -0.3) and the fireball is facing Bottom-Left. So I click in the bottom-left direction and I get (0.6, 0.1, 0.7, -0.4) and it's facing bottom-left. My brain is so fried I'm not piecing it together correctly. Something I'm missing.

# Answer
I finally managed to solve my problem. I was able to find an old question and answer from a few years ago. The code didn't work exactly the same anymore, but I was able to get the idea of what was happening.

Here's the code to instantiate the object.

```
else if(classState == "Flame") {
    one = (Rigidbody2D) Instantiate(fireBallz, transform.position, transform.rotation);
}

```

Then, on the actual fireball itself is this little snippet that controls the actual rotation.

```
void Start () {
    if(spellName == "SmallFireball");{
        mouseClickPos = Camera.main.ScreenToWorldPoint(
             new Vector3 (Input.mousePosition.x, Input.mousePosition.y, 1));
        transform.eulerAngles = new Vector3(0, 0, Mathf.Rad2Deg * Mathf.Atan2(
             mouseClickPos.y - transform.position.y,
             mouseClickPos.x - transform.position.x));
    }
}

```

Works like a charm now.
> 1 votes

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


# Question
Title: Bubble shooter clone, structure for storing/adding of bubbles
Im having a few issues trying to figure out what the best data structure to use for storing bubbles on the grid, and how to connect new bubbles to the grid when a moving ball collides with a ball on the grid.

My first implementation was to create a 2d array and populate it with a bunch of bubbles. I then iterate through the array and make a connection between bubbles only if there are adjacent bubbles in all directions from the current bubble. After Ive build the grid, and made all the connections, I added each bubble to list that I can look up and find connections between bubbles when a collision is detected.

When a moving ball collides with a stationary ball, I create a connection between the ball and then run a recursive BFS search from the colliding ball, finding all balls that are of the same color of the ball I just collided with. This works, but isnt very bulletproof, as I often get broken connections between balls when certain balls are deleted, or often groups of balls wont disappear that should.

My second implementation was to use a Hex grid. I had read similar questions on here where users suggested using a hex grid, so I thought I would try that approach. Again, I created a 2d array with a bunch of bubbles and tried running a mapper which mapped certain balls to each other depending on where they are in the grid. I still had a bunch of issues with connections, and often connection would end up getting broken or not connected properly.

Theres a lot of edge cases that Im still stuck on that im not exactly sure how to solve. For example, when I a colliding ball makes a connection with another ball, how should I deal with if that ball collides with a second ball at the same time. Or how should I look for balls within a certain area.

I feel like Im just overthinking this, and making the problem way more complex then it needs to be.

# Answer
> 0 votes
Ive returned to answer my own question now.

I ended up using the resources found in this answer:

Creating a frozen bubble clone

I converted my 2D grid array into a hex array. I still used a 2D array to index into the hexes, but I made sure to make sure my hex grid function in a odd-r layout, and that I indexed my array properly based on that layout. All of this info is coverted in this article:

http://www.redblobgames.com/grids/hexagons/

To detect collisions, I ended up doing some math, trying to find on which part of the hex that my colliding ball made contact with.

A way of doing this is found here:

How can I implement hexagonal tilemap picking in XNA?

# Answer
> 0 votes
I would try using an N-ary tree structure. The bubbles stack up in a skewed formation. If you take a bubble and surround it with other bubble, you will only get 6 possible connections: top left, top right, left, right, bottom left, and bottom right. Contrast this with a 2d grid and you get 8 possible connections: top left, top center, top right, left, right, bottom left, bottom center, and bottom right. This should make using a 2d array a bit cumbersome to keep track of the proper connections between nodes.

My approach would be to make each node have 6 connections, make the tree big enough to represent the entire play area, allow for empty nodes, and allow for edge nodes or null node connections.

---
Tags: architecture, algorithm, data-structure, graph
---


# Question
Title: Combining two independent rotations relative to the world frame
I am implementing a mouse rotation which works by accumulating the X-Y delta between frames to yaw and pitch rotation angles. The problem is that I wish rotations to be independent of each other. But as you can see from the picture:

I wish it behaved like this instead:

In the second picture, instead of dragging, I am releasing the mouse button and performing a second drag movement. So the local Y-axis is not rotated as in the first picture.

This is the code I am using:

```
Vector2 delta = current - lastPointerPosition;
totalYaw += delta.X;
totalPitch += delta.Y;
var r = Quaternion.RotationAxis(Vector3.UnitY, totalYaw / 100f);
var s = Quaternion.RotationAxis(Vector3.UnitX, totalPitch / 100f);
var qOrientation = s*r*qStart;

```

Please ignore for the moment the crude division by 100, I wanted to get the rotation right before optimising that part. That code causes the behaviour in the first picture.

I tried to rotate the UnitX axis used in the second quaternion by doing `var q = r*new Quaternion(Vector3.UnitX, 0)*Quaternion.Invert(r);` and then using `q.Axis` in place of `UnitX` in `s`.

I have looked all over the web but so far none of the solutions seemed to work for me. What am I doing wrong?

**EDIT** every time the mouse moves, I am updating lastPointerPosition with the current one (after updating the rotation matrix); when the mouse pointer is released, totalYaw/totalPitch are restored to 0.

# Answer
Instead of accumulating into `totalYaw` and `totalPitch`, accumulate into a quaternion:

```
Vector2 delta = current - lastPointerPosition;
var yaw = delta.X;
var pitch = delta.Y;
var r = Quaternion.RotationAxis(Vector3.UnitY, yaw / 100f);
var s = Quaternion.RotationAxis(Vector3.UnitX, pitch / 100f);
qTotalRotation = s*r*qTotalRotation;
var qOrientation = qTotalRotation*qStart;

```

(`qTotalRotation` is initialized to the identity quaternion.)

Originally, you computed the total mouse position delta (relabeled as `totalYaw`, `totalPitch`) and applied this to the original quaternion. Crucially, the delta quaternion (`s*r`) is applied to the same `qStart` quaternion, so it is always acting in the same space, with the same coordinate axes.

In this second formulation, each mouse movement results in a new quaternion representing just that small motion being created and accumulated. If the mouse has moved twice, then:

```
qOrientation = qTotalRotation * qStart
qOrientation = (s_2*r_2) * (s_1*r_1) * qStart

```

That is, each of the later `s_i*r_i` are applied *after* the previous rotations, so they act in a space with rotated axes, not the original space.

Another way to look at this which might be helpful is to note that in the orignal formulation, the path the cursor takes from start to finish does not matter: it is only the delta that changes the orientation. In the second one, however, due to the *non-commutativity* of quaternions, if the first motion is horizontal and the second is vertical, this will be different from if the first is vertical and the second horizontal. In particular, the second acts as if the mouse button is released and then pressed immediately on each motion.
> 1 votes

# Answer
The problem lies in `lastPointerPosition`.

In your first image `lastPointerPosition` never changes there for both rotations are applied to the same `qOrientation`. The mouse gets released and applies to the cube.

In the second image `lastPointerPosition` changes. You do the first rotation, let go of the mouse button and apply the rotation. You click again and `lastPointerPosition` changes, you now apply the rotation on top of the existing one, instead of combining them.

The solution would be to do the rotations on a per axis basis i.e have a `lastPointerPositionX` and `lastPointerPositionY`. So basically you do this:

```
Check Pointer X
    If changed do rotation
        based on delta
    apply rotation

Check Pointer Y
    If changed do rotation
        based on delta
    apply rotation

```
> 0 votes

---
Tags: rotation, quaternion, mouse
---


# Question
Title: How to texture a surface generated by marching cubes algorithm?
I'm working on a voxel game, and I have some problems with texturing. I have read the related questions on this stack exchange, but they seem adressing a generic problem (using triplanar texturing), and I think mine is simpler.

You can see that the resulting geometry contains a limited set of polygons. Last I checked I saw only 44 of them. My idea was to uv map these polygons to a regular texture using a static map table, without having to use any triplanar texturing (currently, every polygon is mapped to the same values, so it's ugly).

My questions :

* Is it valid ? It seems much simpler than triplanar texturing, but I can't find a single resource on the subject, so I'm wondering if it's a right approach.
* Where can I find / How can I generate a UV map for this kind of geometrical figure ? I have tried to use blender but it seems like my blender-fu is not strong enough. Is there some simpler software to generate UV map with models like this one ?

# Answer
> 5 votes
Another way would be to procedurally generate your textures. This approach comes with its advantages and disadvantages. Most important tradeoff is that you can't draw your textures in an editor but have to code them using noise functions.

The huge gain in your situation is that you can texture your terrain completely orientation independent. This is done by using so called solid noise. It is a three dimensional noise function.

Using that you can code a function to generate the color value of any given position *in 3d space*. Then you sample just the points lying on the mesh faces. In other words, you carve out from the three dimensional texture.

This is from the libnoise glossary.

> The following image shows an object that has a solid noise texture. Note that the texture does not warp anywhere on the object; it is uniform throughout the object. It would be very difficult to produce a non-warping two-dimensional texture map for this object.

I know that it may not be your aim to code instructions for generating every texture you want to use. But it may also be a challenge and comes not only with the orientation independent advantage but also with heavily reduced storage space and unlimited zoom-in detail.

I would be very interested if you would try to implement solid noise textures for your terrain.

# Answer
> 4 votes
So this doesn't provide details to every problem you'll encounter with your approach, *but*, if you want to map each vertex to the closest non-air voxel in order to scrape information from it (such as which texture to sample), here's a proof for the efficient method I came up with:

> For any given marching cubes vertex, we wish to select a voxel with which to infer the vertex's attributes. We choose the closest non-air voxel, which by its definition must be located along the same edge the vertex is placed on. Furthermore, because the 'surface' we generate delineates air from solid, it follows that the two voxels along an edge containing a vertex must be one solid, and one air. Therefore, if each voxel adjacent to the current cube is indexed by the combination of it's inclinations along each axis, then we may infer two of its inclinations by the particular edge on which the vertex rests, and the third inclination by sampling both possible corners and selecting only the one that is solid. Thus, to sample the desired voxel efficiently, we establish a lookup table mapping each of the twelve cube edges to two possible voxel indices each, the upper and lower four bits of each being indices into the set of eight possible voxels. After sampling both voxels, we may add the two samples together rather than branching in order to select the solid one. If 'air' is a non-zero value, we may simply subtract it from the final result, since one of the operands is guaranteed to be that value.

Here's my implementation in Java, assuming corners and edges are indexed as described in Paul Bourke's popular article (corner zero being -X -Y -Z):

..and assuming that `blockIds` is a `long` whose bytes each correspond to a corner, from most to least significant, 0, 1, 4, 5, 3, 2, 7, and 6. (In terms of inclinations XYZ, the ordered values are 000, 100, 010, 110, 001, 101, 011, and 111.)

```
private static final byte[] BLOCK_PICK_BITS_BY_VERT_INDEX = new byte[]{
    (byte)0x67,
    (byte)0x26,
    (byte)0x23,
    (byte)0x37,
    (byte)0x45,
    (byte)0x04,
    (byte)0x01,
    (byte)0x15,
    (byte)0x57,
    (byte)0x46,
    (byte)0x02,
    (byte)0x13
};

private static final int pickBlockIdForVertex(long blockIds, int vertIndex)
{
    int bits = BLOCK_PICK_BITS_BY_VERT_INDEX[vertIndex];
    int blockIndexA = bits >> 4;
    int blockIndexB = bits & 0xf;
    int blockIdA = (int)(blockIds >> 8 * blockIndexA) & 0xff;
    int blockIdB = (int)(blockIds >> 8 * blockIndexB) & 0xff;

    //assert (blockIdA == airBlockId) != (blockIdB == airBlockId);
    //return blockIdA - nonZeroAirBlockId + blockIdB;
    return blockIdA + blockIdB;
}

```

In C/C++, it could make sense to change `long blockIds` to an array of bytes/shorts/pointers, and remap each four-bit value in the table according to `bits = 7 - bits`. I haven't profiled it, though, so packing everything into a `long` may still be faster. Finally, in case of a non-zero air blockId, it's reordered so that in case of a large domain of blockIds, no overflow occurs. Wouldn't happen in the code above, since I'm using `ints` to store blockIds which are `bytes`, but it's something to consider.

(To be 100% clear, I contribute this method to the public domain and waive liability according to the full license described here: http://unlicense.org/)

# Answer
> -2 votes
UV mapping does look like the correct way to go with this. I believe this answers your first question (but I may be wrong). About why Blender won't UV map this for you is because it's trying to unwrap it as one giant lump-thing. You need to add seams to the model so that Blender can split it appropriately - look at Blender's Official Guide to UV Mapping to see how to do this.

---
Tags: 3d, voxels, uv-mapping
---


# Question
Title: Instantiate a prefab and call a method from it's script
I am creating a game in unity and I have a prefab that I instantiate on center occasions. What I want to do though is after instantiating the prefab. Get a handle to it and call a specific public method from the script attached to it. One method would be to put that part of code in the start function of that script. But what if I do not want that code to run as soon as the prefab is instantiated? How can I get a handle to it and manually call that specific method?

# Answer
GameObject.Instantiate returns an Object reference that you can then cast. Use GameObject.GetComponent() to get a component of type T from that gameobject. Since scripts are components, you can get them through this method.

So:

```
GameObject prefab;
GameObject prefabInstance = GameObject.Instantiate( prefab ) as GameObject;
if( prefabInstance != null )
{
    var myScriptReference = prefabInstance.GetComponent<MyScript>();
    if( myScriptReference != null )
    {
        myScriptReference.MyMethod();
    }
}

```

So, we instantiate like normal and get a reference to the created game object. Then we check to make sure the result wasn't null for some reason. If that went okay, we can get a reference to our script using GetComponent. Using the script reference, we can call the method with want.

Also note in Unity 5 a generic version of instantiate was added. This means the second line can be changed to:

```
GameObject prefabInstance = GameObject.Instantiate<GameObject>( prefab );

```

Which makes things a little cleaner. The reason we need to cast in the first place is because Instantiate is actually an Object method, not a GameObject method.
> 2 votes

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


# Question
Title: Help on transition from one position to another
I'm pretty sure I'm over thinking stuff, but I can't seem to figure this out. I want to move the object from one location to another. Here's what I got. I searched this up earlier here, and I found something similar, but I wasn't able to make it work. Any help would be appreciated, thanks.

```
//the current position of the object is at 400, 300
Vector2 nextPosition = new Vector(100, 200);
Vector2 difference = nextPosition - position;

difference.Normalize();

position += difference * 5;

```

# Answer
> 1 votes
```
position += velocity * DeltaTime * speed;

```

This is a better way of calculating the position. this way your movement wont slow down on framerate drops, because you take into account the time elapsed between the last Update call, if it was longer than usual (low fps) you move more distance.

The code you have simply keeps increasing the position and never stops. You need to stop the movement once it reached the target position. Here I show you how to move an object to the current mouse position.

```
//---Initialize some variables---
Vector2 targetPosition; //mouse current position
Vector2 currentPosition = new Vector2(200, 200); //start from (200,200)
Vector2 velocity = targetPosition - currentPosition;
float speed = 0.1f;

//---Update()---
//update velocity and target position according to the mouse's current position
MouseState ms = Mouse.GetState();
targetPosition = new Vector2(ms.Position.X, ms.Position.Y);
velocity = targetPosition - currentPosition;

//if we are currently not on target position
if (currentPosition != targetPosition)
{
    //move the current position towards target position
    currentPosition += Vector2.Normalize(velocity) * speed *
        (float)gameTime.ElapsedGameTime.TotalMilliseconds;

    //if we passed the target, set the current position to target position
    Vector2 nextVel = targetPosition - currentPosition;
    if (nextVel.X * velocity.X < 0 || nextVel.Y * velocity.Y < 0)
        currentPosition = targetPosition;
}

```

You only need to update the the velocity `velocity = targetPosition - currentPosition;` whenever you change the `targetPosition`. Here, I need to update the velocity in every Update, because I change the `targetPosition` in every Update (because I set the targetPosition to the mouse current position).

# Answer
> 1 votes
There are a lot of ways to move something between two points. Want it to go in a straight line at a constant velocity? Then you might want to consider simple linear interpolation.

```
// Gives you a value that linearly interpolates between the start and end.
// t is an interpolation parameter between 0 and 1. When t = 0, the position is
// at the stat. When t = 1, the position is at the end.
Vector2 lerp(Vector2 start, Vector2 end, float t)
{
    return (1 - t) * start + t * end;
}

```

You can scale this over time by doing this:

```
// Gives the position of the target at the given time by linearly interpolating.
Vector2 move(Vector2 start, Vector2 end, float currentTime, float maxTime)
{
    return lerp(start, end, clamp(currentTime / maxTime, 0.0, 1.0));
}

```

Now, when you start moving, set the current time to `0.0`. Increment the time by the change in time between frames until you get to the max time. Then the move is done.

---
Tags: c#
---


# Question
Title: Usage of math.Atan2 in a 3D coordinate system with Unity
I have a simple question on usage of math.Atan2 function with Unity in a 3D environment.

I found this code on Unity's documentation for Math.Atan2. I changed it a bit to fit my needs.

```
Vector3 waypoint = Random.insideUnitSphere + new Vector3(Random.Range(minX+1.5f, maxX-1.5f),prevPosY,Random.Range(minZ + 1.5f,maxZ - 1.5f));  //waypoints are generated based on random unit sphere + ( bounds of the plane they are on )
Vector3 relative = transform.InverseTransformPoint (waypoint);
float angle = Mathf.Atan2 (relative.x, relative.z) * Mathf.Rad2Deg;

```

I know how it works in a normal 2D coordinate system, however when switching to a 3D coordinate system, if I would want to move my character on the x-z plane, then how does this actually work mathematically?

I am assuming that it would be the angle between z and x axis? so in a mathematical equation would it be, angle = Atan2(z/x) or Atan2(x/z)? Would both of them work?

# Answer
Beware of the argument order here. Here is what `atan2` will give you:

* `atan2(x,z)` is the angle between the `(x,0,z)` vector and the +Z axis in the Z-X plane.
* `atan2(z,x)` is the angle between the `(x,0,z)` vector and the +X axis in the X-Z plane.
> 3 votes

# Answer
The value of the *angle* variable would be equivalent to the atan(relative.x/relative.z) for the angles lying in the range (-pi/2; +pi/2). In other words it is an angle measured from axis z, positive direction of that is a CCW rotation seen from the top of the y vector.

For the given example, the value of the *angle* variable would be an angle between the local (corresponding to the *transform* variable) z axis and a projection of the *weypoint* onto the local x-z plane.
> 1 votes

---
Tags: unity, mathematics
---


title: In Game Maker, how do I draw a surface?

text:
# Question
Title: In Game Maker, how do I draw a surface?
I'm trying to draw a surface in black in Game Maker. This is the code:

```
//Create event
surf = surface_create(room_width, room_height);

//Draw event
surface_set_target(surf);
draw_clear_alpha(c_black, 0.8);
surface_reset_target();

```

It seems to only work when I minimize and then maximize the game. How can I make this work without having to minimize the game?

# Answer
You aren't actually drawing the surface here. You clear it with black and then leave it.

You need to draw the surface with `draw_surface(surf, x, y)`

Furthermore, you shouldn't clear the surface every draw event if it is not going to change. Move

```
surface_set_target(surf);
draw_clear_alpha(c_black, 0.8);
surface_reset_target();

```

to the create event and the surface will only be cleared once.
> 1 votes

---
Tags: rendering, game-maker
---


# Question
Title: how to make coins explode out of monster in phaser?
I am trying to make coins explode out of a monster when it is killed. the explode would be similar to this example: http://phaser.io/examples/v2/particles/diamond-burst

I also want the coins to be clicked individually similar to this example: http://phaser.io/examples/v2/groups/call-all-input

I am confused as to how to incorporate the two above examples together. Is emitting particles the way to go? I am also confused as to how to set each coin to have a different value depending on the monster.

Any help is appreciated.

# Answer
> 0 votes
You can set a custom class for your particle-system instead of the standard-particle.

Use the `emitter.particleClass` property (here's an example of how to use it).

In that custom class you can then write code that handles the user-interaction etc.

---
Tags: phaser
---


title: Circle-Circle collision resolution

text:
# Question
Title: Circle-Circle collision resolution
This seems easy but I can't figure it out, when I have one circle(c1) collide with another(c2) I give the c2 circle the heading of c1 and send the c1 circle on the normal vector to the heading (the heading is stored as vector = (cos(theta), sin(theta)) this is probably a bad solution). So this works great when c1 is colliding head-on with c2, however if c1 collides with it's tail into c2 then c2 takes the direction that c1 is facing which causes them to intersect each other. Any ideas of how I can "re-word" the heading vector so it's not dependent on theta (the angle that c1 is looking at in the cartesian plane)?

Here is an example: Elastic Collision

# Answer
The question sounds like it is describing a problem with object penetration. (When one circle is overlapping the other and it causes the deflection to be calculated wrong).

This is a problem with the precision of the collision tests. If I have understood the problem correctly, what is happening is that collision detection only happens once per frame but the object is moving too fast in a single frame. The collision with the correct edge is missed. When the collision test occurs, the object has already passed through and is then deflected off the other side.

The key thing to fix this is to limit the speed of your moving objects to less than half their width. This would ensure that your collision is always detected on the correct side. This will still allow objects to penetrate though and anytime you have object penetration your physics will be inaccurate, though it's often good enough.

You can improve on this by offsetting the penetrating objects so that they are just touching (IE. rewind to the point where they actually collided), then perform your deflection calculations based on the corrected positions.

If you want accurate results or need fast moving objects (good for billiards and similar high speed collisions), then you need to implement sweeping collision detection. Basically, instead of checking once per frame, you check X times per frame, depending on how much precision you want.
> 2 votes

# Answer
Your solution is correct, but only for a very specific type of collision. Even the gif is really only valid if a moving circle hits a stationary circle - not if two circles are moving and hit each other. Since you probably want to be able to make this work regardless of how the circles are moving when they collide, you'll need to do some calculations.

Short description: find the normal vector between the two touching circles, and know that each circle will have its velocity vector essentially flipped over that line - that gives you the direction of the resultant velocities. Use conservation of momentum to find their magnitudes. For the actual math I found http://www.hoomanr.com/Demos/Elastic2/ seems to explain it reasonably.
> 1 votes

---
Tags: mathematics, physics, collision-resolution
---


# Question
Title: When does DirectX convert a vertex/pixel's depth from range Near-Far to 0-1?
When I output a vertex from a vertex shader, it seems to have a world-space-ish mapping. Vertices about 1 unit away have about 1 unit as their Z value.

When we input into the pixel shader, the depth values are mapped from 0..1 as defined in the viewport state.

Where does this conversion occur? It's late and I'm forgetful, but I can't find a place where I told DirectX what my depth range even was (other than implicitly in the projection matrix). How does it know how to convert it?

# Answer
The Z coordinate has a different meaning when we're talking about viewport coordinates.

In most vertex shaders, at some point you are multiplying each vertex by a projection matrix in order to convert world coordinates into viewport coordinates.

After leaving the vertex shader, each vertex will be then divided by the W value. The resulting value is now in viewport coordinates, where triangles whose vertices are all outside of the (-1, -1, -1), (1, 1, 1) cube are culled.

In viewport coordinates, X and Y are mapped to X and Y in the screen ((0, 0) being the center of the screen), and Z to the depth of the vertex (-1 being the near plane, and 1 the far plane).

After interpolation, each fragment will then have a Z coordinate, which can be used for Z-buffering and Z-testing if you wish to.
> 1 votes

---
Tags: hlsl, directx10
---


# Question
Title: How do I fix the error "The type or namespace name RigidBody could not be found"?
I got stuck with this problem; I have searched Unity forums but could not get an answer to solve it.

I am getting this error:

> The type or namespace name RigidBody could not be found. Are you missing a using directive or an assembly reference?

```
using UnityEngine;
using System.Collections;

public class playercomponent : MonoBehaviour {

    public RigidBody rb;

    void start()
    {
        this.rb =  GetComponent<Rigidbody>();
    }

    void FixedUpdate()
    {
        float moveHorizontal = Input.GetAxis("Horizontal");
        Float moveVertical = Input.GetAxis("Vertical");
        Vector3 movement = new Vector3 (moveHorizontal,0.0f,moveVertical);

        rb.AddForce(movement);
    }
}

```

# Answer
it should be Rigidbody, not RigidBody
> 17 votes

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


# Question
Title: Problem with textures using DirectX file format in Irrlicht
I'm using Irrlicht 1.8.1, and Blender 2.71 to create my animations. I've just create a simple cube, added a default material to it, and i've mapped a texture to it using UV unwrap, all that in Blender.

Then i use I to save rotation+location+scale, when i pressa ALT+A, everything works fine, and when i press F12, i can see that the texture mapping are fine too.

When i export the mesh using OBJ format (which is not an animation) and load it as AnimatedMeshSceneNode or simple MeshSceneNode, Irrlicht render it as expected. Fine

But when i export the entire cube animation scene (checking the export animation option, and material option, etc) and loading it in Irrlicht (cube.x) the model is loaded and the animation started as expected but the TEXTURE ARE MAPPED INSIDE THE CUBE! Then the outside faces of the cube looks like transparrent letting you to see the texture mapped on the faces inside this cube.

Thought, I noted Irrllicht was able to load the well known "dwarf.x" animation model in its examples source codes.

Anyone knows how to fix this unwanted behaviour of the texture?

# Answer
> 1 votes
Graphics APIs have a function called "backface culling" where they omit drawing any triangle which is facing away from the viewpoint.

This is determined by looking at the winding order of the vertices after projection, classifying them based on if it's clockwise or counter-clockwise.

There is a mismatch between the winding of your source geometry and the winding that your current settings in your engine. Either change the winding your engine expects (if possible) or change the winding in your content creation package. That operation is usually called "unify/flip normals", or is achieved with an option in the exporter.

As you claim to be able to load a sample mesh correctly, you need to fix your mesh to agree with conventions, or fix the exporter in case it does it wrong.

---
Tags: textures, directx, blender, irrlicht, format
---


title: What is AABBvsAABB Collision detection?

text:
# Question
Title: What is AABBvsAABB Collision detection?
Currently studying Game Engineering at university and my lecturer has asked us to implement a collision manager. He asks us to use AABBvsAABB to build it, so then we can add the physics.

My question is and if anyone can answer it as simple as possible (as the notes he uses I am still lost).

**What exactly is AABBvsAABB for collision detection?**

Any links to sites that explain it or just some basic examples would be appreciated. EDIT: links or examples that explain it in simple terms, I can't seem to find any :(

# Answer
An AABB is an axis-aligned bounding box. It is a box whose sides are aligned with the axes of the world, and which has extents along each axis.

By "AABBvsAABB" your instructor is trying to tell you to make an intersection test between (versus) two AABBs, finding whether they intersect, how they intersect, etc.

There are algorithms to find intersections for pretty much any combination of primitive shapes you can imagine, the one for AABB/AABB is rather straightforward, checking for each axis if the ranges from the low and high ends overlap.

```
+--------------------------------------+
|                                      |
|                              Y check |
|                                      |
|            +------+           +      |
|            |      |           |      |
|            |      | +---+     |  +   |
|            +------+ |   |     +  |   |
|                     |   |        |   |
|                     |   |        |   |
|                     |   |        |   |
|                     +---+        +   |
|                                      |
|                                      |
|            +------+                  |
| X check                              |
|                     +---+            |
|                                      |
+--------------------------------------+

```

An index of references to the methods can be found on the Realtime Rendering site.
> 6 votes

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


# Question
Title: Simulation of ball movement in a 3d landscape. The easiest way?
I have a landscape(generated via Perlin noise) and a ball. I want the ball to move along the geodesic(implementation of basic physics: gravitation, friction). I thought to do raycast around the ball to the landscape, choose the lowest point and move the ball to this point, but it won't work in every case and it won't allow the ball to jump (with inertia). So, what is the best way/algorithm to implement such feature?

P.S. I don't want to use any libraries.

Thanks.

# Answer
The first step in implementing a physics engine is to model the movement of each object in form of a 3d velocity vector. Each object has current velocities in x, y and z direction. Each logic tick of your game engine, the object is moved by its current velocity. Changing the velocity-vector of an object by applying an acceleration-vector is the primary method of moving an object in a pyhsics engine. Other forms of position changes only occur in extraordinary circumstances, because an instant position change violates Newton's laws of motion and thus introduces implausible situations into your physics simulation.

To introduce gravity, change the z-vector (or whichever axis is "up" in your game) by the equivalent of 9.81 meters per second / your update rate.

To make the ball bounce, check for collisions with the ground. When you have a collision, mirror the current movement vector at the plane on which the collision happened. For a flat plane, that would mean to just invert the z-vector. When you have angled planes, it gets a bit more complex.

Then multiply the vector by the "bounciness" of the object. The bounciness is somewhere between 1.0 for super-bouncy (bounces forever) or 0.0 for completely unbouncy (stops completely when touching a surface).

But seriously, you are reinventing the wheel here. There is no shame in using 3rd party libraries. There are lots of physics engines available which already implement this better than you could. Just use the tools the development community has to offer and use the time you safe to build your game.
> 4 votes

---
Tags: opengl, c++, 3d, physics, simulations
---


title: C# - console application, array problem

text:
# Question
Title: C# - console application, array problem
I have problem in very simple console app, code looks like this.

int x - player moving and changing axis "x" and I want make full history of moving via array. See code(only example) below...

Thank you for your help and answer

```
  int round = 0;

  while(infinity){

  int[] PosXSave = new int[round + 1]; //theoretically infinity size of arrray.

  PosXSave[round] = x; //every round i want save current value of x, but
                       //only last save have propertly value and rest are
                       //zero or other number

  round++

  }

```

# Answer
> 1 votes
Using array might be bit faster, but List would be easier to use in this case.

```
List<int> history = new List<int>();
while(infinity){

 history.Add(x);

}
// round is history.count;

```

---
Tags: c#, console
---


# Question
Title: Monogame - stopping a custom shader (drawable game component) when inside another drawable game component
I have run into a bit of trouble when using a custom shader (gaussian effect) within another drawable game component, as I cant figure out how to break out of the draw method, so the effect is applied to everything.

Basically, I have a WP8 project where the game class merely instantiates two separate DrawableGameComponents

```
        // Resource used for loading the different screens.
    private ScreenManager mScreenManager;

    public static BloomComponent BloomComponent;

    ....

        // Initialize the bloom component.
        BloomComponent = new BloomComponent(this);
        Components.Add(BloomComponent);
        BloomComponent.Settings = new BloomSettings(null, 0.25f, 4, 2, 1, 1.5f, 1);

        // Initialize the screen manager.
        mScreenManager = new ScreenManager(this);
        Components.Add(mScreenManager);

```

and the draw method of the game class itself doesn't actually do anything - it leaves it up to the components initialized when the game is instantiated.

The screen manager then renders the "Gameplay" screen which goes through and draws all the game sprites and some GUI text for the score etc, which is all fine.

I am then trying to use the BloomComponent via a static call to the Game class's BloomComponent instance, within the draw method of my "gameplay" screen, which works and applies the effect. The only problem is it applies the effect to everything, including the GUI text for the score; I only want to apply it to the sprites being rendered. Hence, I am basically trying to terminate the draw call for the BloomComponent. I had taken the BloomCoponent from an online sample, which appears to break the effects draw by calling base.Draw(gameTime). However, from within the Draw() method for my screen I cannot access the xna.Game Draw() due to the way the ScreenManager renders the screens:

```
    /// <summary>
    /// Tells each screen to draw itself.
    /// </summary>
    public override void Draw(GameTime gameTime)
    {
        // Draw all of the game screens.
        foreach (GameScreen screen in mScreens)
        {
            // If the screen is hidden, don't draw it.
            if (screen.ScreenState == ScreenState.Hidden)
                continue;

            // Draw the screen.
            screen.Draw(gameTime);
        }
    }

```

So my question is,is there a way to break out/stop a drawable game component, so that I can stop the effect from being applied to everything?

Here is my GameplayScreen Class, and the BloomComponent for reference:

GameplayScreen.cs

```
#region Using Statements

using System;
using System.IO;
using System.Collections;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using Microsoft.Xna.Framework.Input.Touch;
using System.IO.IsolatedStorage;
using Microsoft.Xna.Framework.Storage;
using System.Xml.Serialization;
using System.Collections.Generic;
using Microsoft.Phone.Shell;
using Microsoft.Phone.Controls;
using System.Windows;
using Vision.ScreenPad;

#endregion

namespace Vision
{
    /// <summary>
    /// This screen implements the main game logic. It provides access functionality to
    /// load, render and update the level and player objects. It also checks and handles user
    /// input.
    /// </summary>
    class GameplayScreen : GameScreen
    {

        #region Fields/Properties

        // Resource for loading content.
        public ContentManager Content
        {
            get { return mContent; }
        }
        private ContentManager mContent;

        // Resource for drawring content.
        private SpriteBatch mSpriteBatch;

        // The screens viewport.
        public static Viewport Viewport;

        public static Vector2 ScreenSize { get { return new Vector2(Viewport.Width, Viewport.Height); } }

        public static ParticleManager<ParticleState> ParticleManager { get; private set; }

        public static GameTime GameTime { get; private set; }

        public static BackgroundGrid BackgroundGrid { get; private set; }

        private static BloomComponent BloomComponent;

        #endregion

        //////////////////////////

        // The on screen game pad
        public static Vision.ScreenPad.ScreenPad ScreenPad;

        // The current state of the screen pad
        Vision.ScreenPad.ScreenPadState CurrentScreenPadState;

        #region Initialization

        /// <summary>
        /// Constructor to create a new gameplay screen.
        /// </summary>
        /// <param name="levelIndex">The numeric index for the level to be loaded.</param>
        /// <remarks>
        /// The actual level file loaded will be value of the index incremented by one.
        /// </remarks>
        public GameplayScreen()
        {
            // Set the transition time for when the screen is loaded and unloaded.
            TransitionOnTime = TimeSpan.FromSeconds(1.0);
            TransitionOffTime = TimeSpan.FromSeconds(0.3);

#if WINDOWS_PHONE
            PhoneApplicationService.Current.Deactivated += GameDeactivated;
            App.RootFrame.Obscured += GameObscured;
#endif
        }

        #endregion

        #region Loading

        /// <summary>
        /// Loads all of the gameplay screens cotent.
        /// </summary>
        /// <remarks>
        /// The level object loads the player and all tile content contained within the level
        /// file, which is retrieved using the incrememnted level index.
        /// </remarks>
        public override void LoadContent()
        {
            if (mContent == null)
                mContent = new ContentManager(ScreenManager.Game.Services, "Content");

            // Create a new SpriteBatch which will be used to draw the level and player textures.
            mSpriteBatch = new SpriteBatch(ScreenManager.GraphicsDevice);

            // Load the viewport.
            Viewport = ScreenManager.GraphicsDevice.Viewport;

            ScreenPad = new ScreenPad.ScreenPad(Viewport,
                Content.Load<Texture2D>("Overlays/Controller/ThumbBase"),
                Content.Load<Texture2D>("Overlays/Controller/ThumbStick"),
                Content.Load<Texture2D>("Overlays/Controller/Dpad_All"),
                Color.Blue,
                Color.Red,
                Color.Green
                );

            // Load the art objects
            Art.Load(mContent);

            // Load the sound objects
            Sound.Load(Content);

            ///////////////////////////////////////////////////

            //BloomComponent = new BloomComponent(ScreenManager.Game);
            //ScreenManager.Game.Components.Add(BloomComponent);

            //BloomComponent.Settings = new BloomSettings(null, 0.25f, 4, 2, 1, 1.5f, 1);

            //////////////////////////////////////////////////

            ParticleManager = new ParticleManager<ParticleState>(1024 * 20, ParticleState.UpdateParticle);

            const int maxGridPoints = 1500;
            Vector2 gridSpacing = new Vector2((float)Math.Sqrt(Viewport.Width * Viewport.Height / maxGridPoints));
            BackgroundGrid = new BackgroundGrid(Viewport.Bounds, gridSpacing);

            EntityManager.Add(PlayerShip.Instance);
        }

        /// <summary>
        /// Removes all graphics content used by the gameplay screen.
        /// </summary>
        public override void UnloadContent()
        {
            mContent.Unload();
        }

        #endregion

        #region Rendering

        /// <summary>
        /// This is called when the gameplay screen should draw all of the loaded content.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        /// <remarks>
        /// The spritebatch is passed to the level object to localise the rendering of level content.
        /// The same spritebatch is also passed to the player object to allow it to render it's content.
        /// </remarks>
        public override void Draw(GameTime gameTime)
        {

            //////////////////////////////////////////////////////

            GameRoot.BloomComponent.BeginDraw();

            // Draw entities. Sort by texture for better batching.
            mSpriteBatch.Begin(SpriteSortMode.Texture, BlendState.Additive);
            EntityManager.Draw(mSpriteBatch);
            mSpriteBatch.End();

            ///////////////////////////////////////////////////

            mSpriteBatch.Begin(SpriteSortMode.Deferred, BlendState.Additive);
            BackgroundGrid.Draw(mSpriteBatch);
            ParticleManager.Draw(mSpriteBatch);
            mSpriteBatch.End();

            ////////////////////////////////////////////////////

            mSpriteBatch.Begin();

            ScreenPad.Draw(gameTime, mSpriteBatch);

            mSpriteBatch.End();

            base.Draw(gameTime);

            // I want to end it here, but the call to base just calls the virtual Draw method for the Game clas which has no functionality at all

            //////////////////////////////////////////////////

            // Draw user interface
            mSpriteBatch.Begin(SpriteSortMode.Deferred, BlendState.Additive);

            mSpriteBatch.DrawString(Art.Font, "Lives: " + PlayerStatus.Lives, new Vector2(5), Color.White);
            DrawRightAlignedString("Score: " + PlayerStatus.Score, 5);
            DrawRightAlignedString("Multiplier: " + PlayerStatus.Multiplier, 35);

            if (PlayerStatus.IsGameOver)
            {
                string text = "Game Over\n" +
                    "Your Score: " + PlayerStatus.Score + "\n" +
                    "High Score: " + PlayerStatus.HighScore;

                Vector2 textSize = Art.Font.MeasureString(text);
                mSpriteBatch.DrawString(Art.Font, text, ScreenSize / 2 - textSize / 2, Color.White);
            }

            mSpriteBatch.End();

            // If the game is transitioning on or off, fade it out to black.
            if (TransitionPosition > 0)
                ScreenManager.FadeBackBufferToBlack(1f - TransitionAlpha);
        }

        private void DrawRightAlignedString(string text, float y)
        {
            var textWidth = Art.Font.MeasureString(text).X;
            mSpriteBatch.DrawString(Art.Font, text, new Vector2(ScreenSize.X - textWidth - 5, y), Color.White);
        }

        #endregion

        #region Update/Input Handling

        /// <summary>
        /// Allows the game to run logic such as updating the level and
        /// checking for collisions.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        /// <remarks>
        /// Update logic is localised within the object being updated.
        /// </remarks>
        public override void Update(GameTime gameTime, bool otherScreenHasFocus, bool coveredByOtherScreen)
        {

            GameTime = gameTime;

            ScreenPad.Update();

            CurrentScreenPadState = ScreenPad.GetState();

            PlayerStatus.Update();
            EntityManager.Update();
            EnemySpawner.Update();
            ParticleManager.Update();
            BackgroundGrid.Update();

            base.Update(gameTime, otherScreenHasFocus, coveredByOtherScreen);
        }

        /// <summary>
        /// Allows the game to respond to user input. Unlike the Update method,
        /// this will only be called when the gameplay screen is active.
        /// </summary>
        /// <remarks>
        /// The gameplay screen only needs to handle generalised touch input
        /// and the use of the back button.
        /// </remarks>
        public override void HandleInput(InputState input)
        {
            if (input == null)
                throw new ArgumentNullException("input");
        }

        #endregion

        #region Event Handlers

        /// <summary>
        /// Event handler to capture when the application is deactivated.
        /// </summary>
        private void GameDeactivated(object sender, DeactivatedEventArgs e)
        {

        }

        /// <summary>
        /// Event handler to capture when the application is obscured.
        /// </summary>
        private void GameObscured(object sender, ObscuredEventArgs e)
        {

        }

        #endregion

    }
}

```

BloomComponent.cs

```
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace Vision
{
    public class BloomComponent : DrawableGameComponent
    {
        #region Fields

        SpriteBatch spriteBatch;

        Effect bloomExtractEffect;
        Effect bloomCombineEffect;
        Effect gaussianBlurEffect;

        RenderTarget2D sceneRenderTarget;
        RenderTarget2D renderTarget1;
        RenderTarget2D renderTarget2;

        // Choose what display settings the bloom should use.
        public BloomSettings Settings
        {
            get { return settings; }
            set { settings = value; }
        }

        BloomSettings settings = BloomSettings.PresetSettings[0];

        // Optionally displays one of the intermediate buffers used
        // by the bloom postprocess, so you can see exactly what is
        // being drawn into each rendertarget.
        public enum IntermediateBuffer
        {
            PreBloom,
            BlurredHorizontally,
            BlurredBothWays,
            FinalResult,
        }

        public IntermediateBuffer ShowBuffer
        {
            get { return showBuffer; }
            set { showBuffer = value; }
        }

        IntermediateBuffer showBuffer = IntermediateBuffer.FinalResult;
        private byte[] shaderCode;

        #endregion

        #region Initialization

        public BloomComponent(Game game) : base(game)
        {
            if (game == null)
                throw new ArgumentNullException("game");
        }

        /// <summary>
        /// Load your graphics content.
        /// </summary>
        protected override void LoadContent()
        {
            spriteBatch = new SpriteBatch(GraphicsDevice);

            var assembly = Assembly.GetExecutingAssembly();

            var stream = assembly.GetManifestResourceStream("Vision.Content.Shaders.BloomExtract.mgfxo");
            using (var ms = new MemoryStream())
            {
                stream.CopyTo(ms);
                shaderCode = ms.ToArray();
            }
            stream.Close();
            bloomExtractEffect = new Effect(GraphicsDevice, shaderCode);

            stream = assembly.GetManifestResourceStream("Vision.Content.Shaders.BloomCombine.mgfxo");
            using (var ms = new MemoryStream())
            {
                stream.CopyTo(ms);
                shaderCode = ms.ToArray();
            }
            stream.Close();
            bloomCombineEffect = new Effect(GraphicsDevice, shaderCode);

            stream = assembly.GetManifestResourceStream("Vision.Content.Shaders.GaussianBlur.mgfxo");
            using (var ms = new MemoryStream())
            {
                stream.CopyTo(ms);
                shaderCode = ms.ToArray();
            }
            stream.Close();
            gaussianBlurEffect = new Effect(GraphicsDevice, shaderCode);

            // Look up the resolution and format of our main backbuffer.
            PresentationParameters pp = GraphicsDevice.PresentationParameters;

            int width = pp.BackBufferWidth;
            int height = pp.BackBufferHeight;

            // Create a texture for rendering the main scene, prior to applying bloom.
            sceneRenderTarget = new RenderTarget2D(GraphicsDevice, width, height, false, SurfaceFormat.Color, pp.DepthStencilFormat, pp.MultiSampleCount, RenderTargetUsage.DiscardContents);

            // Create two rendertargets for the bloom processing. These are half the
            // size of the backbuffer, in order to minimize fillrate costs. Reducing
            // the resolution in this way doesn't hurt quality, because we are going
            // to be blurring the bloom images in any case.
            width /= 2;
            height /= 2;

            renderTarget1 = new RenderTarget2D(GraphicsDevice, width, height, false, SurfaceFormat.Color, DepthFormat.None);
            renderTarget2 = new RenderTarget2D(GraphicsDevice, width, height, false, SurfaceFormat.Color, DepthFormat.None);
        }

        /// <summary>
        /// Unload your graphics content.
        /// </summary>
        protected override void UnloadContent()
        {
            sceneRenderTarget.Dispose();
            renderTarget1.Dispose();
            renderTarget2.Dispose();
        }

        #endregion

        #region Draw

        /// <summary>
        /// This should be called at the very start of the scene rendering. The bloom
        /// component uses it to redirect drawing into its custom rendertarget, so it
        /// can capture the scene image in preparation for applying the bloom filter.
        /// </summary>
        public void BeginDraw()
        {
            if (Visible)
            {
                GraphicsDevice.SetRenderTarget(sceneRenderTarget);
            }
        }

        /// <summary>
        /// This is where it all happens. Grabs a scene that has already been rendered,
        /// and uses postprocess magic to add a glowing bloom effect over the top of it.
        /// </summary>
        public override void Draw(GameTime gameTime)
        {
            GraphicsDevice.SamplerStates[1] = SamplerState.LinearClamp;

            // Pass 1: draw the scene into rendertarget 1, using a
            // shader that extracts only the brightest parts of the image.
            bloomExtractEffect.Parameters["BloomThreshold"].SetValue(Settings.BloomThreshold);

            DrawFullscreenQuad(sceneRenderTarget, renderTarget1, bloomExtractEffect, IntermediateBuffer.PreBloom);

            // Pass 2: draw from rendertarget 1 into rendertarget 2,
            // using a shader to apply a horizontal gaussian blur filter.
            SetBlurEffectParameters(1.0f / (float)renderTarget1.Width, 0);

            DrawFullscreenQuad(renderTarget1, renderTarget2, gaussianBlurEffect, IntermediateBuffer.BlurredHorizontally);

            // Pass 3: draw from rendertarget 2 back into rendertarget 1,
            // using a shader to apply a vertical gaussian blur filter.
            SetBlurEffectParameters(0, 1.0f / (float)renderTarget1.Height);

            DrawFullscreenQuad(renderTarget2, renderTarget1, gaussianBlurEffect, IntermediateBuffer.BlurredBothWays);

            // Pass 4: draw both rendertarget 1 and the original scene
            // image back into the main backbuffer, using a shader that
            // combines them to produce the final bloomed result.
            GraphicsDevice.SetRenderTarget(null);

            EffectParameterCollection parameters = bloomCombineEffect.Parameters;

            parameters["BloomIntensity"].SetValue(Settings.BloomIntensity);
            parameters["BaseIntensity"].SetValue(Settings.BaseIntensity);
            parameters["BloomSaturation"].SetValue(Settings.BloomSaturation);
            parameters["BaseSaturation"].SetValue(Settings.BaseSaturation);

            GraphicsDevice.Textures[1] = sceneRenderTarget;

            DrawFullscreenQuad(renderTarget1, (int)GameplayScreen.ScreenSize.X, (int)GameplayScreen.ScreenSize.Y,
                               bloomCombineEffect,
                               IntermediateBuffer.FinalResult);
        }

        /// <summary>
        /// Helper for drawing a texture into a rendertarget, using
        /// a custom shader to apply postprocessing effects.
        /// </summary>
        void DrawFullscreenQuad(Texture2D texture, RenderTarget2D renderTarget,
                                Effect effect, IntermediateBuffer currentBuffer)
        {
            GraphicsDevice.SetRenderTarget(renderTarget);

            DrawFullscreenQuad(texture,
                               renderTarget.Width, renderTarget.Height,
                               effect, currentBuffer);
        }

        /// <summary>
        /// Helper for drawing a texture into the current rendertarget,
        /// using a custom shader to apply postprocessing effects.
        /// </summary>
        void DrawFullscreenQuad(Texture2D texture, int width, int height,
                                Effect effect, IntermediateBuffer currentBuffer)
        {
            // If the user has selected one of the show intermediate buffer options,
            // we still draw the quad to make sure the image will end up on the screen,
            // but might need to skip applying the custom pixel shader.
            if (showBuffer < currentBuffer)
            {
                effect = null;
            }

            spriteBatch.Begin(0, BlendState.Opaque, null, null, null, effect);
            spriteBatch.Draw(texture, new Rectangle(0, 0, width, height), Color.White);
            spriteBatch.End();
        }

        /// <summary>
        /// Computes sample weightings and texture coordinate offsets
        /// for one pass of a separable gaussian blur filter.
        /// </summary>
        void SetBlurEffectParameters(float dx, float dy)
        {
            // Look up the sample weight and offset effect parameters.
            EffectParameter weightsParameter, offsetsParameter;

            weightsParameter = gaussianBlurEffect.Parameters["weights"];
            offsetsParameter = gaussianBlurEffect.Parameters["offsets"];

            // Look up how many samples our gaussian blur effect supports.
            int sampleCount = weightsParameter.Elements.Count;

            // Create temporary arrays for computing our filter settings.
            float[] sampleWeights = new float[sampleCount];
            Vector2[] sampleOffsets = new Vector2[sampleCount];

            // The first sample always has a zero offset.
            sampleWeights[0] = ComputeGaussian(0);
            sampleOffsets[0] = new Vector2(0);

            // Maintain a sum of all the weighting values.
            float totalWeights = sampleWeights[0];

            // Add pairs of additional sample taps, positioned
            // along a line in both directions from the center.
            for (int i = 0; i < sampleCount / 2; i++)
            {
                // Store weights for the positive and negative taps.
                float weight = ComputeGaussian(i + 1);

                sampleWeights[i * 2 + 1] = weight;
                sampleWeights[i * 2 + 2] = weight;

                totalWeights += weight * 2;

                // To get the maximum amount of blurring from a limited number of
                // pixel shader samples, we take advantage of the bilinear filtering
                // hardware inside the texture fetch unit. If we position our texture
                // coordinates exactly halfway between two texels, the filtering unit
                // will average them for us, giving two samples for the price of one.
                // This allows us to step in units of two texels per sample, rather
                // than just one at a time. The 1.5 offset kicks things off by
                // positioning us nicely in between two texels.
                float sampleOffset = i * 2 + 1.5f;

                Vector2 delta = new Vector2(dx, dy) * sampleOffset;

                // Store texture coordinate offsets for the positive and negative taps.
                sampleOffsets[i * 2 + 1] = delta;
                sampleOffsets[i * 2 + 2] = -delta;
            }

            // Normalize the list of sample weightings, so they will always sum to one.
            for (int i = 0; i < sampleWeights.Length; i++)
            {
                sampleWeights[i] /= totalWeights;
            }

            // Tell the effect about our new filter settings.
            weightsParameter.SetValue(sampleWeights);
            offsetsParameter.SetValue(sampleOffsets);
        }

        /// <summary>
        /// Evaluates a single point on the gaussian falloff curve.
        /// Used for setting up the blur filter weightings.
        /// </summary>
        float ComputeGaussian(float n)
        {
            float theta = Settings.BlurAmount;

            return (float)((1.0 / Math.Sqrt(2 * Math.PI * theta)) *
                           Math.Exp(-(n * n) / (2 * theta * theta)));
        }

        #endregion
    }
}

```

Thanks in advance.

# Answer
> 0 votes
Upon closer inspection of the bloomComponent's draw method, I realised that when it gets called it re-renders the initial render target so stops the bloom from being applied. SO all I do is now call the draw method of the bloomcomponent to stop it. It seems to run very slow, but that is a different issue all together :-(

---
Tags: c#, 2d, monogame, bloom
---


title: How can I implement an RPG-maker style

text:
# Question
Title: How can I implement an RPG-maker style
I'm currently working with Phaser, making a game that's procedurally generated. I wanted to use some RPG maker art in my game (for reference, I'm using the RTP). I stumbled across this article, which breaks down how auto tiles work. I also stumbled across this answer which links to another article that explains auto tiling.

Here's the thing, I have no idea how I would implement something like this. I'm sure I would have to keep track of which tile sets can connect to which other tilesets (ie, some tiles have grass on the outside, and sand on the inside, so in this example I'd have to note that "grass" tiles were the outer tiles).

I've made a map generator, and I wanted to make seamless connections between my tile areas. For example, the brown areas would be "dense" areas (forests, caves, etc). The purple areas would be stone floors, and the green area is the grass. There is a tileset that works very well for things like this:

So I would like to use the top left grass, and the third tile set, stone, which connects to the grass.

What sorts of things would I have to consider when implementing auto tiling using these sorts of tilesets, and is there an algorithm I can look at to implement?

# Answer
> 1 votes
I have implemented this(using the RTP) in a simple(but quite tedious) way.

I took a list of all neighbors for the current cell, and with a lot of `if` statements I drew the tile as 4 smaller/quarter tiles.

For me this method lead to some barely visible errors, but they can be resolved by testing for some edge-cases and correcting accordingly.

If you look at the source images and the resulting image in the RPG maker, you should be able to do this(perhaps with some trial-and-error) with `if` statements, identifying what the current case is for the given quarter tile and drawing accordingly.

This method can be further improved and made less tedious with bitmasks(as mentioned by jzx).

---

Answering your comment:

By rendering only quarter tiles, the possibilities decrease dramatically.

You shouldn't have to handle tiles on tiles, as they should be on a different layers alphablended or keycolored on each other.

Also, I don't see why would you need built-in neighbors, but that could be handled separately in the neighbor calculation, perhaps using some sort of maps(list of pairs that blend).

The map is usually static, and the images are low-res, so no need to worry about performance.

---
Tags: tiles, tilemap, phaser, rpg-maker-vx, tile-bitmasking
---


# Question
Title: How do I render an object's position trail of a constant length?
I want to show a trail of the last points that the object has been in, but I want that trail to *always be a certain length*, regardless of the object's speed. How can I do that?

---

At the moment, I have an array of 100 points. When it gets full, I overwrite the oldest one.

However, if the object is staying still (or moves slowly), the old points are overwritten and the trail becomes shorter. I want the the trail to *always be 100 pixels total length*.

# Answer
There's a couple ways to do this. One way would be to store a dynamic number of previous positions instead of 100, and only throw old points away when the are beyond the length you want to show. A better way to do this though would probably be to store the last 100 evenly spaced positions where each position is totalDistance / 100 units apart. Basically, where you used to just put the player's position into the array, if the distance from the last point to the new point was 3/100 of the total distance you'd want to show, you'd calculate the 3 points at that fixed length interval from the old position to the new position and put them into your array, removing old points to make room if necessary. Hopefully that makes sense, let me know if not.
> 0 votes

---
Tags: 2d, graphic-effects
---