title: Unity2D tall grass

text:
# Question
Title: Unity2D tall grass
I'm using Unity to create a 2D top-down game. Everything has been great so far, but I have come into a problem that I fail to solve properly.

I want to implement "tall grass areas" where part of the character will be occluded.

A visual example:

I though about making the tall grass by layers, but that would create a LOT of game objects, and the transition as the character moves up won't be smooth enough.

Any idea about how could I approach this? I thought that maybe using shaders I could achieve something like this, but my knowlegde on shaders is very very limited, so I don't even know if such thing is possible.

# Answer
I finally found a satisfying solution! @Thebluefish comment pointed me to the right direction with masks.

The idea is to use a shader that draws the character in two passes:

* In the first pass the character is rendered normally, BUT being completely behind the bushes.
* In the second pass I draw it again, using a mask that olny draws the top part of the character, on top of the bushes.

This is done even when the chatacter is not inside the bushes. This way I don't have to detect collisions agains the bushes, and also it makes the transition inside the bush smooth on limit cases like this one:

The half of the character that is outside the bush is rendered in the first pass. The other half will be completely occluded by the bush.

In the second pass the masked character will be rendered again. The part outside the bush will remain the same, but the part inside the bush will be rendered on top with the mask on top of the bush, making it look like its inside the bush.
> 0 votes

# Answer
I agree with @Christian (though I wouldn't call it a hack). Detect the condition when the object should look different and then just draw it different. Every single thing in the game doesn't have to be a "model" of how it works in "nature". That's a mistake I've made many times and so it's become something of a mantra for me. Ask yourself this: what would you gain by having the bush occlude the player "realistically" instead of just drawing the player the way they should look? I put this in quotes, because in trying to imagine what this would look like I think the layered occlusion approach may actually look inferior.

If your concern with @Christian's approach is in managing the "potentially unbounded" list of little things you have to check each frame, this is another mistake I've made many times. I'd recommend you "just go with it" for now and periodically check how long the list has actually gotten--**and whether it's actually become a problem**. One of two things will happen. Either it hasn't become a problem, in which case--why are you trying to solve it? Or it has and you need to engineer a (minimal) solution to solve it. Don't try to *solve* it by *simulating* it.
> 1 votes

# Answer
You can detect wether or not character is in the grass. Then draw only top-half of character.
> -1 votes

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


title: Texture2D ignored by GC

text:
# Question
Title: Texture2D ignored by GC
I loaded my textures with FromStream method and I noticed a problem that those textures are being ignored by garbage collector. I even nulled them, called dispose on them and tried to force garbage collector - they're still in the memory. Any ideas why this might be happening?

# Answer
I forgot to call Dispose() on texture loaded with FromStream().
> 1 votes

---
Tags: monogame
---


# Question
Title: How can I format the number of digits my stopwatch shows?
I have made a stopwatch that displays the time in seconds during my game in libgdx. At the moment it shows a bunch of digits after the decimal point as it runs. Does anyone know how to change it so it only shows the time to 3 decimal points?

Here is my Timer class:

```
public class Timer {
SpriteBatch sb;
private BitmapFont font;
private float deltaTime = 0;
CharSequence str;

public Timer() {
    font = TextureManager.font;
    sb = new SpriteBatch();

}

public void drawTime(SpriteBatch sb) {
    deltaTime += Gdx.graphics.getDeltaTime();
    str = Float.toString(deltaTime);
    font.draw(sb, str, 240 / 2 - 60, 400 / 2);
}

}

```

Thanks

# Answer
> 0 votes
Since your value is a float, you can just pass it to String.format

`String.format("%.3f", floatValue);`

---
Tags: java, libgdx, timer
---


title: Using Box2D for soccer physics

text:
# Question
Title: Using Box2D for soccer physics
I've learned quite a bit of Box2D and I've succeeded basic stuff concluding ball physics.

I want to implement 'opposing forces', as the character kicks the ball with a certain strength, with the leg having a certain mass, in a certain velocity. Basically, I don't want the leg to be controlled by Box2D's world, but to be counted as an object that I (the programmer) can move freely without the `b2World::Step()` method affecting it (as the player controls the leg).

How do I do so? I'd be happy to have a link, as I can't seem to find one.

# Answer
> 1 votes
Box2d has a body type that fits your need: KinematicBody. Kinematic bodies aren't affected by collisions, you programmatically set their velocity from outside of Box2d. Also you can directly set their positions, instead of manipulating their speed, though it's not recommended.

In case when you set kinematic bodies' speed, their position is still controlled by `b2World::Step()`, but they aren't affected by other bodies, though other bodies are affected by them - seems like what you want.

Here's a nice tutorial on that: http://www.emanueleferonato.com/2012/05/11/understanding-box2d-kinematic-bodies/

---
Tags: box2d, physics, sfml
---


# Question
Title: Is the rendering of distorted point clouds more complex?
I have two point clouds of *n* points:

1. A dense ball-shape point cloud with many points inside
2. A spherical point cloud with points on its surface.

Is there (really) any difference between rendering (complexity/time) of these two point clouds?

How does the distortion of points affect the complexity of the rasterisation process?

# Answer
No, from rasterization point of view both are the same. GPU processes all points independently and doesn't care about their position.
> 2 votes

# Answer
In theory, it will take the same time to render regardless. However, if a point occluded points in the back, then some pixels may be discarded before they are rasterized (because they failed the depth test), and I can imagine that that would be slightly faster.
> 2 votes

---
Tags: 3d, mathematics, rendering, point-cloud, rasterization
---


# Question
Title: Is using the student version of 3DS Max and Unity3d legal?
I am developing an indie game together with my friend using Unity3D engine. I bought "Silo 3D" for modeling two month ago and for texturing I use 3D coat. We plan to sell our game in the future. For the animations I work with 3DS max (only animation part).

My question is, can I work with a students license? The license for the original version is too expensive for me. I am still at the university and I can not buy the 3DS Max license which costs 4000 €. As an alternative I have the choice beetween Blender (can´t work with this software and don't have time to invest for learning a new program) and Truespace (can´t export fbx animation and specially with bones) so for me, 3DS Max is the best choice to be effective and quick.

Is it possible to prove it when I export my fbx characters from 3DS Max to Unity3D? I mean can they find out that I have used the students license of 3DS Max for the animations after the release of the game? Maybe with help of DRM?

Can I solve that problem when I export the fbx from 3DS Max to Blender and after that export the same fbx to Unity3D?

# Answer
Forget all that expensive software. Either it's expensive, and you take a hit, or you get used to high-end software, and can't use anything else.

Like I said in my comments, just start learning Blender 3D. It's actually not that bad, the interface just takes a little while to get used to.

If you already know concepts like materials, textures, spot lighting, lofting, etc. then you'll feel right at home.
> 9 votes

# Answer
Yes, and No.

Yes it is legal if you won't publish it. No it is not legal if you'll publish it.

Simple as that.
> 4 votes

# Answer
There's a low cost version of Maya on steam "Maya LT" available for a subscription of $30 per month.

Blender may seem a good alternative but at current state its not good for any real animation work that can be used in a commercial game.

Blender is great for rendering movies or still scenes but sucks very hard at exporting animation and other things for use in Unity or UE4. Its alright for static meshes though.

If you are willing to pay $30 for Maya LT you'll save youself a fortune of headache you'll have while using blender
> -1 votes

---
Tags: unity, legal, 3dsmax
---


# Question
Title: Questions about scaling in a 2d game in unity
Okay, so:

I am making an android game. I want everything to scale to the size of the screen I'm using. Further, my static background needs to scale (as well as every other object), but if the aspect ratio is less than the AR of the background image I want the image to be cut off at the edges.

Further, I have a game object I need to always be at the corner of the screen. I'm guessing I should use a script to determine the width of the screen and place it a few coordinates up and right of that on start?

The game is only in landscape mode if that matters. How do I go about this? I previously had the background as a plane with an image on it but it didn't take up the whole screen and I think it might not be the right thing to do? Maybe use a quad?

How do I test to make sure that this works? I only have my one android phone to test it on.

# Answer
> 0 votes
For the gameObject to always stay in the corner set it's position to camera.ScreenToWorldPoint(new Vector3(0, 0, -camera.gameobject.transform.position.z)) - new Vector3(yourObjectsizeX / 2, yourObjectsizeY / 2,0) \[this to make sure the whole button is visible\]

Regarding the scaling, I did a while back such a scale to the background by defining the width and it's maximum size and after scaling on Y respective to the new X. Ex. you have a background of 2048 X 1536 and background size 20.48 X 15.36. For x= 1024 you'll have y=768 hence your background will scale to 10.24 X 7.68.

Hope this helps

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


# Question
Title: Is there a way to manipulate a pixel Array on the GPU?
I'm currently working on a 2D-Game and i want to draw and calculate the whole screen myself through a pixel array. I'm programming in C++, using SDL 2 and OpenGL specifically a OpenGL Texture which is generated through my manipulated pixel array. My rendering System basically works like this:

1. Pixelvalues from a spritesheet are getting put into the pixel array (those are all the tiles that should be rendered).
2. The RGB values of every pixel are getting multiplied by a certain value to get the effect of lighting.
3. The manipulated pixel array is being passed to OpenGL to generate a Texture which is then drawn to the screen.

And the problem is that especially the lighting calculations cost a lot of time since its all being calculated on the CPU and even though all i'm doing is drawing the very basic things my FPS is maxed out at like 160 (on a quite good computer). And after profiling my code i also got to the conclusion that mostly the lighting function takes up a lot of time.

Lighting function:

```
    void PixelRenderer::applyLight(Uint32& color, Uint32 factor){
    Uint32 red = (((color >> 16) & 0xff)* factor) >> 8;
    Uint32 green = (((color >> 8) & 0xff)* factor) >> 8;
    Uint32 blue = (((color) & 0xff)* factor) >> 8;

    if (red > 255) red = 255;
    if (green > 255) green = 255;
    if (blue > 255) blue = 255;

    color = (color & 0xFF000000) | red << 16 | green << 8 | blue;
}

```

and this is done for every single pixel on the screen (1024\*576 resolution and 32x32 tileSize)

So my question basically is if theres any way i can do those calculations on the GPU to improve my performance.

# Answer
> 1 votes
Yes!

This is exactly the sort of thing that can be done very well on the GPU, since it is processing one pixel at a time.

There's two ways you might address this:

1. Incorporate this processing directly in your shader, so you don't need to preprocess the texture at all. just process it on the fly as you apply it. To do this, you'd incorporate your applyLight calculations into the fragment shader for the thing you're texturing.
2. Preprocess it as you do now, but on the GPU.

I'd probably lean towards Way #1, as the calculations seem not very expensive.

For interest, though, I'll sketch out Way #2, too.

**Way #2, Preprocess on GPU**

You'll need to write an OpenGL program (vertex & fragment shaders).

The general approach will be:

* Create a geometry of two triangles to fill the screen.
* Vertex shader pass-through
* Fragment shader looks almost identical to your applyLight method, but using floating point and four-element vectors.
* Render to a frame buffer object
* The pixel data of the frame buffer object can be used directly as a texture next.

I'm attaching an excerpt of my one code which deals with creating an OpenGL frame buffer object; it's not standalone, I'm afraid, but perhaps provides a good sketch of how to get your frame buffer going.

```
MeFrameBufferGl::MeFrameBufferGl(int width, int height, EMeTextureKind kind) : MeObjectBase("MeFrameBufferGl")
{
    this->width = width;
    this->height = height;

    this->colorTexture = // created with glTexImage2D, width, height
    this->depthTexture = // created with glTexImage2D, width, height

    glGenFramebuffers(1, &this->frameBufferName);
    glBindFramebuffer(GL_FRAMEBUFFER, this->frameBufferName);

    //Attach 2D texture to this FBO
    GLuint colorTextureName = this->colorTexture->getGlName();
    GLuint depthTextureName = this->depthTexture->getGlName();
    glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, colorTextureName, 0);
    SHOW_GL_ERROR;
    glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, depthTextureName, 0);
    SHOW_GL_ERROR;

    //-------------------------
    //Does the GPU support current FBO configuration?
    GLenum status;
    status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
    switch(status)
    {
        case GL_FRAMEBUFFER_COMPLETE:
            meLogInfo("framebuffer is good");
            break;
        default:
            meLogError("framebuffer is bad: 0x%04x %d\n", status, status);
            break;
    }

    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
}

```

---
Tags: opengl, c++, performance, gpu, pixel
---


# Question
Title: OpenGL memory optimization and batching technique pitfalls
I'm studying OpenGL optimization techniques. What I'd like to achieve is to emulate as closely as possible Mantle/DirectX12 programming patterns (aggressive batching, flexible memory handling, complex pipelines) with current OpenGL API. The assumption I'm making here is that hardware behavior is almost the same, with the OpenGL layer being a bit restrictive and not matching accurately the underlying architecture.

I'm considering the optimization technique proposed here:

http://www.openglsuperbible.com/2013/10/16/the-road-to-one-million-draws/

The article suggests allocating a giant buffer and writing a custom allocator to fill it with vertex, instance and texture data, then drawing it with glMultiDrawElementsIndirect. Immutable storage, triple buffering and persistent mapping can also be used for best streaming performance (see http://www.bfilipek.com/2015/01/persistent-mapped-buffers-in-opengl.html).

That seems pretty close to my goal, however I have some doubts:

1. I read that it's better not to overuse GPU memory on PC because it's also needed by other applications. However, when using this technique with dynamically loaded, continuously changing scenes (e.g. very large tiled worlds) we end up using much more memory than actually needed because we can't predict how much data we'll need to store. Is this a real concern? If yes, how can I address the problem?
2. View frustum and occlusion culling force you to continuously rewrite instancing and command data. Is this really good? Does decreased CPU load reward time spent copying around memory chunks? Does memory bandwidth significantly impact performance in this case?
3. Is the "one shader for all materials" method based on subroutines more efficient (higher frame rate with same input data) than modifying the program pipeline? What's the cost of binding a different pipeline or switching a shader in the current pipeline?

# Answer
> 5 votes
> However, when using this technique with dynamically loaded, continuously changing scenes (e.g. very large tiled worlds)

You wouldn't use this for the level geometry.

Your chunks should map in their own static buffers on demand, just like you normally would.

> View frustum and occlusion culling force you to continuously rewrite instancing and command data. Is this really good?

You have to constantly rewrite that data *anyway* for your dynamic objects, so you're hardly losing anything with this technique.

The streaming persistent buffers remove latency; they don't add additional copying. Remember that the driver is allocating GPU memory repeatedly for buffers that you are discarding (i.e. the old recommended practice) so there's already a lot more copying going on than might be apparent. The persistent streaming buffers just put you in control of that rather than making it magical driver shenanigans.

> Is the "one shader for all materials" method based on subroutines more efficient (higher frame rate with same input data) than modifying the program pipeline? What's the cost of binding a different pipeline or switching a shader in the current pipeline?

If you're just targeting current/modern hardware (with latest drivers), subroutines should be faster than swapping shader programs. A subroutine should be implemented as a simple indirection in the shader machine code. You want the subroutine selection to be as uniform as possible to ensure maximum GPU shader core throughput; same as with any uber-shader approach, really, except that subroutines will be faster than branching (usually).

Switching shader programs involves various pipeline state changes, which can be complex commands. The cost is not fixed by the spec so it of course will vary by hardware. A single GPU shader cluster can only run one program at a time, so on "old" hardware a shader change can involve an entire pipeline stall, while recent hardware can often run a handful of different shaders at the same time (though the driver may not allow a single application to take advantage of this).

Profile your specific game and specific content on target hardware to find out for sure.

---
Tags: opengl, performance, optimization
---


title: Update Loop in libGDX

text:
# Question
Title: Update Loop in libGDX
I have a screen class in libGDX. In this screen, I want to change a sprite's texture a certain number of times before the screen changes to a different screen class. I tried having a for loop in the render method, but that obviously didn't work as render is constantly called.

Can anyone help?

# Answer
> 1 votes
Try this

```
private long time;

public void show(){
//...
        time = System.currentTimeMillis();

}
public void draw(){
//...
       if(System.currentTimeMillis()>time+3000){
            time = System.currentTimeMillis();
            System.out.println("called after 3 seconds");
            //change texture
        }
}

```

So you can change your `Sprite`'s `Texture` every 3 seconds.

---
Tags: java, libgdx
---


# Question
Title: Unintended sliding blocks Unity (5) physics
A game I'm working on right now relies on the Unity physics system for collisions, gravity etc. This all works well except for one strange thing. When an explosive is placed on a stone cube, it'll slide right off.

A video displaying the sliding behavior: https://www.dropbox.com/s/lr6lhnn30x61tvf/Unity%202015-02-19%2013-41-39-54.avi?dl=0

The stone gameobject settings: http://puu.sh/g3BFn/c15483b8ea.jpg The explosive has the same settings except for that the Mass is 1.

What could cause this weird sliding and how can it be fixed?

# Answer
> 2 votes
I belive there is no friction. Add a physic material with a friction.

---
Tags: unity, physics
---


# Question
Title: Animation fails due to a NullPointerException which I'm certain shouldn't be thrown (LibGDX / Java)
What the title says basically. I've been stuck on this error for a few hours I got it to work earlier but I honestly can't see why its failing now (ctrl + z'd back to the working stage). Here's my code:

```
public class Animator {
    private Animation animation;
    private TextureRegion[] walkFrames;
    private TextureRegion[] jumpFrames;
    private TextureRegion[] enemyFrames;
    private Texture jumpSheet;
    private Texture walkSheet;
    private Texture enemySheet;
    private TextureRegion currentFrame;
    private Animation enemyAnimation;
    private Animation jumpAnimation;
    private Animation walkAnimation;
    private TextureRegion[][] animationType;
    private TextureRegion[] animateJump;
    private TextureRegion[] animateWalk;
    private TextureRegion[] animateEnemy;
    private GameObject object;
    private float stateTime;

    public Animator(GameObject object) {
        this.object = object;
        jumpSheet = new Texture(Gdx.files.internal("jumpsheet.png"));
        walkSheet = new Texture(Gdx.files.internal("walksheet.png"));
        enemySheet = new Texture(Gdx.files.internal("enemySheet.png"));
        enemyAnimation = animate(1, 4, enemySheet);
        jumpAnimation = animate(1, 7, jumpSheet);
        walkAnimation = animate(1, 4, walkSheet);
        stateTime = 0f;
    }

    public Animation animate(int rows, int cols, Texture spriteSheet) {
        TextureRegion[] frames = new TextureRegion[cols * rows];
        animationType = TextureRegion.split(spriteSheet, spriteSheet.getWidth()
                / cols, spriteSheet.getHeight() / rows);
        int index = 0;
        for (int i = 0; i < frameRows; i++) {
            for (int j = 0; j < frameCols; j++) {
                frames[index++] = animationType[i][j];
            }
        }
        animation = new Animation(0.25f, frames);
        return animation;
    }

    public void render(SpriteBatch batch) {
        stateTime += Gdx.graphics.getDeltaTime();
        if (object.getType() == ObjectType.PLAYER
                && object.getState() == ObjectState.JUMPING) {
            currentFrame = jumpAnimation.getKeyFrame(stateTime, true);
        } else if (object.getType() == ObjectType.PLAYER
                && object.getState() == ObjectState.NORMAL) {
            currentFrame = walkAnimation.getKeyFrame(stateTime, true);
        } else {
            currentFrame = enemyAnimation.getKeyFrame(stateTime, true);
        }
        batch.draw(currentFrame, object.getxPos(), object.getyPos()); // Null Pointer
    }
}

```

I get the NullPointer on the last line, and if I run in debug mode with breakpoints it tells me that currentFrame is null (at every stage of the if statement). Can anyone see why?

Any help is highly appreciated, thanks.

# Answer
> 1 votes
`assert` is your friend, if you get NullPointerExceptions that originates in your code (and not deeper into nested calls) then one of your objects is null, no matter how unlikely or impossible it seems.

You have to assume that all assumptions are wrong and either step through the code and checking variables as you go, or - if that is hard due to the program - add `assert(x != null)` in your code

```
public void render(SpriteBatch batch) {
    assert(batch != null);
    stateTime += Gdx.graphics.getDeltaTime();
    assert(object != null);
    if (object.getType() == ObjectType.PLAYER
            && object.getState() == ObjectState.JUMPING) {
        assert(jumpAnimation != null);
        currentFrame = jumpAnimation.getKeyFrame(stateTime, true);
    } else if (object.getType() == ObjectType.PLAYER
            && object.getState() == ObjectState.NORMAL) {
        assert(currentFrame != null);
        currentFrame = walkAnimation.getKeyFrame(stateTime, true);
    } else {
        assert(enemyAnimation != null);
        currentFrame = enemyAnimation.getKeyFrame(stateTime, true);
    }
    batch.draw(currentFrame, object.getxPos(), object.getyPos()); // Null Pointer
}

```

If you would like more details you will have to post the exceptions stack trace, if those asserts don't catch your issue you are probably misreading the stack trace.

---
Tags: java, 2d, android, libgdx, animation
---


# Question
Title: Rotating an object continously with OnMouseDown
I have a script that works but it does not do what I want it to do. My script makes an object rotate on when another is clicked. However, I want the object to continuously rotate until I click on the other object again. Right now when I click it rotates just a bit and stops.

Here is my script:

```
 public class Rotate : MonoBehaviour {
    public float speed =50f;
    public GameObject target;

    public void OnMouseDown(){
       target.transform.Rotate (new Vector3(0, Time.deltaTime, 0) * speed);
    }
 }

```

How can I make the object rotate continuously until I click it again?

# Answer
Don't Rotate() in OnMouseDown(). Instead, have OnMouseDown() set an isRotating boolean value and then Rotate() in Update(). Something like:

```
bool isRotating;
void Update() {
  if (isRotating) {
    target.transform.Rotate(etc);
  }
}
void OnMouseDown() {
  isRotating != isRotating;
}

```
> 2 votes

# Answer
Rotate will rotate it once by the amount specified. You must rotate it yourself every frame.

```
public float rotationSpeed = 50f;
public GameObject target;
private bool rotate = false;

void OnMouseDown() {
    rotate = !rotate; //this line toggles the bool "rotate" every time the object is clicked
}

void Update() {
    if(rotate) {
        target.transform.Rotate (new Vector3(0, Time.deltaTime, 0) * rotationSpeed );
    }
}

```
> 1 votes

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


# Question
Title: Should independent game developers target older hardware?
A developer I work with tells me that indie developers should target hardware that is around six or more years old (at max settings). I get the idea that one should allow everyone that wants to play their game to play it at a runnable framerate, regardless of how old their hardware is, but should indie developers limit themselves to using a low-poly art style, or make their games with older hardware in mind, mainly because "most people that play indie games have old hardware?"

Is there any reason to allow your game to run at max settings for very old hardware, even though it would lower the graphical possibilities for people with newer hardware?

**Are there any statistics that show that games that reach their upper graphical limits easily on older hardware are more successful than games that push their upper graphical limits higher at the expensive of a 'less-than-the-best' experience for players on older hardware?**

Any insight on this will be greatly appreciated.

# Answer
In this era old hardware has become a misnomer. Old hardware is not necessary slow. 6 years old is 2009 and DirectX11 was already existing. We still don't have much newer today.

You need to consider two things:

* features
* power

## features

This is the level of instructions that the hardware will support, DirectX9,10,11, or OpenGL something (this depends on the drivers). And the CPU instruction set: SSE4, AVX..

This is the biggest headache usually in developpment, scalability facing those is harder than scalability facing power. DirectX9 had something called `technique` in the `.fx` files to fall back, for both points. But for CPU instructions you need multiple executables, or large branching sections in your program. Or don't use them.
Luckily today, even 6 years is a short period and you will have access to about everything you need even on "old" hardware.

## power

This is the point that should scale, on **todays** machine, and not legacies machine. A high end of 2009 potentially features a geForce GTX280, this is very powerful, and much more powerful than your low end AMD A6-3650 APU or something.

One need to understand the gigantic gap of performance between low end, and high end, of today's machine. Because it largely exceeds the gap of performance of your 6 year range machines on the high end scale.

So its not a consideration of market regarding renewal, its a consideration of market regarding original buying budget. And if you need to target today's laptops or low end Desktops, you are going to need to scale anyway, and way more than you think.

Try to care about resolution, pixel fillrate and graphics memory bandwidth. You play on those factors thanks to the number of screen passes, the width of your Gbuffer if you have deferred shading (very costly on low end machines), the resolution of your textures and their quantity present on screen at any given time t... Polygon richness will not be an issue unless you are targeting 2002 hardware. Shader ALU/FPU complexity will not be a problem either, unless you target 2005/2006 hardware.
> 21 votes

# Answer
I can't remember where I first heard it, but that's an old rule of thumb that doesn't hold up to much critical thought. Truly, it comes down to business objectives. If you don't plan on selling the game, it doesn't matter.

The fact is, the more hardware you can support the bigger your potential market is. However, most independent developers aren't going to have the resources to support anywhere near cutting edge hardware anyway, because in order to take advantage of said hardware they're going to have to expend a fair amount on *content*. Any independent developer that needs to worry about that usually has the resources to find out what system specs they need to target, and that's likely information you can buy. Steam, for example, collects those statistics and likely resells it to developers.
> 10 votes

# Answer
As a general rule, the wider the variety of hardware on which any program will run, the more opportunities you'll have to sell a copy. How much variety you can support depends a lot on the game. A game like Dwarf Fortress can easily be very scalable, both in terms of processing requirements and graphics. An FPS with realistic physics like Amnesia not so much. My suggestion would be to write your game so that it can be run on the widest possible array of hardware and still give a good experience. You don't necessarily have to support it all right away, but being able to reconfigure it for newer/older/just-plain-different hardware easily will pay dividends as your fanbase grows and as technology progresses.

There are two things that will make your life a lot easier when it comes to making your game run on a wide array of devices, and they have little to do with the age of the hardware you target (at least directly):

1) If possible, split the backend from the frontend. If the part that does the math about which pieces are doing what, where has a well-defined interface for passing that information to the part that displays it on the screen and takes user input, then you can more easily adjust one (usually the frontend) to new hardware without having to mess with the other. If written this way, many kinds of games could be given frontends ranging from top-of-the-line 3d graphics, to animated sprites on a webpage, to pure ASCII text characters. At that point, you can choose which to implement based on who you think will buy the game now. And you can expand to new output schemes as people show interest -- without having to mess with the core of the game.

2) As much as possible, write portable code. Depending on the specific behaviour of DirectX 9.3c or whatever may let you get it done faster, but when you realise that you should put out a version for Android, you're going to have to redo a lot of work. Picking libraries and languages that aren't dependent on a single vendor, and that follow open and well-defined standards will seriously reduce your workload in the long run. Remember: writing a program is usually a tiny portion of the work compared to maintaining the program. (Unless you're going for the "planned obsolescence" business model, but that's not likely to get you a big fanbase in the long run.)
> 2 votes

---
Tags: marketing, business
---


# Question
Title: StartCoroutine inside TriggerOnEnter2D isn't working
I am new to this, but I need help with a CSharp script. I need to collide with the desired object, pass the game to be 1.6 in TimeScale. After passing 8 seconds in the game, change back to 1 TimeScale, and try to call a Coroutine does not work. I really appreciate your help!

The code:

```
void TimeSet(){
    Time.timeScale = 1.6f;
}

IEnumerator Normal (){
    yield return new WaitForSeconds(8f);
    Time.timeScale = 1f;
    Debug.Log ("Ready");
}

void OnTriggerEnter2D(){
    TimeSet ();
    StartCoroutine ("Normal");
}

```

# Answer
> 1 votes
OnTriggerEnter2D is supposed to have a `Collider2D` parameter. As yours have none the method signature is different and that's probably why it's never called when a collision occurs.

Also as explained in the documentation I would strongly suggest to use `StartCoroutine` in it's method parameter form instead of using it with a string parameter.

I hope it helps.

**EDIT**

You should try by changing your `OnTriggerEnter2D` by:

```
void OnTriggerEnter2D(Collider2D othercollider)
{
    TimeSet ();
    StartCoroutine (Normal());
}

```

Also be sure that one of your game objects has a `RigidBody2D`

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


# Question
Title: Where to start developing a 2D puzzle game
I would like to start developing a 2D puzzle games, much like sudoku for example. I would like to publish it on Facebook and on gaming websites, like miniclip, agame, kongregate. The game should have a premium part for which people can pay. In a second stage I would like to make the game available for mobile devices, Android and Apple and also offer a premium paid section. I would like to accomplish this with one code base.

First of all is this possible? Secondly at which platforms should I look: Unity, HTML5 frameworks, Construct2, ...

# Answer
I strongly suggest you to start working on your first game to get enough skills and global knowledge on video game development before wondering about platforms or selling plans.

Read about video game development (through books, internet...). Learn how to make a game. Fail at making a dozen of games. And only then you'll probably be confident and skilled enough to start thinking about where to release your game and how to sell it.
> 1 votes

# Answer
It's definitely possible to have a common code base if you use cross-platform technologies such as Unity or HTML5 frameworks. Though you'll always need some platform-specific work (Facebook app creation, distribution on the app stores, integration with the payment services,...)

Choosing the framework highly depends on your skills and preferences. If you like GUI-oriented tools, Unity might be the right choice for you, especially because it's quite popular and active right now. If you are more code-oriented, you might prefer some lower lever HTML5 frameworks (check http://html5gameengine.com/)
> 1 votes

---
Tags: unity, 2d, javascript, html5, construct-2
---


# Question
Title: How do I "reset" the color in OpenGl ES 1.0/1.1?
In my 2D game I use `glColor4f()` to set the color and draw my screen border rectangles but when I try to start drawing my game objects, made up of a texture on a rectangular "quad", using `GL10.GL_TEXTURE_2D`, `GL10.GL_VERTEX_ARRAY` and `GL10.GL_TEXTURE_COORD_ARRAY` no `GL10.GL_COLOR_ARRAY`, it uses the "current color" from `glColor4f()`.

My question is what do I need to set/reset in OpenGl ES to re-enable it to use the colors from the texture when I try to draw them? If I comment out the border drawing, so `glColor4f()` never gets called, the colors are fine.

I'm not using double buffering. I read that once you set the color with `glColor4f()` it stays set, unless you possibly use `glPushAttrib(GL_CURRENT_BIT)`, but I heard that that's expensive, time wise.

# Answer
Full explanation:

OpenGL's (and GLES') default behavior is to modulate the currently set color with the texture with a simple multiplication. That is, it multiplies the color with the value at the texture.

The default color is white. White is defined as `<1.0f, 1.0f, 1.0f, 1.0f>`. One times anything is itself, so modulating white with the texture color results in the texture color itself.

If you were to change the color to red (`<1.0f, 0.0f, 0.0f, 1.0f>`) then the result would be red times the texture color; since zero times anything is zero, the result would be `<1.0f * Texture.Red, 0.0f * Texture.Green, 0.0f * Texture.Blue, 1.0f * Texture.Alpha> = <Texture.Red, 0.0f, 0.0f, Texture.Alpha>`. In other words, you'd see just the red component of the texture color at the texture's opacity.

That's useful behavior to have for some effects, especially back before more complicated masking and blending operations became available or the advent of shaders. The effect doesn't necessarily look all that good, but it works. (The problem is that you'd lose all the countours of green and blue objects, so what you probably want is a color modulation of luminocity values computed from all three color channels.)

You can't get too much control without switching to GLES 2+ and using shaders.

The result of all this math on your situation is what's already been suggested: reset GL's current color to white before drawing in order to see textured objects 'properly'.
> 2 votes

# Answer
You should set the color to white `glColor4f(1,1,1,1)` before drawing textured geometry.
> 1 votes

# Answer
Quoting the author:

---

I got it working:

The textures are made up of several colors. I went ahead and changed it to use a color array, and not use `glColor4f()`, when drawing the solid color borders, adding them with `glColorPointer()` and in `beginDrawing()` it does `glEnableClientState()` or `glDisableClientState()` with `GL10.GL_COLOR_ARRAY` and it's working pretty well.
> 0 votes

---
Tags: android, opengl-es
---


title: OpenGL Positional 2D Texture Masking

text:
# Question
Title: OpenGL Positional 2D Texture Masking
I have a simple 2D java game engine running using LWJGL. I have my own vertex and fragment shaders, and I'm able to render quads with textures.

I want to be able to mask one quad using the texture from another quad. Example: I have two quads with two different textures mapped to them. Quad A has a red circle texture. Quad B has a blue square texture. I want to use Quad A's red circle texture as a mask such that Quad B will only be visible if it is within Quad A's red circle texture.

Here's an image showing what I want to do:

The problem is that I am always seeing the 'full overlap' no matter the position of the quads. I can never get that partial masking that I'm looking for.

My shader logic is close to this:

```
#version 150 core
uniform sampler2D texture;
uniform sampler2D maskTexture;

in vec2 pass_TextureCoord;
in vec2 pass_MaskTextureCoord;

out vec4 out_Color;

void main(void) {
     //***other logic here to determine out_Color***

     if(pass_MaskTextureCoord.x != -1 && pass_MaskTextureCoord.y != -1) { //if we have valid mask texture coordinates, we are masking
          vec4 maskColor = texture(maskTexture, pass_MaskTextureCoord); //get the rgba values of the mask texture
          if(maskColor.a == 0) { //if mask texture has no alpha, discard
               discard;
          }
     }
}

```

Do I need to pass location data of the masking quad into the shader? If so, how do I do that?

**EDIT**: ilmale's method using the stencil buffer worked for me! All I needed to add was a uniform boolean value to tell the shader if I was drawing a mask or not.

Here's the relevant shader code:

```
if(isMask) { //if this is a mask, discard where texture alpha is 0
    if(texColor.a == 0) {
        discard;
    } else {
        out_Color = vec4(0, 0, 0, 0); //make the rest transparent, so we don't see the mask texture
    }
}

```

# Answer
this is the classical use of stencil buffer.

```
glStencilOp( GL_KEEP, GL_KEEP, GL_REPLACE );
glStencilFunc( GL_ALWAYS, 1, 0xFF );
drawQuadA();

glStencilOp( GL_KEEP, GL_KEEP, GL_KEEP );
glStencilFunc( GL_EQUAL, 1, 0xFF );
drawQuadB();

```

QuadA will write the stencil buffer to 1. QuadB will be drawn only where the stencil buffer is 1.
> 1 votes

---
Tags: opengl, shaders, masking
---


# Question
Title: How to get more gentle (cloud like) noise?
Recently I have started playing around with making terrain with perlin noise. Using this library I can make A fairly fast. However, it is to squiggly to be desirable. What I want to achieve is B, where you can see more convincing slopes with the softer noise.

# Answer
> 4 votes
The noise function is returning a single "frequency" of noise. The effect on the right (B) is by adding together noise of multiple frequencies, in a "red noise" or "fractal brownian noise" pattern. Low frequencies will be more prominent than high frequencies.

You can change the frequency by multiplying the input to the noise function by a constant. For example, `noise(2*x,2*y)` will have frequency 2. So try adding `16*noise1(x,y) + 8*noise2(2*x,2*y) + 4*noise3(4*x,4*y) + 2*noise4(8*x,8*y) + noise5(16*x,16*y)` where `noise1``noise5` are `new Perlin(…)` with different seeds, and see if that's closer to what you want. I don't know for sure whether these constants will be what you need but you can start playing with them to get different effects.

---
Tags: terrain, perlin-noise
---


title: How do I model diffusion and heat?

text:
# Question
Title: How do I model diffusion and heat?
So I'm trying to solve a heat/diffusion equation for a continuous space, but I'm not opposed to a grid solution. I'm a little short on the maths needed but have made it work so far.

If I model sources and sinks on a grid, I just need to center a gaussian potential on that coordinate with the appropriate sign. A source is like a positive metaball and a sink is like a negative one. Similarily, I can just do a gaussian blur of the entire image *if it has no walls*. The sources and sinks will smear together and give the actual solution.

However, if I have walls I can't do that, because there are boundary conditions to the problem all of a sudden. I could incrementally blur by a small amount, then add the walls back in, but I'm looking for a solution that I can lookup any `t` (time) for directly.

I could also expand the heat map out from sources and sinks by flood filling from those points, but I need the heat value to be implicitly there. I'll be pulling single values of perlin noise out of the air for obstacles and don't want to evaluate the entire field only to pull a single heat value.

So, is there any way I can define the boundary conditions as part of the convolution (gaussian blur) using math or some technique?

I looked at potential fields but I don't think that solves the diffusion exactly. To restate, how do I add boundaries to a diffusion problem and solve for a specific coordinate `(x,y,t)`? It should be possible since the boundary/obstacle is a single function `f(x,y,t)`.

# Answer
If you're looking for a single heat value you can calculate the distance between your sample point and all sources & sinks in a straight line.

If there is a wall in a straight line, calculate from your sample to the ends of the wall and then to the source/sink.

it gets a bit more complicated with walls made of multiple segments due to being potentially convex/wavy.

Depending on your need, you could account for the walls reflecting/holding heat into the material or not.

It can get complicated but can still be faster than the grid way. Depends on the number of points and walls.

It's running an open-area path-finding algorithm to every heat sources / sinks.

I can't remember what it's called. Someone can probably chime in. I got a total brain fart on the name but here's a quick graph:

When you hit a wall (red line with 'X') you try around both ends and iterate until you find a path around all obstacles. Have to be careful when a wall points straight to a goal there's some rounding errors you have to take care of by not passing exactly at the end points but just a little bit outside.

Every time you hit a wall there's to ways: left & right, you keep the shortest path or use all paths for heat/gas distribution, depends on what you need.

(I didn't draw the 2 blue possibilities to keep it clean.)

The problem is very similar to turning an arbitrary polygon into triangles to render using a GPU (http://en.wikipedia.org/wiki/Polygon\_triangulation) **but turned inside-out**. Maybe looking at those algorithm as well will help.
> 1 votes

# Answer
Surprisingly enough, a simple Google of "the heat equation" yields kilo-calories of information on the partial-differential equations and common boundary conditions encountered in solving heat-flow problems. The derivation of the equation in one, two, or three dimensions is readily developed from Conservation of Energy and Fourier's Law.

> The law of heat conduction, also known as Fourier's law, states that the time rate of heat transfer through a material is proportional to the negative gradient in the temperature and to the area, at right angles to that gradient, through which the heat flows. We can state this law in two equivalent forms: the integral form, in which we look at the amount of energy flowing into or out of a body as a whole, and the differential form, in which we look at the flow rates or fluxes of energy locally.

However, in your case the theoretical evaluation is not of interest, but rather the mathematical evaluation by numerical analysis. The *Differential form of Fourier's Law* is readily adapted to numerical analysis:

> The differential form of Fourier's Law of thermal conduction shows that the local heat flux density, \overrightarrow{q}, is equal to the product of thermal conductivity, k, and the negative local temperature gradient, -\nabla T. The heat flux density is the amount of energy that flows through a unit area per unit time.

If anyone knows how to use LEX to properly format the above from the preceding link, that would be greatly appreciated.
> 0 votes

---
Tags: mathematics, algorithm, simulations
---


title: Visual studio and Unity does not sync

text:
# Question
Title: Visual studio and Unity does not sync
I'm pretty new to Game Development world. I'm using Unity 3D (4.6 - Latest version I think) and Visual Studio to code the script and something when I edit the script un VS 2013 and go back to Unity the script I edited does not match what unity "have". And Unity does not even show a compile error.

Exemple I have is :

(in a 2D environment) i wrote this script

```
void Update(){
    Vector2 tweak = new Vector2(Math.Random(0f,0.2f), Math.Random(0f,0.2f));
    rigidbody.velocity += tweak;
}

```

Well unity gave me the error that rigidbody does not exist on the Transform (aright that's cool im in a 2d env. so it's rigidbody2D.velocity. I edited the script, with the fix, but Unity was still executing the line BEFORE the fix. I had to close VS and Unity to fix this.

# Answer
Try using Visual Studio Tools for Unity from Syntax tree http://unityvs.com/ You can debug Unity from within Vs with this plugin.
> 1 votes

---
Tags: unity, game-design, unityscript, visual-studio
---


# Question
Title: How can I render a simple lattice in LibGDX?
I have searched all over, but I can't find what I think will be a simple answer. I am using Opengl ES 2.0, and LibGDX. I simply want to use GL\_LINES primitives to create a lattice structure.

I have used shapeRenderer with the following code: in create():

```
shapeRenderer = new ShapeRenderer();
shapeRenderer.setProjectionMatrix(cam.combined);

```

in render():

```
shapeRenderer.setProjectionMatrix(cam.combined);
shapeRenderer.begin(ShapeType.Line);
shapeRenderer.setColor(0, 1, 0, 1);
for (float i = -10; i <=10; i++) {
    for (float j = -10; j <= 10; j++){
        shapeRenderer.line(i, j, -10, i, j, 10);
        shapeRenderer.line(-10, i, j, 10, i, j);
        shapeRenderer.line(j, -10, i, j, 10, i);
    }
}
shapeRenderer.end();

```

The problem is, this is not a model instance, thus doesn't seem to use the RendererContext (GL\_DEPTH\_TEST, etc.). When I render the lattice this way, it either shows up entirely behind my models, or entirely in front of them (depending on the order I render them in the render method).

Is there a way to build a model which is simply a set of lines to be rendered with Opengl primitive GL\_LINES? Any pointers would be greatly appreciated.

# Answer
Ok, I found a way. I'm not sure that it's the most performant, but it works, and the DEPTH\_TEST (z-culling) is working now. Here is how I did it:

in declarations:

```
private ModelInstance mLattice;

```

in create():

```
ModelBuilder modelBuilder = new ModelBuilder();
modelBuilder.begin();
MeshPartBuilder meshPartBuilder = modelBuilder.part("lattice", GL20.GL_LINES,
        Usage.Position, new Material(ColorAttribute.createDiffuse(Color.GREEN)));

for (float i = -10; i <=10; i++) {
    for (float j = -10; j <= 10; j++){
        meshPartBuilder.line(i, j, -10, i, j, 10);
        meshPartBuilder.line(-10, i, j, 10, i, j);
        meshPartBuilder.line(j, -10, i, j, 10, i);
    }
}

Model latticeModel = modelBuilder.end();
mLattice = new ModelInstance(latticeModel);
instances.add(mLattice);

```

in render():

```
modelBatch.begin(cam);
modelBatch.render(instances, environment);
modelBatch.end();

```

This solved my problem. There may be better (more efficient) ways to accomplish this, but this suits my needs at the moment. If I find something better, I'll update the answer for anyone who may stumble upon this.
> 0 votes

---
Tags: opengl, java, android, libgdx, opengl-es2
---


title: How can you visualize a quaternion?

text:
# Question
Title: How can you visualize a quaternion?
When I visualise a three dimensional rotation matrix, or scaling matrix I visualize it as three axes.

**Is there a similar way that I can visualize a rotation quaternion?**

# Answer
There is an entire 600 page book on "Visualizing Quaternions": http://books.google.ca/books?id=CoUB09xzme4C&lpg=PP1&ots=uEdJHsni9y&dq=Visualizing%20Quaternions&pg=PP1#v=onepage&q&f=false

The book is actually quite good, covering a wide range of topics. It starts with a good introduction to game related linear algebra, it talks about matrices and vectors, their shortcomings and why you would want to use Quaternions. It then explains what they are and how to make use of them. If you are interested you might want to pick it up: http://www.amazon.com/Visualizing-Quaternions-Kaufmann-Interactive-Technology/dp/0120884003
> 20 votes

# Answer
One of the visualization methods I like is to represent quaternion (orientation in 3d space) as **vector** (*x,y,z* components) **\+ spin** (the rotation around that vector, stored in *w* component).

If you are looking for some **online visualizer** for quaternions, you can always use wolframalpha:

http://www.wolframalpha.com/input/?i=quaternion%3A+0%2B2i-j-3k&lk=3

Take the a look at the visualization labeled as "corresponding 3d rotation" (the 3d vector + spin):

I've found it useful while working with quaternions in my 3d engine.
> 12 votes

# Answer
I visualize my quaternions as three-dimensional vectors (direction + length) with a bit to the side to be able to show rotation along the vector's axis.

It's a common way to visualize rotation vector in physics, but the name escapes me.
> 7 votes

# Answer
You do not necessarily need an alternate visualization technique for quaternions versus matrices.

When you visualize your rotation matrix as the 3 axes gizmo, what you're really visualizing is an orientation. Since the quaternion also represents an orientation, consider continuing to use your 3 axes gizmo as your mind's eye visualization object.

Rarely, for both quaternions or matrices, do you need to relate the actual component values into your visualization, so just because the component values of the quaternion do not relate to your 3 axes gizmo doesn't mean it can't be used for visualization purposes.
> 4 votes

# Answer
You can, but it becomes difficult. Instead of three separate axis of rotation, or three gimbals that are each moving independently one at a time, you have to picture a quaternion as a description of the full three dimensional rotation angle and the magnitude at once as a single description of the entire translation.

http://en.wikipedia.org/wiki/Quaternion\_rotation

Quaternions are definitely not an area I'm rock solid on, but that wiki page has some decent info on it. Wikipedia talks about rotations on a hypersphere though, gets a little confusing. Good luck!
> 2 votes

# Answer
As you know, Quaternion is based on complex numbers and represents rotation of 4D sphere in 4D dimension. So you cannot visualize it 'as is'. I see that you know it too. And one and only one choice will be visualization of result of rotation. For example result of rotation of basis; Or you can render 3D sphere and paint it by layered 'temperature' of rotation by each axis; Good luck!
> 2 votes

---
Tags: mathematics, quaternion
---


# Question
Title: How to launch ball in an arc between two points?
How do I launch a ball in an arc from one place to another? I am using Construct 2 personal but am not familiar with the program, can anyone help?

# Answer
In Construct 2, sprites can have "Behaviours". You might want to add the Bullet and Gravity behaviour to your ball, and tweak the parameters so that the Ball fires at the angle you want it to, and then the Gravity behaviour will cause it to fall to the bottom of the screen. You could also set the speed of the Ball's movement from user-input.

Or do you want to the ball to land at a specific point?
> 0 votes

---
Tags: construct-2
---


title: Fps independent rotation

text:
# Question
Title: Fps independent rotation
I'm trying in my game to have camera rotation speed idependent of fps. For keyboard it works without problems but not for mouse movoment. At 60 fps it works good but at 200 for example rotation is to slow.

mouse\_dif is difference since last frame in pixels. Maybe thats a problem too, bigger screen resolution will rotate faster then smaller.

My code:

```
const float rot_speed = u.GetRotationSpeed(); // returns 5.f
float val = 0;

if(allow_input == ALLOW_INPUT || allow_input == ALLOW_MOUSE)
    val += float(mouse_dif.x)/200;

if(val > rot_speed*dt)
    val = rot_speed*dt;
else if(val < -rot_speed*dt)
    val = -rot_speed*dt;
u.rot += val;

```

How can I make it fps independent?

# Answer
> -2 votes
This page has fantastic explanations of different ways to update your game loop, the last one will show you how to make your logic update run independently from updating the screen. Hope it helps: http://www.koonsolo.com/news/dewitters-gameloop/

---
Tags: rotation, mouse, first-person-shooter
---


# Question
Title: Texture loading: Everything at once OR un-/loading the needed assets?
Good evening. We've been developing quite a huge game for android on the basis of AndEngine. So we have a lot of assets to load, especially textures.

At the moment everything (sound, textures etc) for every screen (menu, shop, etc etc) is loaded when the app starts (while showing a progress bar). This way the user only has to wait once about 16 seconds at the start of the game. We think that this is a pretty pleasant solution from the users perspective but might it be bad in terms of battery usage / memory usage or any other reasons?

What arguments speak for a solution where we unload all the screen specific assets of the active screen and load the assets needed for the next screen? Thank you for your opinion!

# Answer
> 0 votes
The only argument for the solution you propose is so there is less memory usage at a specific time, which might be good for a mobile device with a relatively small amount of memory vs a PC. However, it is a double edged sword. For you to unload and load assets as your game is running, you might need to introduce multiple loading screens because of the overhead from processing this.

It is probably a better experience for your players if there is a single loading screen at the start, and they don't need to wait for anything later on. There might even be less load on the battery life from loading everything at the start, rather than loading and unloading multiple times.

---
Tags: opengl, java, android, opengl-es2, andengine
---


# Question
Title: Event handling on own UI implementation in XNA
I´m creating a game in XNA with my own UI and its controls/components. Currently I have some problems with the event handling. Let me tell me the way I do it right now. Every object is handles as a component (also the form itself). Each component can implement an interface with a container which can contain a list of components (and so on and so on). An example: I have a form. On this form there is a TabControl. In this TabControl there are different TabPages and in these pages there are buttons.

I now have to handle my events that when I click on the button, the overlaying controls should not fire an event (like OnClick etc.).

How can I easily do that? I have a current function which runs recursively but only on two levels depth or something.

Here is my current function which is not working as expected:

```
private Boolean HandleComponentList(IComponentList parent) {
foreach (var singleItem in parent.Components.OrderByDescending(i => i.ID).Where(singleItem => singleItem.Visible))
{
    // Cast item to IComponentList.
    var castedList = singleItem as IComponentList;
    // If list is not null (so it implements IComponentList), call HandleComponentList for Components in this control first.
    if (castedList != null)
    {
        // If an event has been raised, break function.
        var eventFound = HandleComponentList(castedList);

        if (eventFound)
            return true;
    }

    // Only fire events if control is enabled.
    if (singleItem.Enabled)
    {
        // look for events.
    }
}

return false;

```

}

Would be great if someone has some suggestions! Thank you!

# Answer
In the similar scenario i've used polling model (updating input every frame), composite pattern (which you already implemented) and rectangle hit detection.

Every frame visual tree root (GUIManager, in my case) polls its children, calling the Update with the mouse coordinates, until one of them reports that the mouse is inside of it. This control will also be the only one checking the mouse button states and raising events. Visual tree root code:

```
foreach(Component c in Children)
{
    if(c.Update(Mouse.X,Mouse.Y))
        break;
}

```

And the update method (simplified):

```
if (IsInside(Mouse.X, Mouse.Y))
{
    //mouse is ours, check buttons, raise events.
    return true;
}
else return false;

```

For the complex controls, you can just combine these two pieces of code, firstly asking all of your control's children, and if none of them returns true, then the parent will handle the mouse/raise events.

```
if (IsInside(Mouse.X, Mouse.Y))
{
    foreach(Component c in Children)
    {
        if(c.Update(Mouse.X,Mouse.Y))
            return true;
    }
    //mouse is over the parent control, but not over one of its childs.
    return true;
}
else return false;

```

This behaviour can be tweaked in case you will need to handle the mouse in several controls. For instance, you can return up some kind of class which will store Handled variable - this will be a sort of WPF bubbling event model. Also instead of the special GUIManager you can use one of your Component classes for uniformity.
> 1 votes

---
Tags: xna, c#, events
---


# Question
Title: What are 'ambient' lighting/illumination/occlusion?
What's the difference between ambient lighting,ambient illumination and ambient occlusion ? What are they? What's the difference between them?

# Answer
### They approximate indirect lighting in a local illumination light model.

In other words, the interaction between lights bouncing from one surface to another is not a part of local illumination; we call the light model where bounces are considered *global illumination*.

Ambient lighting and occlusion simulate accumulated light (or find areas where indirect light has difficulty accumulating in the case of occlusion) without actually doing the complicated work of bouncing photons around the scene.

This is a necessary hack for lighting in general purpose real-time rendering.
> 0 votes

# Answer
To begin with, most real time rendering is done by rasterization, rather than ray tracing. While much faster, it means that we're essentially imitating how light works rather than simulating it. We get an even bigger speed boost by "baking" our static lighting information into the environment.

**Ambient lighting** is the base level of light, or the minimum amount of brightness everything is rendered at. Therefore, a white surface without any light sources will be as bright as the ambient light level. In a non-normalized lightmap, every point will be at least whatever this value is. This is usually used to make up for lack of...

**Ambient illumination**, usually called **Global illumination**, which is light that bounces from one surface to another. For example, if you shine a bright white light on a flat green wall, that light will bounce off and illuminate the other walls in green.

However, global illumination can be processor intensive, so...

**Ambient occlusion** is often used to support the scene. Rather than calculate how much light each point in a scene receives, we instead calculate how much light would be blocked (or occluded). There are various implementations of ambient occlusion, the most common being screenspace, which uses the depth buffer - it isn't "realistic," strictly speaking, as detailed further in Sean Barrett's article Corners Don't Look Like That: Regarding Screenspace Ambient Occlusion, but makes things more interesting than just having flat walls.
> 1 votes

---
Tags: rendering, lighting
---


# Question
Title: How can I test if one point can "see" another point. (XNA)
I want to test if my enemy can see the player, however I want this to be pixel-perfect.

I already have all of the solid objects drawing into a separate render state. It should be noted that every solid object is changing and warping all over the place constantly. **I cannot check individual walls because a distortion effect is applied to all of them. The walls blend together.**

Essentially it would lerp between the enemy's position and the player's position and see if there are any pixels that have an alpha value of greater than 0. The rotation of the enemy and the player do not matter.

All of my attempts at doing this on the cpu have worked, however they slowed the game down dramatically. All of my attempts at going this on the gpu just didn't work at all.

What is the most efficient way of doing this? **Is there any way to do this in the gpu?**

Edit: There is no geometry at all. The walls are completely amorphous.

I did not realize that global variables were constant in hlsl until after I wrote this:

```
sampler s0;
texture tex;
sampler tex_sampler = sampler_state{Texture = tex;};

float2 screenSize;
float2 from;
float2 to;
float2 impact;
int impacted;

float4 PixelShaderFunction(float2 coords: TEXCOORD0) : COLOR0
{
    from /= screenSize;
    to /= screenSize;

    impacted = 0;

    for (float i = 0; i < 1; i += 1.0f / length(to - from))
    {
        float2 test = lerp(from, to, i);

        if ( (tex2D(tex_sampler, test)).a )
        {
            impacted = 1;
            impact = test * screenSize;
            break;
        }
    }

    return tex2D(s0, coords);
}

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

```

The solid pixels would be passed into the "tex" variable. I would read the "impacted" and "impact" variables after one pass on a 1x1 texture. hlsl just doesn't want to let me do this. Apparently global variables are implicitly constant. Is there another way of doing this?

on the variable syntax page it says "Global variables are considered const by default (suppress this behavior by supplying the /Gec flag to the compiler)." How do I add the /Gec flag to the compiler?

I also wrote this, but it slowed the game down:

```
private bool CanSee(Vector2 from, Vector2 to)
{
    Color[] t = new Color[target_solid_final.Width * target_solid_final.Height];
    target_solid_final.GetData(t);

    for (float i = 0; i < 1; i += 8.0f / (to - from).Length())
    {
        Vector2 test = Vector2.Lerp(from, to, i);
        Point test_p = new Point((int)test.X, (int)test.Y);

        if (viewportRect.Contains(test_p) &&
            t[test_p.X + test_p.Y * target_solid_final.Width].A > 0)
            return false;
    }

    return true;
}

```

# Answer
EDIT: I see your updates now, I'd suggest you try implementing something such as my first suggestion.

Since you didn't post any of your code, I'm going to have to guess at how you're doing the collisions. Are you using a single pixel collision check between the player and the enemy with the wall or other related sprites around it? If so, there are probably some ways you can speed this up.

First, it's not really necessary to use pixel perfect lines to check - all that does is slow down C# / XNA. Instead, try checking to see if there is any wall between the player and enemy every 3 pixels or 4 pixels. As long as the walls are at least 5 or so pixels thick, then using a 3 pixel skip in your line of sight to the player won't lose you much accuracy, but it will increase the speed.

Second, you can take the distance of each enemy to the player, and for each enemy, any walls that are greater than the distance from that enemy and the player (+ an inch or so for error) obviously cannot be obstructing the enemy's view of the player.

Third, enemies further than a certain large distance from the player are likely unable to see the player. If the enemy is halfway across the screen, you can probably exclude it from collision checks - how would it be able to see the player that far away anyway, assuming that somehow it wasn't obstructed by a wall?

Fourth, if you're not already doing so, you can use bounding box collision as a precursor to collision checks per enemy. *This will make a VERY significant speed difference*! If you're already doing this, then you should look into using my first three suggestions. But if you're not doing bounding box collision, start here.

Hope these concepts help you speed up your game! If I assumed how your collision works incorrectly, just leave me a comment.
> 2 votes

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


# Question
Title: C++ DirectX FBX SDK Importer Weird Mesh Problem
I'm having a problem understanding how to render the vertex data in fbx model into directx. This is my two functions and I've already triangulated all the mesh nodes.

```
bool FBXLoader::CopyVertexData(Mesh* mesh)
{
    FbxVector4 pos, nor;
    FbxNode* rootNode = mScene->GetRootNode();
    if (rootNode)
    {
        int iChildNodeCount = rootNode->GetChildCount();

        for (int i = 0; i < iChildNodeCount; i++)
        {
            // Child Node -> Object
            FbxNode* fbxChildNode = rootNode->GetChild(i);
            FbxMesh* fbxMesh = fbxChildNode->GetMesh();
            if (!fbxMesh)
                continue;
            int iVertexCount = fbxMesh->GetControlPointsCount();
            if (iVertexCount > 0)
            {
                SubMesh subMesh;
                int iPolyCount = fbxMesh->GetPolygonCount();
                for (int j = 0; j < iPolyCount; j++)
                {
                    // The poly size should be 3 since it's a triangle
                    int iPolySize = fbxMesh->GetPolygonSize(j);
                    // Get 3 vertices for the triangle
                    for (int k = 0; k < iPolySize; k++)
                    {
                        // Get index
                        int index = fbxMesh->GetPolygonVertex(j, k);
                        subMesh.indices.push_back(index);

                        // Get position
                        pos = fbxMesh->GetControlPointAt(index);
                        // Get normal
                        fbxMesh->GetPolygonVertexNormal(j, k, nor);

                        // Insert pos and nor data
                        Vertex vertex;
                        vertex.fPos = DirectX::XMFLOAT3((float)pos.mData[0], (float)pos.mData[1], (float)pos.mData[2]);
                        vertex.fNor = DirectX::XMFLOAT3((float)nor.mData[0], (float)nor.mData[1], (float)nor.mData[2]);
                        vertex.fTex = DirectX::XMFLOAT2(0.5f, 1.0f);
                        subMesh.vertices.push_back(vertex);
                    }
                }
                mesh->subMeshes.push_back(subMesh);
            }
        }
    }
    else
    {
        MessageBox(NULL, "Unable to create FBX Root Node object", "Error", MB_ICONERROR | MB_OK | MB_TASKMODAL);
        return false;
    }

    return true;
}

bool FBXLoader::CopyVertexDataTest(Mesh* mesh)
{
    FbxNode* rootNode = mScene->GetRootNode();
    if (rootNode)
    {
        int iChildNodeCount = rootNode->GetChildCount();

        for (int i = 0; i < iChildNodeCount; i++)
        {
            // Child Node -> Object
            FbxNode* fbxChildNode = rootNode->GetChild(i);
            FbxMesh* fbxMesh = fbxChildNode->GetMesh();
            if (!fbxMesh)
                continue;
            int iVertexCount = fbxMesh->GetControlPointsCount();
            if (iVertexCount > 0)
            {
                SubMesh subMesh;
                FbxVector4* pVertices = fbxMesh->GetControlPoints();
                for (int j = 0; j < iVertexCount; j++)
                {
                    Vertex vertex;
                    vertex.fPos = DirectX::XMFLOAT3((float)pVertices[j].mData[0], (float)pVertices[j].mData[1], (float)pVertices[j].mData[2]);
                    vertex.fNor = DirectX::XMFLOAT3(0.3f, 0.6f, 0.9f);
                    vertex.fTex = DirectX::XMFLOAT2(0.5f, 1.0f);
                    subMesh.vertices.push_back(vertex);
                }
                int iIndexCount = fbxMesh->GetPolygonVertexCount();
                //int* indices = new int[iIndexCount];
                int* indices = fbxMesh->GetPolygonVertices();
                for (int j = 0; j < iIndexCount; j++)
                {
                    subMesh.indices.push_back(indices[j]);
                }
                mesh->subMeshes.push_back(subMesh);
            }
        }
    }
    else
    {
        MessageBox(NULL, "Unable to create FBX Root Node object", "Error", MB_ICONERROR | MB_OK | MB_TASKMODAL);
        return false;
    }

    return true;
}

```

Here's the result using between those 2 functions. All images are the output of shader

CopyVertexData

CopyVertexDataTest

I exported the same model into .obj format for data checking between fbxMesh-\>GetControlPointAt(index) and fbxMesh-\>GetControlPoints(). So... my first question is why is it that GetControlPoints() gave me the same exact vertices data as the .obj data while GetControlPointsAt(...) gave different values?

Here's my second question. Let's use a cube model as an example case. A cube have 6 faces and each face have 6 vertices(2 triangles) which means a cube will have 12 triangles and 36 vertices. Assume that the cube have 6 polygon faces.

I load the cube fbx model and then I triangulate the mesh. I assumed that when I use GetPolygonCount(), I will get 12 triangulated polygons and each polygons will give 3 vertices. Is it wrong?

My solution

```
bool FBXLoader::CopyVertexData(Mesh* mesh)
{
    FbxVector4 pos, nor;
    FbxNode* rootNode = mScene->GetRootNode();
    if (rootNode)
    {
        int iChildNodeCount = rootNode->GetChildCount();

        for (int i = 0; i < iChildNodeCount; i++)
        {
            // Child Node -> Object
            FbxNode* fbxChildNode = rootNode->GetChild(i);
            FbxMesh* fbxMesh = fbxChildNode->GetMesh();
            if (!fbxMesh)
                continue;
            int iVertexCount = fbxMesh->GetControlPointsCount();
            if (iVertexCount > 0)
            {
                int indicesIndex = 0;
                SubMesh subMesh;
                // Get all positions
                FbxVector4* pVertices = fbxMesh->GetControlPoints();
                int iPolyCount = fbxMesh->GetPolygonCount();
                for (int j = 0; j < iPolyCount; j++)
                {
                    // The poly size should be 3 since it's a triangle
                    int iPolySize = fbxMesh->GetPolygonSize(j);
                    // Get 3 vertices of the triangle
                    for (int k = 0; k < iPolySize; k++)
                    {
                        // Get index
                        int index = fbxMesh->GetPolygonVertex(j, k);
                        subMesh.indices.push_back(indicesIndex++);

                        // Get normal
                        fbxMesh->GetPolygonVertexNormal(j, k, nor);

                        // Insert pos and nor data
                        Vertex vertex = Vertex();
                        vertex.fPos = DirectX::XMFLOAT3(static_cast<float>(pVertices[index].mData[0]), static_cast<float>(pVertices[index].mData[1]), static_cast<float>(pVertices[index].mData[2]));
                        vertex.fNor = DirectX::XMFLOAT3(static_cast<float>(nor.mData[0]), static_cast<float>(nor.mData[1]), static_cast<float>(nor.mData[2]));
                        vertex.fTex = DirectX::XMFLOAT2(0.0f, 0.0f);
                        subMesh.vertices.push_back(vertex);
                    }
                }
                mesh->subMeshes.push_back(subMesh);
            }
        }
    }
    else
    {
        MessageBox(NULL, "Unable to create FBX Root Node object", "Error", MB_ICONERROR | MB_OK | MB_TASKMODAL);
        return false;
    }

    return true;
}

```

Result

# Answer
I had the same issues. Check if you are using LH or RH coordinate system. To use RH (what I would suggest since most tools do) create your projection matrix with :

```
XMMATRIX perspMatrix = XMMatrixPerspectiveFovRH(angle, aspect, 0.1f, 100.0f);
XMStoreFloat4x4(m_pProjMatrix, XMMatrixTranspose(perspMatrix));

```

and when setting up your rasterizer use :

```
D3D11_RASTERIZER_DESC desc;
desc.CullMode = D3D11_CULL_BACK;
desc.FrontCounterClockwise = true;

```

Otherwise you have to convert from RH to LH i.e. if you are importing .fbx from Maya

I think it would be more clever to copy all control points in advance (before traversing the mesh) by :

```
    auto axisSystem = fbxScene->GetGlobalSettings().GetAxisSystem();
    auto controlPoints = mesh->GetControlPoints();
    auto controlPointsCount = mesh->GetControlPointsCount();

    // Copy all control points
    for (auto cp = 0; cp < controlPointsCount; cp++)
    {
        auto point = controlPoints[cp];
        auto newVertex = new Vertex();
        newVertex->Position = ConvertFbxVector4ToXMFLOAT3(&point, axisSystem, 1.0f);
        vertices->push_back(*newVertex);
    }

```

whrere ConvertFbxVector4ToXMFLOAT3 is your on function to invert or change axis depending on the actual axis system. For normal RH coordinate systems (+Y-Up, + Z-Front), nothing has to be converted. Then you work on your copied verices like this :

```
    for (auto v = 0; v < polygonSize; v++)
    {
        auto vertexIndex = mesh->GetPolygonVertex(p, v);
        auto newVertex = new Vertex(vertices->at(vertexIndex));

        // Create the normal
        FbxVector4 normal;
        mesh->GetPolygonVertexNormal(p, v, normal);
        newVertex->Normal = XMFLOAT3
        {
            static_cast<float>(normal.mData[0]),
            static_cast<float>(normal.mData[1]),
            static_cast<float>(normal.mData[2])
        };

            // Use a standard color for all vertices
        newVertex->Color = XMFLOAT4
        {
            0.7f, 0.2f, 0.7f, 0.6f
        };

        // Dont set that now
        newVertex->UV = XMFLOAT2
        {
            0.0f, 0.0f
        };
        vertices->at(vertexIndex) = *newVertex;
        indices->push_back(vertexIndex);
    }

```

> I will get 12 triangulated polygons and each polygons will give 3 vertices. Is it wrong?

No, you are right but I know what you mean. I've tried the same with Blender (creating cube and importing it as FBX) and what I got is 4 indices per polygon (4 * 6 = 24) instead of 3 (2 * 3 * 6 = 36) which afaik Direct3D does not accept.
> 0 votes

---
Tags: c++, directx, fbx, model-loader
---


# Question
Title: How do I convert a vector into a distance?
I'm doing a 2D raycast where i have to pass distance. The scenario is this:

I'm using rigidbody2d.Moveposition to move my character instantly. However, before a character is moved, i want to do a raycast in that direction. My Movement code is:

```
if (Input.GetKeyDown (KeyCode.D)) {
            rigidbody2D.MovePosition(rigidbody2D.position+speedx);
            return;
        }

```

where speedx is Vector2 Vector2(1,0) (can be increased as necessary). So when A is down, first i want to do a raycast to see if it hits any collider and then move or not move the character to that position. However, i'm not able to understand how to set the raycast distance so that it corresponds to the exact distance my character intends to move.

So, what i'm looking for is a way to corelate Vector2 and float.

# Answer
You can get the length of a vector (the distance from its start to end position) using vector.magnitude.

Note that typically an entity doesn't move its full speed as distance in any single frame, since d = v * t. So you'll usually want to multiply your speed or velocity by your timestep to get the distance traversed this frame.

Also, note that the amount of space your character needs clear to complete the move won't just be the span between their old and new position, but also a little extra to account for the size of the character. You might do that by adding a fudge factor to your vector's length, to account for the character's bounding radius. That only checks in the direction of movement though.

If you want to be really robust, you can use the CircleCast or BoxCast methods (SphereCast or CapsuleCast in 3D) to check whether an object with some volume to it can travel through space to the destination without hitting anything.
> 1 votes

---
Tags: unity
---


title: Calculating Projectile Movement

text:
# Question
Title: Calculating Projectile Movement
I'm having some trouble putting together a method that will constantly move a "bullet" in the same direction accurately. Here is what I have so far

```
public Vector3f moveFromPosition(Vector3f location, float pitch, float yaw, Game game) {
        Vector3f loc = location;
       loc.z += 0 * Math.cos(Math.toRadians(yaw - 90)) - 1 * Math.cos(Math.toRadians(yaw));
       loc.x -= 0 * Math.sin(Math.toRadians(yaw - 90)) - 1 * Math.sin(Math.toRadians(yaw));
       loc.y += 0 * Math.sin(Math.toRadians(pitch - 90)) - 1 * Math.sin(Math.toRadians(pitch));
       return loc;
    }

```

This method is being called in the render method, so every frame it will move the bullet 1 space depending on the pitch, yaw, and location the bullet was fired from. The pitch and yaw values stay the same each frame, and the vector3f "location" stands for the location the bullet is currently at. The bullet is then translated accordingly depending on the return location from this method.

**The x and z values are calculated correctly, but the y value seems to be a little off and I can't figure out why**

Here is where the method is being called from

```
package Entitys;

import Main.Game;
import Model.Model;
import Tools.TrigCalculator;
import org.lwjgl.util.vector.Vector3f;

public class Projectile {

    Model model;
    Game game;
    Entity entity;
    Vector3f startLocation;
    float startPitch;
    float startYaw;
    TrigCalculator trigCalculator;

    public Projectile(Vector3f startLocation, float startPitch, float startYaw, Entity entity, Game game){
        //The location the camera is at, or where the bullet will be fired from
        this.startLocation = startLocation;
        //Camera's pitch when shot
        this.startPitch = startPitch;
        //Camera's yaw when shot
        this.startYaw = startYaw;
        //The entity representing the bullet
        this.entity = entity;
        //The class the calculation moveFromPosition is at
        this.trigCalculator = game.getToolHandler().getToolTrigCalculator();
    }
    /* This move method is being called in the render method */
    public void move(){
        //Translating the entity according the the calculation below.
        entity.setTranslation(startLocation);
        //Here is where the method is called
        startLocation = trigCalculator.moveFromPosition(startLocation, startPitch, startYaw, game);
    }
}

```

Requested Edit: This is how I create a new projectile

```
projectiles.add(new Projectile(new Vector3f(loc.x, loc.y, loc.z), game.getCamera().getPitch(), game.getCamera().getYaw(),entity, game));

```

After debugging the return of game.getCamera().getYaw() and getPitch() both return the correct value. Then it's passed into the startPitch value, which is passed into the moveFromPosition method each frame. Other than that it doesn't change.

# Answer
Well for one, your x,y,and z would stay zero based on moveFromPosition. If you want the bullet to follow a certain path, you need to get rid of the zeros, math calculates anything multiplied by 0 is equal to 0

Your next problem is you are over-complicating the math in moveFromPosition. All you need to do during an update is

```
float horizontal = Math.cos(Math.toRadians(pitch)) * wantedSpeedForward;
float vertical = Math.sin(Math.toRadians(pitch)) * wantedSpeedForward;

loc.x += Math.cos(Math.toRadians(yaw)) * horizontal;
loc.z -= Math.sin(Math.toRadians(yaw)) * horizontal;
loc.y += vertical;
//if you wanted strafing, or non-forward motion add this
loc.x -= Math.sin(Math.toRadians(yaw)) * wantedStrafingSpeed;
loc.z += Math.cos(Math.toRadians(yaw)) * wantedStrafingSpeed;

```

This insures the bullet travels at the speed you want based on pitch and yaw (just set the rotations properly and it will work) but you may not want to create a physical bullet projectile like this because if you calculate physics, it will slow down the program a lot so the preferred way is a directional spray, probably through raycasting, and spawning particles after its fired upon the raycasted path. This severely decreases the actual physics and makes bullets simplified and more realistic in the end. Now if you were aiming for a bow, you would want this, but I think I have answered your problem and suggested a better solution if need be so I will hold my peace.

EDIT: wouldn't a separate object for the bullet itself be better (you know, where it holds its position, rotation and anything else significant) All you would need to do is bullet\_object.update()
> 0 votes

# Answer
You're doing something strange: Every frame, you calculate the x,y,z values of the bullet's movement, based on a yaw and pitch that will never change. Why not create a vector3 that stores the direction and speed of the bullet in the bullet constructor? This way, you can do the calculations once per bullet, and then just add its speed vector to its current position every frame. This saves resources.

Also, wouldn't it be easier to store the camera's rotation as a matrix or quaternion? You might already be doing this, I can't tell. If you do that, you could simply say that the bullet's direction is equal to the forward member of the quaternion or matrix.

I've personally had a LOT of issues with rotations when trying to calculate them by yaw pitch and roll (especially when you add the third, it can be a nightmare), but simply copying over a rotation matrix (or quaternion) that already works is quite simple.
> 1 votes

# Answer
As a rule of thumb: never use Euler angles unless you have to. For velocities, it's probably just better to use vectors, and don't worry about the orientation. You can use the matrix representation of the camera to find which direction the player is facing.

```
public Vector3f moveFromPosition(Vector3f location, Vector3f velocity, float dt) {
   return location + velocity * dt;
}

```

Or, since it seems you're using java, you'll probably need some boiler plate for copying and such.

```
public Vector3f moveFromPosition(Vector3f location, Vector3f velocity, float dt) {
   Vetor3f loc = new Vector3f(location);
   Vector3f vel = new Vector3f(velocity);
   vel.multiply(dt);
   loc.add(vel);
   return loc;
}

```

Then, calculate the velocity like this:

```
public Vector3f getBulletDirection(Camera camera) {
  return new Vector3f(camera.getForward());
}

```
> 0 votes

---
Tags: opengl, java, lwjgl, projectile-physics, trigonometry
---


title: Pathfinding and clusters

text:
# Question
Title: Pathfinding and clusters
For an assignment, I am required to implement an A\* algorithm in order to find the shortest path between two object using different heuristics

1. null, this effectively becomes Dijkstra
2. Euclidean distance
3. Clustering

So I have successfully implemented the A\* algorithm and the first two heuristics and they work wonderfully. However the third heuristic I am having trouble with. According to the text

> The cluster heuristicworks by grouping nodes together in clusters. The nodes in a cluster represent some region of the level that is highly interconnected. **Clustering can be done automatically using graph clustering algorithms that are beyond the scope of this book**
>
> When the heuristic is called in the game, if the start and goal nodes are in the same cluster, then Euclidean distance (or some other fallback) is used to provide a result. Otherwise, the estimate is looked up in the table.

I'm not one to give up on a challenge so I would like to implement some automatic clustering technique. I am lazy and I really don't feel like manually clustering nodes, I want it to be automated. So I have been doing research on clustering and I've come across this technique: **Markov Cluster Algorithm**(MCL)

Are there any good methods besides the one presented? I have searched the IEEE database for clustering techniques but I am not entirely sure if those are valid for the scope of my assignment. I'm not looking for any code but I would surely appreciate any guidance on the matter.

Edit: I should clarify what is required in the assignment for clustering.

> For the Cluster heuristic consider the nodes in each room to contain a cluster, and each corridor to contain a cluster. Using Dijkstra’s algorithm, between each pair of clusters compute the shortest distance between any two nodes (one from each cluster). Use these results between pairs of clusters to create a lookup table.

Furthermore this is the requirements for the level. Each convex polygon represents an obstacle. If I had to guess, there are 7 clusters in total

# Answer
**Clustering in Graphs**

I'm not sure why your assignment has given you an open research problem (clustering in graphs) to solve. Please ask your professor if this is really required before continuing.

If you know the number of clusters, (or can guess them) I would suggest trying something like spectral clustering, or K-means clustering; using the number of edges as the affinity between clusters. You can also try min-cut-max-flow like algorithms.

Generally, the idea is to divide the graph into a number of connected components such that:

* The connectivity *within* the components is maximized
* The connectivity *between* components is minimized
> 2 votes

---
Tags: unity, path-finding, heuristics
---


# Question
Title: How to find the closest point on a plane
So I have this terrain with a perpendicular plane setup, now I want to move the vertices of the plane to their closest resp. vertices on the terrain. I made a drawing to illustrate my thoughts. Final result being the terrain will look like it has some thickness.

i also need the projection of the point on the terrain

I found this code on a previous thread :

```
    float distance = PointToPlaneDistance(smallObj.transform.position, wall.transform.position, wallNormal);

    private float PointToPlaneDistance(Vector3 pointPosition, Vector3 planePosition, Vector3 planeNormal)
    {
        float sb, sn, sd;

        sn = -Vector3.Dot(planeNormal, (pointPosition - planePosition));
        sd = Vector3.Dot(planeNormal, planeNormal);
        sb = sn / sd;

        Vector3 result = pointPosition + sb * planeNormal;
        return Vector3.Distance(pointPosition, result);
    }

```

The result vector here is the closest point

But what is the plane normal? Unity has a built in `mesh.normals` which gives all the surface normals for the terrain. Which one should I use here?

# Answer
Since your plane is perpendicular, you wouldn't use the normals. Just like your second drawing in your album:

Just ignore the Y and Z axis, of the terrain. For each point you want to match on the terrain, take the X axis value, and match that value on your perpendicular plane.

For example, if the point is at (1,3,0), just take the point (1,planeTop,0) on your plane.

Your terrain even appears to be a regular grid, meaning you can use a simple loop to iterate through the terrain vertices and match them with your plane vertices.

As for the projection, you don't have a flat plane, which is what that code is for. You have an uneven mesh. Using the normals will not help you. Just take the four values that make up the corners of the grid square you're directly above, then use linear interpolation to find the y value of the mesh at that point.

See this answer for more information.
> 1 votes

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


# Question
Title: If you create a game, do you automatically have the rights to it?
I am creating a game in c++ that will me multiplier and am going to post it on https://indiegamestand.com Here is one of the requirements "Must own the rights to distribute your game and to assign those rights to us (non-exclusively) for the purpose of selling here." If I compile my game as an .exe do I have that right? How can I make sure I retain it, and what can they do with the game if I give them that right?

# Answer
You own the rights if you created it (source code and media content). As long as you don't have an existing contracts for work you create (sometimes tech companies will do this while you're employed with them, if the work is similar to the work you do there), what you create is yours. Also ensure the software and hardware you're using does not claim any rights to the content you're using them to create.

You can prove that you have the rights by showing evidence that you're the creator, with source code, notes, dated correspondence (emails talking about what you're working on maybe?), etc.

If you give them the right to sell it, they have the right to sell it. You're not giving them rights to the game, just rights to sell the game, and they're non-exclusive rights, so you can still sell it other places.
> 3 votes

---
Tags: publishing
---


# Question
Title: Camera is centered on character, but doesn't show character in game window
I'm using Unity 4.6.3. I create an animation from sprite. When I press `Play` button, I see animation plays on scene window, but on Game Window, I don't see anything.

Here is Inspector for main camera:

Here is Inspector for Player:

I have checked that both z = 0 when execute. Please tell me which part I config wrong ?

# Answer
> 2 votes
The camera needs to be in front of the scene (some -Z value) in order to see the scene. The camera can't see things that are at or behind its depth.

Set your camera position to be something like -10 for the Z component of the position. You should notice right away that the camera preview shows your sprite.

---
Tags: unity, camera
---


# Question
Title: How to make randomly placed objects not on top of each other?
I randomly instantiate game objects, to create a dynamic "sky map". But some planets appear on top of another ones. I'm trying to solve this problem with Collision detection and Colliders, but it doesn't seem to work. How to solve this problem? Maybe there is a better and easier way to do this?

Here is the code I use:

Instantiating:

```
for (int i = 0; i<planet_one_count; i++) {
            var planets = Instantiate (planet, new Vector3 (Random.Range (-9.0F, 9.0F)+(Random.value), Random.Range (-4.0F, 3.0F)+(i*Random.value), 0), new Quaternion (0, 0, 0, 0)) as GameObject;
            planets.transform.localScale = planets.transform.localScale*Random.Range(0.75f,1);
                }
        for (int i = 0; i<cometcount; i++) {
            var comets = Instantiate (comet, new Vector3 (Random.Range (-9.0F, 9.0F)+(Random.value), Random.Range (-4.0F, 3.0F)+(i*Random.value), 0),Quaternion.Euler(0,0,Random.Range(-34,-24))) as GameObject;
            comets.transform.localScale = comets.transform.localScale*Random.Range(0.75f,1);
        }
        for (int i = 0; i<planet_two_count; i++) {
            var planets_two = Instantiate (planet_two, new Vector3 (Random.Range (-9.0F, 9.0F)+(Random.value), Random.Range (-4.0F, 3.0F)+(i*Random.value), 0), new Quaternion (0, 0, 0, 0)) as GameObject;
            planets_two.transform.localScale = planets_two.transform.localScale*Random.Range(0.75f,1);
        }

```

Collision:

```
void OnCollisionStay2D(Collision2D coll){
    coll.gameObject.transform.position = new Vector3(coll.gameObject.transform.position.x+0.1f,coll.transform.position.y+0.1f,0);
}

```

# Answer
> 1 votes
Depending on the game's field of play's size, divide the area you wish to populate with planets into a grid where each square can contain a planet in it's entirety. Now Randomly decide if there is a planet in each square of the grid, by randomizing a number.

```
NUMBER_OF_SQUARES = width * height;
NUMBER_OF_PLANETS = 28;

planetsLeft = NUMBER_OF_PLANETS;
while (planetsLeft > 0)
for (int i = 0; i < NUMBER_OF_SQUARES; i++)
    if (Random.Range(0.0, 1.0) > NUMBER_OF_PLANETS / NUMBER_OF_SQUARES)
        if (gird[i] == false)
            grid[i] = true;
            planetsLeft--;
            // planet[i].xy = grid[i].xy + small_randomness_inside_square;

```

# Answer
> 0 votes
Okay, I'm not going through debugging your code because I think there is an easier way. Rather than checking for per pixel or rectangle collision, why not maintain a list of Vector3s and a list of floats? Populate the list of Vector3s with positions and the list of floats with the radius of the planets.

```
private bool AddPlanetIfNoCollision(Vector3 position, float radius)
{
    if (positions.Length > 0)
    {
        for (int i = 0; i < positions.Length + 1; i++)
        {
            if (Vector3.Distance(positions.elementAt(i), position) > radius + radii.elementAt(i))
            {
                return false;
            }
        }
    }
    positions.Add(position);
    radii.Add(radius);
    return true;
}

```

Obviously that code is not something you'd copy paste into your program, it's just a concept. But it will work fine as long as your planets are circular.

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


title: Box2D Lights - Simulate water

text:
# Question
Title: Box2D Lights - Simulate water
I have a libGDX project, in which I have a Box2D world, which is currently filled with some boxes as a terrain. I also added a `DirectionalLight` to the scene for simulating the Sun. I almost have the effect I'd like to achieve, but is there any way to let the light shine through the water more deeply than it does on the surface?

# Answer
You simply need to define the water, the same way you define the skies for lighting purposes. You may or may not need to duplicate the world simulation for lighting if you want water to behave different from solids.
> 0 votes

---
Tags: libgdx, box2d, lighting
---