title: Identify mouse click unity3d

text:
# Question
Title: Identify mouse click unity3d
I have a 3 fbx models. When i click on the first object it should displays its name of the gameobject in a label and clear the label when click on another object. How to display the name of the gameobject in a label.I dont know how it identifies the click and how to get the name of that object display in label.

```
 void Start () {
    gui.enabled = true;
    labelfont=new GUIStyle();
    labelfont.fontSize=18;
    labelfont.normal.textColor=Color.white;

}
void OnMouseEnter () {
    //code I have so far
    Debug.Log ("nameee" + gameObject.name);

if (gameObject.name == "venacava")
    {
      gui.text = "";
     gui.text = "venacava";
  displaymessage = true;
 }
}

```

# Answer
To be able to select objects in Unity, you need to add colliders to your objects. Just dragging the model into the scene will not automatically add a collider. For each game object you want to interact with, select it in the Hierarchy and add a MeshCollider using the Inspector.

Now, create a script that will display interact with the objects, something like Highlighter. In the Highlighter script, you can implement the method `OnMouseDown`. This method is activated when the user left clicks an object in the scene. Inside this method you make whatever changes you like to the selected objects.
> 5 votes

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


# Question
Title: Can you change Unity's default script template for a single project?
Can you change Unity's default script template **for a single project**?

Here it's explained how to do that globally and it's fine, I wonder if you can do it on a per-project basis.

I mean, I'd bet you can't or I would have been able to find it, but maybe I missed something, or there's a plugin, who knows...

# Answer
unfortunately in my travels i have not yet found a way to do this, and afaik i haven't seen an add-on to specifically do this either.

**what i have found is an interesting answer here...** of a possibly useful alternative solution... there the op goes into modifying the editor with some custom scripts to enhance the "create script" menu options, essentially to include your new script templates as options

hope this helps
> 3 votes

---
Tags: unity
---


# Question
Title: How do I draw a line using jme3.scene.shape.Line in JMonkeyEngine 3.0?
I can successfully create the object, but it can't be attached to the rootNode. What can I do to make the line appear?

I'll also would like to know how to reverse the effect(making it disappear) shortly after if any special steps are involved.

# Answer
> 4 votes
The solution is actually quite easy.

The `.attachChild()` method of the rootNode object only accepts Nodes as it's argument. Therfore, a Geometry object must be created with the line object as its second arguement.

In addition, you can also set its material afterwards.

An example:

```
Line line = new Line(new Vector3f(0, 0, 0), new Vector3f(0, 100, 0));
line.setLineWidth(2);
Geometry geometry = new Geometry("Bullet", line);
Material orange = new Material(assetManager, "Common/MatDefs/Misc/Unshaded.j3md");
orange.setColor("Color", ColorRGBA.Blue);
geometry.setMaterial(orange);
rootNode.attachChild(geometry);

```

---
Tags: java, graphics, jmonkeyengine
---


title: 2d Ice movement

text:
# Question
Title: 2d Ice movement
I am building an top-down 2d RPG like zelda. I have been trying to implement ice sliding. I have a tile with the slide property. I thought it would be easy to get working. I figured that I would read the slide property, and move the character forward until the slide property no longer exists. So I tried a loop but all it did was stop at the first tile in an infinite loop. I then took the loop out and tried taking direct control of the character to move him along the slide path but I couldn't get it to move.

Is there an easy way to do an ice sliding tile based movement in libgdx. I looked for a tutorial but none exist.

# Answer
> 1 votes
Many games do not handle player movement as a purely binary moving/not moving system, but model the players movement through acceleration, deceleration and top-speed. The result is a much more natural movement. In such a system, a slippery floor is essentially free, because you can just reduce acceleration and remove automatic deceleration when the player isn't moving.

# Answer
> 0 votes
**Tweening**

Also known as "Easing" and "Inbetweening". But basically, if you use it in movement, (See the very bottom link) it could give you the smooth, ice-walking animation you want.

Webopedia defines it as;

Short for in-betweening, the process of generating intermediate frames between two images to give the appearance that the first image evolves smoothly into the second image. Tweening is a key process in all types of animation, including computer animation. Sophisticated animation software enables you to identify specific objects in an image and define how they should move and change during the tweening process. (http://www.webopedia.com/TERM/T/tweening.html)

Also, you can find it in this amazing talk about adding "Juice" (More gameplay output per input) to your game here; (http://youtu.be/Fy0aCDmgnxg?t=2m38s)

---
Tags: libgdx
---


# Question
Title: Simultaneously translating and rotating sprite in Unity
I have a 2D object (a PNG file I dragged onto the screen) which is a circle I would like to move left and right when the correct side of the screen is touched and have it rotate in the respective direction while doing so. Naturally, I thought using transform.Translate and transform.Rotate would be the proper way to do this, as such:

```
void Update() {

    if (Input.touchCount > 0)
    {
        var touch = Input.GetTouch (0);
        if (touch.position.x < Screen.width/2)
        {
            transform.Translate (Vector3.left * Time.deltaTime);
            transform.Rotate (Vector3.forward * Time.deltaTime);
        }
        else if (touch.position.x > Screen.width/2)
        {
            transform.Translate (Vector3.right * Time.deltaTime);
            transform.Rotate (Vector3.back * Time.deltaTime);
        }
    }
}

```

For whatever reason, rotating left and right didn't work so I tried forward and back which at least rotated it. The problem is that the circle moves in an arc, I'm assuming because as it rotates, the direction of "right" changes. Also, the circle gets squashed into an ellipse after a bit, I assume because I'm rotating on the wrong axis. I've literally just started using Unity yesterday; what is the most concise and best way to accomplish what I'd like?

# Answer
Essentially your main problem is that you're not rotating correctly. Which is leading to other issues.

When rotating I find it's easier to use the version of `Rotate` that takes an axis to rotate around, and the number of degrees to rotate. So:

```
float degreesPerSecond = 45;
if (touch.position.x < Screen.width/2)
{
    transform.Translate (Vector3.left * Time.deltaTime);
    transform.Rotate (Vector3.up, degreesPerSecond * Time.deltaTime);
}
else if (touch.position.x > Screen.width/2)
{
    transform.Translate (Vector3.right * Time.deltaTime);
    transform.Rotate (Vector3.up, -degreesPerSecond * Time.deltaTime);
}

```

The reason it appears to get squished is because even though you're using a 2D object, it's being rotated in 3D. This makes it appear to be squished when it rotates away from the plane you're viewing it on. The version of `Rotate` you're using applies the rotation as direct euler angles:

> Applies a rotation of `eulerAngles.z` degrees around the z axis, `eulerAngles.x` degrees around the x axis, and `eulerAngles.y` degrees around the y axis (in that order).

Also note that the `Translate` and `Rotate` methods both accept a `Space` parameter, this defaults to the local or `Self` coordinates. If you always want to rotate around the world axis you'll have to pass in the `World` variable when translating or rotating.
> 1 votes

---
Tags: c#, unity, rotation, vector, transformation
---


title: smooth movement pygame

text:
# Question
Title: smooth movement pygame
Hello im trying to learn more about smoother movement in games. I have created a little program to hopefully help me understand this. As far as i can tell i am suppose to track time, and update positions accordingly. However, for some reason, this concept is very hard for me to understand. I am using python and pygame at the moment for my games, and in none of them i have been able to come up with the smoothness i wanted. Ive also tried several games off of the pygame website and so far none of them have had the smoothness i prefer.

like i said, i understand you have to track time, and update positions accordingly instead of just +1'ing location each frame/iteration. By doing it the 'wrong way' as far as i understand then it doesnt neccesarily sync up with the monitor thus creating the sense of jittery motion, even at high FPS.

i have read a few articles on the subject of time steps, however i have been unable to fully understand the concept and incorporate it in my game. so i would like to ask, if someone can explain how to implement a timestep and create smooth motion. i am not going to incorporate physics in my first games, so the accuracy of the timer does not matter too much, what is most important right now is a game that can run as smooth as a proffesional game. i am sure a revisit if not simplified explanation of timestepping, and even how to do it in a simple way with python will be of benefit to any programmer hoping to use pygame/python for his games.

Anyway this is the program i was able to write, that doesent have smooth motion. Perhaps someone can modify it, so we can get a working example with time stepping and see how it improves the smoothness. PS. you need python 2.7 and a python 2.7 pygame compatible version to run the program/game

http://bpaste.net/show/qmE362O29sq6GPGBK3fg/

# Answer
> 8 votes
First we need to clarify what "smooth movement" is.

Let's first talk about **smooth movement in a pixelated space**.

Not taking into account motion blur and sub-pixel movement, the smoothest **amount** of movement you can have on a pixel screen is **one pixel**. So your code

```
pygame.draw.circle(SCREEN, (255, 255, 255), (newx, SCREENRECT.centery), 30)
pygame.display.update()
newx+= 1

```

actually procudes the smoothest movement in space possible.

Your code produces a smooth movement of roughly *60 pixels per second* because of the `clock.tick(60)` call. This is smooth, but not very fast.

To get **fast** movement, you now could increase the amount of pixels your image jumps per step by using `newx+= 2` or `newx+= 5`. But this, in line with the above definition, will *no longer produce smooth movement*. Why? Because you move more than 1px in one step, which we percieve as stuttering.

So, what can be done? If we want **fast** movement, but can only get it **smooth** by moving one pixel at a time, *we need to move 1px at a time more often per second*. And that means: increasing the renderings per second, or, more common, frames per second.

(Note that we have not yet talked about timesteps here at all.)

So as a first step, decrease the waiting time between frames (`Clock.tick()` essentially is a pause function with dynamic duration) by increasing the argument. Try `clock.tick(120)` or `clock.tick(360)`.

At some point you will notice that the perceived speed of the motion does no longer increase. This is because you reach the limit of how long your rendering actually takes to compute. At this point, **optimization** has to happen if the movement is still to slow.

Your drawing routine is inefficient for various reasons:

* It clears the whole screen to black every frame with `SCREEN.fill((0, 0, 0))`, although technically you would just neet to clear the area where the circle is.
* You compute and draw a circle in every frame using `pygame.draw.circle()`. It would be more efficient to pre-render the circle to a surface an blit that surface to the background.

These would be starting points to get your simple animation smooth and fast. You can optimize further by abandoning Pygame Surfaces and switching to OpenGL. But it is important to note that **there is always a limit to the speed of smooth, i.e. 1px movement**. Most of the time the practical limit is the *monitor refresh rate*. If your monitor updates the application's display from the frame buffer memory, say, at 90 times per second (90 Hz), then 90 px / s is the most of smooth movement in space that you can get.

Now you were asking about timesteps, so let's talk about **smooth movement in time**.

We perceive an object moving smoothly if it moves by *equal amounts of space* in *equal amounts of time*. If you have tuned up the FPS in the above example to 360, you might have noticed that the circle stutters and moves irregularily. This is because at some frames Pygame manages to draw everything in less than 1/360 s, and in some frames not. This means that some times the circle does move 360px in one second, and some times the circle takes longer than one second *wall clock time* to move 360 px. This is because rendering time *is not guaranteed*. And this is where timesteps come in.

The principle of timestepping is to keep the movement in sync with the wall clock time. That means, instead of blindly moving a fixed amount of pixels per frame, you *measure the time* your frames take, and adjust the amount of movement (and possibly the time to pause) accordingly. The answer of Yos233 shows one way to do this using the return value of `clock.tick()`.

Timestepping requires that there is a target speed of your animation. Say an object shall move 50 px per second. The basic procedure is

1. Draw the object.
2. Wait until 1/50 s has passed.
3. Update position by 1 px.
4. Repeat.

The critical point is when in 2. you see that actually *more* than 1/50 s has already passed. Here, to keep the movement smooth in time, you have to *quantify how much time over 1/50 s has passed*, and *add to the amount of space to move accordingly*.

Note that in this case you inevitably will have to move **more than 1px** to stay in sync; this means that your movement will be **smooth in time**, but no longer **smooth in space**.

To sum up:

1. 1px movement is the smoothest you can get, and it is limited by the frame rate your whole setup can achieve.
2. Timestepping will smooth out your movement over time, but will actually increase jumps and stutter if the target speed can not be met.

For further reading on timesteps, check out the excellent article Fix Your Timestep!.

# Answer
> 4 votes
clock.tick() returns a float in milliseconds since the last call. This is often reffered to as the timedelta.

This means you can do things like this:

```
while running:
    timedelta = clock.tick(60)
    timedelta /= 1000 # Convert milliseconds to seconds
    pygame.draw.circle(SCREEN, (255, 255, 255), (int(newx), SCREENRECT.centery), 30)
    newx += 100*timedelta

```

newx will now increase by 100 per second.

# Answer
> 0 votes
I'm not sure exactly how python works, but i work with physics games that deal with this stuff.

Position: this is the position on the screen. EX: the unit is meters.

Velocity: this is the speed, how much it moves over time. EX: The unit is meters / sec.

To get the next position, you can use velocity, which will give you the distance traveled over a time period passed.

Position = Velocity * (Change in time)

Now to get a smoother speed you need to bring time into the equation. This can be achived if python has a function such as get Time() or something.

Position = Velocity * ( CurrentTime - LastTimeSinceRender)

Basically, don't do this:

newX++;

that isn't good for any physics simulation. Always bring the timestep, which relates position to velocity.

# Answer
> 0 votes
The problem is in your `pygame` usage: you're re-creating the circle on every frame. Pygame works best if you create every image only once, on its own *Surface* (think of it as a virtual canvas), and then in each frame you *blit* that surface's image onto the screen (which is also a surface). Think of blit as an ultra-fast copy from surface to surface.

Here's an alternate version of your code (I've also changed the ordering of a few steps: to me, it seems more to logical to check for input first, then update the objects position, draw, and finally tick the clock):

```
import pygame, sys, random

pygame.init()

## Functions and classes

## Variables

clock = pygame.time.Clock()
SCREEN = pygame.display.set_mode(pygame.display.list_modes()[-1])

radius = 50

# create the surface that will contain the circle image.
# circle will be drawn on its center, so surface width and height is 2*radius
circle = pygame.Surface((2*radius, 2*radius))

# Let's also paint the surface GREEN so you see its corners behind the circle
circle.fill((0, 255, 0))

# draw the circle on the surface instead of screen
pygame.draw.circle(circle, (255, 255, 255), (radius, radius), radius)

# Last but not the least, create a companion rect, based on surface's size
# A rect is just a tool to define width, height and position at the same time
rect = circle.get_rect()

# rect now has same width and height as the surface,
# It's positioned at (0, 0) so let's move it to desired initial position

rect.x = 0  # instead of SCRENRECT.centerx, so it stays longer on screen
rect.y = SCREEN.get_rect().centery

# The surface (and our friend the rect) is set up and ready to be used on screen

## Main loop

running = True

while running:
    #Quit event etc
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
            running= False

        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_ESCAPE:
                pygame.quit()
                sys.exit()
                running= False

    rect.x += 1

    SCREEN.fill((0, 0, 0))

    # and now we blit the pre-drawn circle onto the screen,
    # using rect as coordinates
    SCREEN.blit(circle, rect)

    pygame.display.update()
    clock.tick(60)

```

---
Tags: animation, python, pygame
---


# Question
Title: Disabling impact damage by Kinematic actor on non-dynamic destructibles (using NVidia APEX)
I have a destructible non-dynamic object at Apex scene and am hitting the object with a *kinematic* actor. I do not want it to be fractured by these impacts. Is it possible?

PS: the impact damage is off when the destructible is dynamic. I have tried below settings:

```
physx::apex::NxDestructibleParameters destructibleParameters =
                                          destructibleActor->getDestructibleParameters();
destructibleParameters.forceToDamage = 0;
destructibleParameters.damageCap = 0;
destructibleParameters.impactVelocityThreshold = PX_MAX_F32;
destructibleParameters.impactDamageDefaultDepth = -10;
destructibleActor->setDestructibleParameters(destructibleParameters);

```

# Answer
Setting *damageThreshold* handled it:

```
...
NxParameterized::Interface* descParams = destructibleAsset->getDefaultActorDesc();
NxParameterized::setParamF32(*descParams, "defaultBehaviorGroup.damageThreshold", -1.0f);
NxApexActor* tempActor = destructibleAsset->createApexActor(*descParams, scene.getApexScene();

```
> 1 votes

---
Tags: physx
---


# Question
Title: Do total conversion mods require absolutely no programming or scripting skills?
I tried to look up total conversion and other mods as examples (Counter-Strike, Defense of the Ancients, Gunman Chronicles, Dear Esther, Natural Selection) but it is a bit difficult to find out if they (and other total conversion mods) required a little or a lot of programming.

I ask this out of pure curiosity, as I have heard some people claim you can make a total conversion with **absolutely no programming skills**. However, this is not easy to research as google does not bring up articles mentioning how total conversion mods do/don't require programming skills.

# Answer
A "total conversion" mod usually means that you are not just going to replace assets, but that you are going to change game mechanics and actor behaviors. This usually requires programming skills. What kind of skills depends on the engine.

Some engines have amazingly powerful map editors which can really do a lot (Defense of the Ancients was originally a Warcraft III custom map), but when a tool gets that powerful, using it to its full extend practically becomes programming.
> 2 votes

---
Tags: modding
---


# Question
Title: How can I optimize a parallax effect consisting of multiple transparent layers?
I have a parallax effect in MonoGame consisting of multiple semi-transparent layers of textures. The effect is simple, but rendering multiple transparent layers on top of each other is rather slow. This effect doesn't need to be "accurate". How can I optimize this effect or fake it with shaders to make it more efficient?

The main premise is multiple full screen size semi-transparent layers drawn on top of each other from back to front. There are currently 3 layers + the actual game layer that also has some transparency.

I used a stencil buffer to render the game layer, already eliminating some of the parallax layers' pixels from rendering, but it's still inefficient.

# Answer
It really depends on what you're trying to render. For example, if you're rendering layers of clouds that are transparent to the background but not necessarily to each other, one useful trick is to draw the background, then non-transparent cloud layers, then draw the background *again* at 50% transparency over the other layers.
> 2 votes

# Answer
I'm not familiar with MonoGame.

Have you thought about drawing your parallax background at a reduced resolution to a render texture? Scale the finished render texture up to the original size and render it to the screen. If you create the render texture at half the width and height of the original, you need to overdraw and blend only 25% of the fragments in the semi-transparent layers.

This approach may blur the parallax layers depending on the size of the render texture. Depending on what you want to achieve, this may not be acceptable...
> 1 votes

---
Tags: xna, shaders, monogame, optimization, parallax-scrolling
---


title: ImpactJS and Construct 2

text:
# Question
Title: ImpactJS and Construct 2
I'm interested in HTML5 game development and I found about this 2 game engines, I already know ImpactJS requires more programming experience and that Construct 2 has its own event and action system that can be extended with plugins made with JavaScript.

I want to know what are each engine's primary focus, when would someone choose one over the other assuming programming knowledge is not a concern.

Is it a matter of taste, features available, type of game or is it that each tool serves better for some kind of games or development process?.

I'm not looking to know which is better, just in which situations works better each tool, so people can have an idea of what's better for building the game they have in mind.

# Answer
I never used ImpactJS, but I have used Construct2 quite a lot.

Wether or not you have experience in Game Programming. You should totally check out Construct2 IMO!

Many things work just out of the box. You plug them into your game and it changes. Perhaps some things to consider?

* Do you know how to switch between several game screens? Are you able to utilize Webstorage? Can you write your own A\*star algorythm and can you do Polygon Collision? Obviously nothing is stopping you from learning all of these things :) But not everyone does have that much interest in Programming. If you are more of a Designer Perhaps, or want to build your game (or prototype) with rapid speed. You should totally check out their free demo. Can't hurt.

***Here are some nice features of Construct2:***

* No Programming: Everything is done via the Event System. You never truly interact with any real programming code.
* Addons! Loads and Loads of extensions by the Community. They are all written in JavaScript with the simple C2 SDK and obviously free of charge. You can add addons simply by dragging the new addon folder into the **/Plugin** or **/Behavior** folder.
* Behaviors: Possibly the most useful feature of Construct 2.. You can give your Objects pre-built behaviors. So if you are creating a Super Mario Clone, simply add the matching Behavior to your Sprite: *(ScrollTo is another Behavior, it focuses the screen on the Objects location)*
* Plugins are just as important as Behaviors. Every Object in Construct2 is a Plugin. Your Spaceship is a Sprite Plugin with added Behaviors. And your Keyboard is also a Plugin:

**EDIT:** I Would also like to address this misconception that Construct 2 somehow is only good for platformers. I think the reason for that is two-folded: 1. The Intro Video on their website shows how to build a Platformer. 2. Building a Platformer can take mere minutes. Here are some of the Pre-Build examples you get when you download Construct2. To give you some idea of its capabilities: *(Couldn't fit all on my screen)*
> 5 votes

# Answer
I have lots of experience with ImpactJS, but none with Construct 2.

ImpactJS is great for developing 2d games like platformy Metroidvanias or top-down RPG-types or card games or what-have-you.

ImpactJS has many pluses on its side:

You 100% need to know how to write JavaScript to use ImpactJS; your game will need a lot of custom behavior that you need to write, line-by-line.

I'm very interested in JS-based 2d games and have found it an excellent place to start. The code is very readable if you need to write your own modifications and the creator, Dominic, is an active member of the forums.

To get an example of what Impact-type JS looks like (and to let me get in a shameless plug), check out my event chain plugin on GitHub.
> 4 votes

# Answer
I agree with Oliver Schöning's response. I haven't used ImpactJS before, so I'll talk about C2:

C2 pros:

* Very well documented. Many tutorials.
* Dedicated plugins: Platformer games become very easy to develop.
* The SDK is extensible with your own plugins and behaviors.

C2 cons:

* To integrate some third party plugin in your game (e.g. Socket.io) you must create a plugin for it.
* Plugins are relatively hard to develop.
> 1 votes

---
Tags: javascript, html5, construct-2, impactjs
---


# Question
Title: GLSL to Cg: why is the effect different?
With reference to this question, where I was trying to make the shader compile, I am now trying to make an effect appear. The effect can be shown here, through a GLSL shader:

But when I use the equivalent Cg shader, the result becomes this:

Using the same images (color map + normal map) and the same code (except the way to retrieve variables).

Here is the original GLSL shader;

```
uniform sampler2D color_texture;
uniform sampler2D normal_texture;

void main() {
    // Extract the normal from the normal map
vec3 normal = normalize(texture2D(normal_texture, gl_TexCoord[0].st).rgb * 2.0 - 1.0);

// Determine where the light is positioned (this can be set however you like)
vec3 light_pos = normalize(vec3(1.0, 1.0, 1.5));

// Calculate the lighting diffuse value
float diffuse = max(dot(normal, light_pos), 0.0);

vec3 color = diffuse * texture2D(color_texture, gl_TexCoord[0].st).rgb;

// Set the output color of our current pixel
gl_FragColor = vec4(color, 1.0);
}

```

And here is the Cg shader I wrote;

```
struct fsOutput {
    float4 color : COLOR;
};

uniform sampler2D color_texture : TEXUNIT0;
uniform sampler2D normal_texture : TEXUNIT1;

fsOutput FS_Main(float2 colorCoords : TEXCOORD0,
            float2 normalCoords: TEXCOORD1)
{

    fsOutput fragm;

    float4 anorm = tex2D(normal_texture, normalCoords);
    float3 normal = normalize(anorm.rgb * 2.0f - 1.0f);
    float3 light_pos = normalize(float3(1.0f, 1.0f, 1.5f));
    float diffuse = max(dot(normal, light_pos), 0.0);
    float3 color = diffuse * tex2D(color_texture, colorCoords).rgb;
    fragm.color = float4(color,1.0f);
    return fragm;
}

```

Please let me know if something needs to be changed in order to obtain the effect, or if you need the C++ code.

# Answer
The shader was fine. But when I tried to use other shaders I realized what was wrong.

It was the C++ code that was lacking lines (rrr!! This is the reason why I hate shaders! It's so complicated to make a link in your head between every line you write in one file and what must be written in the other for it to be recognized!).

In the display function, I had:

```
[clearing + loading identity matrix]

cgGLBindProgram(VertexProgram);
cgGLBindProgram(FragmentProgram);

[buffers swapping]

```

The very important thing that was missing before binding was:

```
cgGLEnableProfile(VertexProfile);
cgGLEnableProfile(FragmentProfile);

```

Only then the shader effect is displayed proprerly. Simple mistakes make worst time wastes!
> 1 votes

# Answer
They are not equivalent. In the GLSL shader you use the same texture coordinate for your diffuse and normal map (`gl_TexCoord[0]`). In the CG shader you use separate ones (`TEXCOORD0` and `TEXCOORD1`, which is presumably not set).
> 2 votes

---
Tags: opengl, c++, shaders, glsl, cg
---


# Question
Title: How could I handle non-rectangular tile collision in Tiled maps?
BrowserQuest map in question.

From what I understand, with tiled, there are two main ways to specify collision:

1. Create an object layer, and interpret the shapes in the engine as collision objects.
2. Create a tiled layer, and make all tiles in the layer have a collision *property*, and interpret all tiles in the layer as collision objects.

I'm using BrowserQuest as a big source of inspiration for my project, and I want to know how they handled collision on the level editing side.

I've checked through all their layers, expecting an object layer to be handling cliff collision like:

But there are no such object layers to be found. Furthermore, the **tile layers containing the tiles for such cliffs have no properties** at all, meaning that they didn't just specify "collision" for such tile layers.

I especially need to know how they handled less rectangular shapes like:

I could imagine that they are not using explicit collision layers, but instead determining collision in the actual engine, based off the presence of specific tile layer sprites. Only because BrowserQuest has whole-tile movement, and it wouldn't look too odd if a small apple, taking up only a fraction of the tile size, prevents movement over that entire tile.

But I'm creating a game with more precise movement, so collision has to be tight to the apple, and I really want to know how BrowserQuest approached collision defining.

If anyone knowledgeable with Tiled could take a quick look at the map, I'd appreciate it! I'm tearing my hair out here :). Thanks

# Answer
I would assume BrowserQuest uses the tile indices (GIDs) to determine collisions. You're probably correct that this is handled in the engine internally and not editable in Tiled.

Though your assumptions about how this can be done is correct, too. And some games actually need both GID-based and object-based collisions.

The platformer I'm working (more here and here) on uses this strategy, and purposefully makes these properties editable both in Tiled and in a configuration file (Lua script with a table). After all I'm working with a non-programming game/level designer. ;)

* Only tiles on the "gameplay" layer are considered when it comes to collision detection & resolve.
* All tiles in a tileset are considered blocking by default. This is because far more tiles on the "gameplay" tile layer are blocking than those that are not.
* Tiles in a tileset can have a `collisionBits` property with the bit-value (and to help my designer, soon this will support string-based bits like so: "one-sided+damage". With value 0 you can make a tile non-blocking if need be. Other bits define slopes, death on contact, one-sided, etc.
* Tiled objects can be used to mark larger areas of a map to change their collision behavior, ie applying collision bits, overriding those set on each individual tile. On load this object-based collision information is baked together with the tile (GID) collision bits into the collision map used by game code (the TMX structure doesn't lend itself well to fast collision checks).
* Finally Tiled rectangle objects can be put in a "colliding objects" category. This makes these objects behave like regular blocking tiles - since they can be on non-grid boundaries and their bounding box can be of any size, they require special handling and are more costly to resolve collisions with - on the other hand these become moving platforms without which no platformer would truly be a "platformer".
> 4 votes

# Answer
In the tilesheet, right click on a tile and then open its Tile Properties. If you see a property named "c", it means that that tile is "closed", and the player cannot enter that tile. If the tile lacks "c", then the player can enter it.

Source: https://github.com/particlequest/ParticleQuest/wiki/How-to-create-a-map-using-tiled-map-editor
> 2 votes

---
Tags: collision-detection, tiles
---


# Question
Title: How can I implement a percentage chance to perform some action?
Let's say that there is an X% chance that a character will shoot a target, or some other action. How do I determine if the action should be taken or not (how do I implement the percentage chance)?

# Answer
One way to do this is, take a pseudo random generator and let it generate a float between 0 and 1. You would then multiply it with 100 to get into the range of 0 to 100. If this final value is smaller than the percent of the chance, in this example, the tank would hit the target. Here is some pseudo code, what it could look like:

```
// chance of tank, hitting the target
float chance = 70.0f;

// first, generate a pseudo random float in the range of 0 to 1
float n = random();

// multiply n with 100 to get into the range of 0 to 100
n = n * 100;

// if n is below chance, the tank will hit the target
if(n < chance)
{
    // do something here
}

```

Edit: Changed from int to float, due to the fact that Anko mentioned.
> 2 votes

---
Tags: algorithm
---


# Question
Title: Why does the text of my label objects overlap?
I am having a problem with labels in my GUI:

I have looked for solutions online but not found something solid enough to fix this problem. Has anyone ever come across this? Here is my GUI function. When the variable changes it overlaps with the previous one:

```
 void OnGUI() {
    if(selected) //set your selected variable in the OnMouseDown method
        GUI.Label(new Rect(40, 50, 400, 22), GetComponent<MeshFilter>().mesh.name);

}

```

# Answer
Make sure you understand what you're doing. You likely have this script attached to multiple objects. You're actually drawing multiple labels in the same spot. The problem is you're using the same script to put the GUI labels at (40, 50).

Two solutions come to mind:

* Define a position in your script where the GUI label should appear. Then, in the inspector, you'd edit the position differently for each object the script is attached to.

Example:

```
public Vector2 NamePosition = Vector2.zero;

void OnGUI() {
if(selected) //set your selected variable in the OnMouseDown method
    GUI.Label(new Rect(NamePosition.x, NamePosition.y, 400, 22),
              GetComponent<MeshFilter>().mesh.name);
}

```
* Dynamically place the label depending on the position of the object on screen:

Example:

```
void OnGUI() {
if(selected) //set your selected variable in the OnMouseDown method
    Vector3 screenPos = Camera.main.WorldToScreenPoint(transform.position);
    GUI.Label(new Rect(screenPos.x, Screen.height - screenPos.y, 400, 22),
              GetComponent<MeshFilter>().mesh.name);
}

```

Additionally, you might want to consider notifying the scripts when they're no longer selected. This means when you set the `selected` bool to `true` on one script, you should set it to `false` on all the other scripts.
> 1 votes

# Answer
If the problem isn't the one described by Byte56 and you only have the script attached to a single object, then check to make sure you have at least one camera that has Clear Flags set to 'Solid Color' or 'Skybox' (as opposed to 'Don't clear' or 'Depth Only').
> 0 votes

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


title: Can't sample texture in HLSL using DX11

text:
# Question
Title: Can't sample texture in HLSL using DX11
Environment:

* Windows 7 x64
* Visual Studo 2012
* DirextX11
* HLSL Shader Model 5
* Ogre 1.9

Okay, so I'm trying to sample a texture in my pixel shader but I'm coming across some strange problems. Here's the pixel shader:

```
struct PS_INPUT {
    float4 pos : SV_POSITION;
    float2 uv  : TEXCOORD0;
};

Texture2D tex0;
SamplerState s0;

float4 pixel_shader(PS_INPUT input) : SV_TARGET {
    float3 texSample = tex0.Sample(s0, input.uv);

    float4 color = float4(1,1,1,1);

    color.xyz = texSample;

    return color;
}

```

If you want / need it here's the ogre .material definition:

```
material simpleMat
{
    technique
    {
        pass simpleMat
        {
            vertex_program_ref vertex_shader {}
            fragment_program_ref pixel_shader {}
        }

        texture_unit 0
        {
            texture diffuse.png 2d
            tex_address_mode wrap
        }
    }
}

```

This produces mostly black on my object, but I get 2 random white pixels. But here's the strangest part. When I debug the pixel shader in visual studio texSample nearly always equals zero. So I decided to try something crazy, I debugged the program, got the value of input.uv and then modified the shader to use these values explicitly. When I do this texSample actually contains the correct color value. So yeah... any help is much appreciated!

Rojuinex

**EDIT**

Here is a snapshot that shows the issue in detail:

http://www.pasteall.org/pic/show.php?id=74835

**EDIT 8/4/2014**

Upon further investigation I have discovered that the further the object is from the camera, the darker the texture becomes. If the camera is right up against the object, the texture has the right color values, but as it moves away the sampler returns darker and darker values until they are black.

# Answer
GuyRT is right. For some reason Ogre 1.9 + RenderSystemDX11 has problems generating the texture mipmap levels. I'm not sure the cause of this, but it is easily fixed by using Microsoft DirectX Texture Tool to generate the mip levels in the .dds
> 0 votes

---
Tags: hlsl, directx11, ogre, fragment-shader
---


# Question
Title: A* in 2D grid with obstacles in between graph nodes
I am using standard A\* (and Jump Point Search) for pathfinding in my 2D game. A map in this game is a simple 2D grid (tile-based). A node (i.e. grid cell) in my map graph can either be blocked or walkable. That works fine so far.

Now I got a new requirement: There can be obstacles in between cells as well, i.e. walls. I thought the easiest way to implement this is to make the cell "behind" a wall an obstacle while searching for a path. However, that does not really work, because if I search for a path from the other side of the wall, then "behind" is also on the other side...

So my question: Is there any "best practice" to implement this, or, if not, what are your ideas?

# Answer
A\* is defined on a graph structure, which consists of nodes (cells) and edges between the nodes (i.e. the walls between cells, or corners). When you make an entire cell not walkable, you remove an entire node from the graph. When you place something between two cells, you effectively remove the edge which is normally there.

Most of the time the neighbors of (x,y) are (x+-1,y-1),(x+-1,y),(x+-1,y+1), and (x+-1,y), for a total of 8 neighbors. If a neighbor is not walkable, then you remove it from this set of neightbors. Likewise, if there is a wall between (x,y) and (x,y+1), then they aren't neighbors, even though they are adjacent. So you don't need to change the properties of the other cell, just filter it out when you are finding the neighbors of a certain cell. The important thing is that the other cell can have it's own distance and everything; you aren't removing it in any way. Instead you remove the edge *between* two cells.
> 3 votes

---
Tags: path-finding
---


# Question
Title: Asymetrcal Public Key (Host it on a server or distribute with launcher)?
I am currently building a launcher for the front end of my game and I am wondering if I should host the public key on a server and have the launcher pull the data as and when needed, or should I distribute it packaged with the launcher. My thinking is that if I distribute it I will need to update the launcher should I need to change the keys but if I host it then I won't need to I just need to swap the keys on the server. I ask because I am unsure if this would dramatically increase load/traffic on the site should the game become popular.

# Answer
Always downloaded from the server. If the private key is compromised then you can easily create a new one.

If you're worried about load when the game gets popular, you can monetize your website or sell your game to pay for server upgrade/rent.
> 1 votes

---
Tags: encryption, authentication
---


# Question
Title: Cocos2d: Positioning Sprites in complex layout patterns
I'm wondering if anyone has suggestions for how to manage the positioning of many sprites in pre-set and complicated patterns? Currently the brute-force method is to painstakingly code each sprite into its place. However, ideally, I would like to not have to code it directly, but instead read the sprite positions in from a file (or some other data source). Are there any solutions out there that do this?

# Answer
You're on iOS using Objective-C, I assume, so use PLIST files.

XCode has an excellent PLIST editor. NSDictionary lets you load a PLIST file with a single method call:

```
NSDictionary * plistDict = [NSDictionary dictionaryWithContentsOfFile:@"test.plist"];

```

From that, it is very easy to automate. Just load the dictionary and set the sprite position:

```
double x = [[plistDict objectForKey:@"sprite_pos_x"] doubleValue];
double y = [[plistDict objectForKey:@"sprite_pos_y"] doubleValue];

sprite.position = ccp(x,y);

```

If you change the sprite position in the PLIST, there is no need to recompile. With a bit of work, you can even add runtime reloading of modified files.
> 0 votes

---
Tags: cocos2d-iphone
---


# Question
Title: How to set up a client-server architecture for a browser based game
I'm really curious about how to set up a game so like Hayday or Clash Of Clans, especially with regards towards the server-client architecture. How does one set up such an artitecture? What are the techinical details?

Thanks a lot!

# Answer
> 0 votes
The question is too broad, but i will start anyway,and if you are looking for specific tutorials, you need google, i know about architecture, and what all factors you might need to consider while writing down the tiptops of your game base interaction.

The main question is whether your game is going to be in real time, turn based, or long-delay based (e.g., email chess). Another question is whether or not you are going to be freezing the state for subsequent reloads.

I would highly recommend figuring out in advance whether or not all players in the same game are going to be hosted on the same server (e.g., 1000 of 5 player matches compared to 5 matches of 1000 players each). If possible, go with the first and stick everyone who is in the same game under the same server. You will have a hard enough time synchronizing multiple clients to one server, rather than having multiple servers against which players are synchronized. Otherwise, the definition of consistency is problematic.

If possible, have each client communicate with the server and then the server distributing updates to the clients. This way you have one "official state", and can do a variety of conflict resolutions, phantoms, etc. Peer to peer gives better performance in faster games (e.g., FPSs) but introduces tons of problems.

Now for implementation of this architecture, i suggest you use linux network programming, cause windows is too vague, and errors might bundle up in future:

1. Create 2 instances of server as back design, you can have more , but main design should consist of one master server, and other slave sever, or master server can fork new servers with { fork();

```
if(pid!=0){//child server interaction};

else(//optional block for authentication of players, you need extra child server for each user)

//parent process}

```

1. The less data you transfer the smaller buffers you need on server -\> more clients on one machine and also a bit faster responses
    2. Three Rings server ARCH For server and client side implementation , you might check out .
    3. server setup details , you might require need

~Client specifics:

* Initiates requests
* Waits for and receives replies
* Typically interacts directly with end-users using a graphical user interface
* Usually connects to a small number of servers at one time

~server specifics

* Waits for requests from clients
* Upon receipt of requests, processes them and then serves replies
* Typically does not interact directly with end-users
* Usually accepts connections from a large number of clients

---
Tags: server, client-server, browser-based-games
---


# Question
Title: C++ OpenGL / SDL2 VBO -- Depth problem / Transparency
I got a problem with my VBO. When having textures. The far blocks overlay the near ones.

I tried editing the alpha, depth buffer, the VBO byte allocation. Nothing works for me...

The FAR plane is overlapping the NEAR plane.

```
    //Alpha
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LEQUAL);
glEnable(GL_CULL_FACE);
glDisable(GL_MULTISAMPLE);

glDepthMask(GL_TRUE);

```

# Answer
It's not clear from your image if that is a single plane and the far faces are overlaying the near ones, or if you are rendering several objects and the far ones overlay the near ones.

If it's the second case, your problem is that you need to either sort the itens back to front or disable the depth test. If you render them out of order, OpenGL will discard any fragment that is drawn behind a fragment closer to the camera. If you disable the depth test, everything will be drawn, but solid objects won't be tested either. Sorting is probably the best alternative if you plan on mixing solid/transparent itens. But you will need to keep them on different lists. Sort transparent ones back to front and solid ones front to back.

There are other issues with transparency and rendering. Some cases where transparent objects intersect may give you the wrong results. Depth Peeling is a technique that can be used to avoid that (Though I never need it myself, so I may be wrong here)
> 0 votes

---
Tags: opengl, c++, vbo
---


title: Shooting based off mouse position

text:
# Question
Title: Shooting based off mouse position
I'm trying to shoot bullets where the mouse is aiming using one image as a test. I'm trying to get the mechanics like this

I have some kind of algorithm to handle that but the results arn't too good. Can anyone help me make the bullet fly towards the mouse's exact location? My code:

```
public class GameScreen implements Screen{

  MyGame mg;

  SpriteBatch batch;
  Sprite s;

  float timeStep=1f/60f;
  float turretX=10f;
  float turretY=10f;
  float bulletSpeed=0.1f;

  float bulletX=turretX;
  float bulletY=turretY;

  float dirX= 100 - turretX;
  float dirY= 100 - turretY;

  public GameScreen(MyGame mg) {
     this.mg = mg;

     float dirLength= (float) Math.sqrt(dirX*dirX + dirY*dirY);
     dirX=dirX/dirLength;
     dirY=dirY/dirLength;

  }

  @Override
  public void render(float delta) {
     Gdx.gl.glClearColor(1F, 1F, 1F, 1F);
      Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
     update(delta);

     batch.begin();
        batch.draw(s, bulletX, bulletY);
     batch.end();

  }

  public void update(float delta) {
     if(Gdx.input.isKeyPressed(Keys.SPACE)) {
     dirX= Gdx.input.getX() - turretX;
     dirY= Gdx.input.getY() - turretY;
     }

     bulletX=bulletX+(dirX*bulletSpeed*timeStep);
     bulletY=bulletY+(dirY*bulletSpeed*timeStep);

  }

  @Override
  public void resize(int width, int height) {
     // TODO Auto-generated method stub

  }

  @Override
  public void show() {
     batch = new SpriteBatch();
      s = new Sprite(new Texture(Gdx.files.internal("HUDS/button_Back.png")));

  }

  @Override
  public void hide() {
     // TODO Auto-generated method stub

  }

  @Override
  public void pause() {
     // TODO Auto-generated method stub

  }

  @Override
  public void resume() {
     // TODO Auto-generated method stub

  }

  @Override
  public void dispose() {
     // TODO Auto-generated method stub

  }

  }

```

# Answer
> 0 votes
Try: position + directon.

The method here is called raycasting. IT can be used in various ways.

(cannonPosition & cannonDirection are vector2's)

Like. `vector2 bulletPosition = cannonPosition + cannonDirection * i`

Just. do:

```
float bulletSpeed = 0.5f;
float shootRange = Gun.getShootDistance(); /*(EG: 100)*/
float gravityConstant = 0.1f;

float gravity = 0;

vector2 bulletPosition = (vector2)null;

for(float i = 1; i < shootRange; i+=bulletSpeed)
{
    bulletPosition = cannonPosition + cannonDirection * i;

    bulletPosition.y = bulletPosition.y - gravity;

    gravity += gravityConstant;
}

```

# Answer
> 0 votes
It is actually very simple, I have this exact thing in my game. I will solve it in a pseudo code manner.

1. Obtain the coordinates of the gun that is firing. var gunPosition;
2. Obtain the coordinates of the target. var targetPosition;
3. Subtract the targetPosition FROM the gunPosition and store it in a new variable. var difference;
4. Now you can either compute the firing angle like this: `atan2(difference.y/difference.x)` or normalize the difference vector and use that.

```
float dirLength=(float) Math.sqrt(difference.x*difference.x + difference.y*difference.y);
dirX=difference.x/dirLength;
dirY=difference.y/dirLength;

```

That should be the correct direction. If you would like to know how this is working, I suggest you learn a little Trigonometry. There are tons of tutorials on it on youtube.

# Answer
> -2 votes
Without screenshots or an idea about where the origin and target are, and what kind of coordinates you're registering for your mouse, it's really just blind guessing on my side.

I think your problem is here:

```
float dirLength= (float) Math.sqrt(dirX*dirX + dirY*dirY);
dirX=dirX/dirLength;
dirY=dirY/dirLength;

```

You're using distance between points to get the euclidian distance between the mouse and the turret.

This is not what you want to do. You want to use either sine law or cosine law to calculate the vector's components (horizontal and vertical).

There's a good, visual example here, albeit one that uses forces. In your case, you're using distance, not force.

Once you solve that, you will have correct values for `dirX` and `dirY`. You can also scale them proportionally down if they are too large (eg. moves too fast).

---
Tags: java, mathematics, libgdx, vector
---


# Question
Title: A*Pathfinding lose target after spawning from script?
I have been using A\*Path finding to enable object tracking. It works fine if I have both objects on the scene at the same time.

However, if I were to use a script to spawn the seeking object instead, it will only track the first path to the object and not repath again.

I am using the default AI Follow script and a prefab variable as the object to be tracked (which is an empty child game object to a moving character).

Code :

```
import Pathfinding;

//var tankTurret : Transform;
var tankBody : Transform;
//var tankCompass: Transform;
var turnSpeed : float = 10.0;

var targetPosition : Vector3;
var seeker : Seeker;
var controller : CharacterController;
var path : Path;
var speed : float = 100;
var nextWaypointDistance : float = 3.0;
private var currentWaypoint : int = 0;

function Start()
{
    //targetPosition = GameObject.FindWithTag("GTO").transform.position;
    GetNewPath();
}

function GetNewPath()
{
    Debug.Log("GETTING NEW PATH!");
    seeker.StartPath(transform.position,targetPosition,OnPathComplete);
}

function OnPathComplete(newPath : Path)
{
    if(!GetNewPath.error)
    {
        path = newPath;
        currentWaypoint = 0;
    }
}
function FixedUpdate()
{
    if(path==null)
    {
        return;
//          Debug.Log("NO PATH!?");
    }
    /*if(currentWaypoint >= path.vectorPath.Length)
    {
        return;
    }*/

    var dir : Vector3 = (path.vectorPath[currentWaypoint]-transform.position).normalized;

    controller.SimpleMove(dir);

    //tankCompass.LookAt(path.vectorPath[currentWaypoint]);
    //tankBody.rotation = Quaternion.Lerp(tankBody.rotation, tankCompass.rotation, Time.deltaTime*turnSpeed);

    if(Vector3.Distance (transform.position,path.vectorPath[currentWaypoint]) < nextWaypointDistance)
    {
        currentWaypoint++;
    }

}

```

Any help will be greatly appreciated.

# Answer
* If you're too far from the target **and** there is no current path to navigate
    + Compute a new path to the target.
* Otherwise
    + Apply your game logic here (attack, heal, talk, etc.)
> 1 votes

# Answer
```
function OnPathComplete(newPath : Path)
{
    if(!newPath.error)
    {
        path = newPath;
        currentWaypoint = 0;
        GetNewPath();
    }
}

```
> 0 votes

---
Tags: unity, 3d, ai, path-finding
---


# Question
Title: Algorithm to modify a color to make it less similar than background
I'm creating a demo of 20 balls bouncing each other, with a background filled with a solid color. Color for each ball is chosen randomly with `randint(0, 255)` for each R, G, B tuple component.

Problem is some balls end up with a color that is very similar to background, making them hard to see. I would like to avoid that, either by rolling another color if the chosen one is ***too similar*** (within a given threshold), or by ***moving it away*** from the background color.

How to calculate a ***similarity index*** to use as a threshold? Or how to transform a color to make it, say, ***less blue-ish***?

*Obvious disclaimer: I know nothing about color theory, so I don't know if the above concepts even exists!*

I'm coding in python, but I'm looking for concepts and strategies, so pseudo-code is fine (or just the theory).

EDIT:

To clarify a few points:

* Each ball have its own random color. I'd like them to remain as random as possible, and to explore as much as possible of the color space (be it RGB or HSV, `pygame` accepts both formats for defining color)
* I'd just like to avoid each color of being "too close" to background. Problem is not just about hue: I'm perfectly OK with a light-blue ball against a dark-blue background (or a "full-blue" against a "white-ish" blue, etc)
* For now, I don't care if a ball ends up with a color similar (or even identical) to another ball. Avoiding that is a bonus, but it's a minor issue.
* Background color is a constant, single RGB color. For now I'm using "basic" blue `(0, 0, 255)`, but I'm not settled with that. So consider the background to be of an *arbitrary* color (with arbitrary hue, brightness, saturation, etc).

EDIT2:

***TL,DR version:*** *Just give a way to create X random colors so that none "fades in too much" against a background of arbitrary (but single and constant) color*

# Answer
You can use the fact that colors make up a (three dimensional) color space and calculate a distance in this color space. You then need to define a metric in this color space to find the distance between two colors.

E.g. the distance in a euclidean space between two points x = (x1, x2, x3) and y = (y1, y2, y3) is given by d(x,y) = sqrt( (y1-x1) * (y1-x1) + (y2-x2) * (y2-x2) + (y3-x3) * (y3-x3) ).

Now you can calculate the distance between a balls color and your background color and if it is too small, create a new random color and test again.

You will find that neither RGB nor even HSV are good color spaces for this task. The wikipedia article on color difference employs the L*a*b color space and gives several possible metrics.

There is also a diskussion on stackoverflow on the topic.
> 32 votes

# Answer
The United Nations web accessibility standards page (http://www.un.org/webaccessibility/1\_visual/13\_colourcontrast.shtml) does indicate a standard for ensuring proper **text** contrast on websites, keeping in mind that some users are colorblind. This might be particularly important for you since some of your users may be colorblind as well (would be hard to tell a red ball from a green background if they have the same luminance).

The UN page points to the Juicy Studios Luminosity Colour Contrast Ratio Analyser at (http://juicystudio.com/services/luminositycontrastratio.php#specify) which states text on background must have a contrast ratio of 4.5:1, except for what I believe to be similar to your case:

* Large Text: Large-scale text and images of large-scale text have a contrast ratio of at least 3:1

Now what's a contrast ratio? Following hyperlinks further (this is fun!) we get to a W3 page that defines contrast ratio as:

```
Contrast Ratio = (L1 + 0.05)/(L2 + 0.05)

```

Where L1 and L2 are the relative luminences of the colors. L1 is the **more** luminant color, L2 is the **less** luminant color. Again, we follow the link to the same W3 page that specifies:

```
L = 0.2126 * R + 0.7152 * G + 0.0722 * B where R, G and B are defined as:

if RsRGB <= 0.03928 then R = RsRGB/12.92 else R = ((RsRGB+0.055)/1.055) ^ 2.4
if GsRGB <= 0.03928 then G = GsRGB/12.92 else G = ((GsRGB+0.055)/1.055) ^ 2.4
if BsRGB <= 0.03928 then B = BsRGB/12.92 else B = ((BsRGB+0.055)/1.055) ^ 2.4
and RsRGB, GsRGB, and BsRGB are defined as:

RsRGB = R8bit/255
GsRGB = G8bit/255
BsRGB = B8bit/255

```

***NOTE****: The caret symbol **^** above refers to exponentiation (x²)*

An we have a pretty good framework for a contrast algorithm (that's colorblind friendly!)

* Determine R, G, B values for each color
* Determine Luminance for each color
* If the Contrast Ratio of the more luminant color to the least luminant color is less than 3, reroll!
> 8 votes

# Answer
Using RGB values by generating a random `0-255` value for each component might not only create colors that are similar to the background, you can also end up with very similar colors for the balls.

I'd probably choose a less random approach and create colors that are guaranteed to be different instead. You could create a color for each ~32 degrees in the hue range and alternate the brightness or saturation (use HSV color-model instead of RGB).

So something like this:

```
numColors = 20;
stepSize = 360 / (numColors / 2 + 1); // hue step size
for(i = 0; i < numColors; i++){
    color = HSV(i / 2 * stepSize, 0.5 + (i % 2) * 0.5, 1.0)
}

```

which will create 20 colors, nicely distributed. This assumes you're using integer math, so `i = 0` and `i = 1` will create the same hue value.

Of course this doesn't scale too well.. if you have 100 color values to create, the hue spacing might not be enough and you'll end up with similar colors again. In that case you could also vary the `V` (brightness) value.

I don't know what your background color is like, but HSV makes it also easier to compare colors (just compare the 3 components and don't forget that HUE is circular (0 == 360)).

**UPDATE:**

Since I didn't really answer your question but rather provided another approach, here's how an algorithm for an arbitrary background and completely random colored balls could look like (this is a brute-force approach but should work fine for your use-case):

```
// background color, currently equals RGB(0, 0, 255)
bg = HSV(240, 1.0, 1.0)

// number of colors to create is equal to the amount of balls
numColors = balls.length

// set threshold to compare colors. you can tweak this to your liking
threshold = 0.15

for(i = 0; i < numColors; i++){
    do {
        // assuming rnd returns a random float 0-1 inclusive
        color = HSV(rnd() * 360, rnd(), rnd())
        // calculate delta values, normalize hue to 0-1
        dH = (180 - abs(abs(bg.h - color.h) - 180)) / 360
        dS = bg.s - color.s
        dV = bg.v - color.v
        // "distance" between bg and color
        difference = sqrt(dH * dH + dS * dS + dV * dV)
    } while(difference < threshold)

    ball[i].color = color
}

```
> 2 votes

# Answer
Since you din mentioned you got a stationary background, the color of the balls can still be a random but they have to fall at certain ranges that still compliments the background.

**Basics.** Before we do that you need to know the basics. Consider the following colors:

```
Black   #000000 rgb(0,0,0)
Red     #FF0000 rgb(255,0,0)
Green   #00FF00 rgb(0,255,0)
Blue    #0000FF rgb(0,0,255)
Yellow  #FFFF00 rgb(255,255,0)
Cyan    #00FFFF rgb(0,255,255)
Pink    #FF00FF rgb(255,0,255)
Gray    #C0C0C0 rgb(192,192,192)
White   #FFFFFF rgb(255,255,255)

```

Mixture of Colors RGB \[(0..255),(0..255),(0..255)\] creates new colors as above.

**Computing for Negative Colours** Computing for negative color is just like transform red in cyan, green in purple, blue in yellow.

```
Red     #FF0000 rgb(255,0,0) ->     Cyan    #00FFFF rgb(0,255,255)
Green   #00FF00 rgb(0,255,0) ->     Purple   #FF00FF    rgb(255,0,255)
Blue    #0000FF rgb(0,0,255) ->     Yellow  #FFFF00 rgb(255,255,0)

```

**Complementary Color**

As per reference on Computing complementary colors: http://serennu.com/colour/rgbtohsl.php

About HSL

HSL expresses colours in terms of their Hue, Saturation and Lightness, giving a number for each of these three attributes of the colour.

The Hue is the colour's position on the colour wheel, expressed in degrees from 0° to 359°, representing the 360° of the wheel; 0° being red, 180° being red's opposite colour cyan, and so on.

Saturation is the intensity of the colour, how dull or bright it is. The lower the saturation, the duller (greyer) the colour looks. This is expressed as a percentage, 100% being full saturation, the brightest, and 0% being no saturation, grey.

Lightness is how light the colour is. Slightly different to saturation. The more white in the colour the higher its Lightness value, the more black, the lower its Lightness. So 100% Lightness turns the colour white, 0% Lightness turns the colour black, and the "pure" colour would be 50% Lightness.

It's easier to see the difference between Saturation and Lightness than to explain it. If you want to clarify, try viewing the Lightness and Saturation variations on the colour calculator page, choosing quite a bright colour as your starter colour.

So HSL notation looks like this, giving the Hue, Saturation and Lightness values in that order:t

Red: 0° 100% 50% Pale pink: 0° 100% 90% Cyan: 180° 100% 50% Here are the Steps:

1. Convert your colour to HSL.
2. Change the Hue value to that of the Hue opposite (e.g., if your Hue is 50°, the opposite one will be at 230° on the wheel — 180° further around).
3. Leave the Saturation and Lightness values as they were.
4. Convert this new HSL value back to your original colour notation (RGB or whatever).

Sites like EasyRGB.com can do generic conversion for you from RGB to HSL or vice versa.

**Programming** Example done in PHP as per reference

Conversion from RGB to HSL

The value above Blue #0000FF rgb(0,0,255) can be presented as Red Hexadecimal 00 + Green Hexadecimal 00 + Blue Hexadecimal FF

```
$redhex  = substr($hexcode,0,2);
$greenhex = substr($hexcode,2,2);
$bluehex = substr($hexcode,4,2);

```

It can also be presented as Red Decimal 0 + Green Decimal 0 + Blue Decimal 255

```
$var_r = (hexdec($redhex)) / 255;
$var_g = (hexdec($greenhex)) / 255;
$var_b = (hexdec($bluehex)) / 255;

```

Now plug these values into the rgb2hsl routine. Below is my PHP version of EasyRGB.com's generic code for that conversion:

Input is $var\_r, $var\_g and $var\_b from above Output is HSL equivalent as $h, $s and $l — these are again expressed as fractions of 1, like the input values

```
$var_min = min($var_r,$var_g,$var_b);ttt
$var_max = max($var_r,$var_g,$var_b);
$del_max = $var_max - $var_min;

$l = ($var_max + $var_min) / 2;

if ($del_max == 0)
{
        $h = 0;
        $s = 0;
}
else
{
        if ($l < 0.5)
        {
                $s = $del_max / ($var_max + $var_min);
        }
        else
        {
                $s = $del_max / (2 - $var_max - $var_min);
        };

        $del_r = ((($var_max - $var_r) / 6) + ($del_max / 2)) / $del_max;
        $del_g = ((($var_max - $var_g) / 6) + ($del_max / 2)) / $del_max;
        $del_b = ((($var_max - $var_b) / 6) + ($del_max / 2)) / $del_max;

        if ($var_r == $var_max)
        {
                $h = $del_b - $del_g;
        }
        elseif ($var_g == $var_max)
        {
                $h = (1 / 3) + $del_r - $del_b;
        }
        elseif ($var_b == $var_max)
        {
                $h = (2 / 3) + $del_g - $del_r;
        };

        if ($h < 0)
        {
                $h += 1;
        };

        if ($h > 1)
        {
                $h -= 1;
        };
};

```

So now we have the colour as an HSL value, in the variables $h, $s and $l. These three output variables are again held as fractions of 1 at this stage, rather than as degrees and percentages. So e.g., cyan (180° 100% 50%) would come out as $h = 0.5, $s = 1, and $l = 0.5.

Next find the value of the opposite Hue, i.e., the one that's 180°, or 0.5, away (I'm sure the mathematicians have a more elegant way of doting this, but):

Calculate the opposite hue, $h2

```
            $h2 = $h + 0.5;

            if ($h2 > 1)
                    {
                            $h2 -= 1;
                    };

```

The HSL value of the complementary colour is now in $h2, $s, $l. So we're ready to convert this back to RGB (again, my PHP version of the EasyRGB.com formula). Note the input and output formats are different this time, see my comments at the top of the code:

Input is HSL value of complementary colour, held in $h2, $s, $l as fractions of 1 Output is RGB in normal 255 255 255 format, held in $r, $g, $b Hue is converted using function hue\_2\_rgb, shown at the end of this code

```
    if ($s == 0)
    {
            $r = $l * 255;
            $g = $l * 255;
            $b = $l * 255;
    }
    else
    {
            if ($l < 0.5)
            {
                    $var_2 = $l * (1 + $s);
            }
            elset
            {
                    $var_2 = ($l + $s) - ($s * $l);
            };

            $var_1 = 2 * $l - $var_2;
            $r = 255 * hue_2_rgb($var_1,$var_2,$h2 + (1 / 3));
            $g = 255 * hue_2_rgb($var_1,$var_2,$h2);
            $b = 255 * hue_2_rgb($var_1,$var_2,$h2 - (1 / 3));
    };

   // Function to convert hue to RGB, called from above

    function hue_2_rgb($v1,$v2,$vh)
    {
            if ($vh < 0)
            {
                    $vh += 1;
            };

            if ($vh > 1)
            {
                    $vh -= 1;
            };

            if ((6 * $vh) < 1)
            {
                    return ($v1 + ($v2 - $v1) * 6 * $vh);
            };

            if ((2 * $vh) < 1)
            {
                    return ($v2);
            };

            if ((3 * $vh) < 2)
            {
                    return ($v1 + ($v2 - $v1) * ((2 / 3 - $vh) * 6));
            };

            return ($v1);
    };

```

And after that routine, we finally have $r, $g and $b in 255 255 255 (RGB) format, which we can convert to six digits of hex:

```
    $rhex = sprintf("%02X",round($r));
    $ghex = sprintf("%02X",round($g));
    $bhex = sprintf("%02X",round($b));

    $rgbhex = $rhex.$ghex.$bhex;

```

$rgbhex is our answer — the complementary colour in hex.

Since your color background is blue or 0,0,255 the HSL is

Hue (H): 240 degrees / Saturation (S):100% / Lightness (L):4.9%

opposite of 240 is 60 in a circle then convert back to RGB gives a value of #181800
> 1 votes

# Answer
I'd like to expand upon @ashes999's idea of creating an outline.

My code is going to be as python-like as I can off the top of my head (I've never written a line of python in my life, but I've glanced over a book once or twice).

```
def lerp(a,b,value): # assuming your library was not kind enough to give you this for free
    return a + ((b - a) * value);

def drawRandomBall(bgColour,radius,point):
    var ballColour = Colour(random(0,255),random(0,255),random(0,255);
    var outlineColour = Colour(lerp(bgColour.R,255 - ballColour.R,0.5),lerp(bgColour.G,255 - ballColour.G,0.5),lerp(bgColour.B,255 - ballColour.B,0.5));
    fillCircle(point,radius+1,outlineColour);
    fillCircle(point,radius,ballColour);

```

It may not look particularly pretty and it's not really ideal for production code, but it should suffice as a quick-fix. I haven't tested the code as I don't exactly have a "balls bouncing around the screen" program to hand that I can mutilate to test it.

---

**Edit:**

Upon seeing the actual code in use, the situation has flipped on its head, so instead I offer this solution.

Replace lines 276-284 with the following:

```
# Colour generator
def generateColourNonBG(leeway):
    color = (randint(0,255), randint(0,255), randint(0,255))
    while color[0] >= BG_COLOR[0]-leeway and color[0] =< BG_COLOR[0] + leeway and
    color[1] >= BG_COLOR[1]-leeway and color[1] =< BG_COLOR[1] + leeway and
    color[2] >= BG_COLOR[2]-leeway and color[2] =< BG_COLOR[2] + leeway:
        color = (randint(0,255), randint(0,255), randint(0,255))

# Ball generator
def generateBall():
    Ball(generateColourNonBG(5),
                   radius=randint(10, radius),
                   position=[randint(100, screen.get_size()[0]-radius),
                             randint(100, screen.get_size()[0]-radius)],
                   velocity=[randint(50, 50+vel[0]), randint(50, 50+vel[1])],
                   )

# Create the balls
balls = pygame.sprite.Group()
for _ in xrange(BALLS):
    balls.add(generateBall())

```

In this new simplified version, a factory method spits out the balls, and a specialised method generates the colours. The colour generator tests the randomly generated colour to see if it is within a certain range of closeness to the background colour. A colour is considered too close to the BG colour if all three of its colour channels are within `leeway` either side of BG. So if leeway is 0, only colours that exactly match BG are refused. I have chosen 5 as the default, which refuses the BG colour and the 5 colours either side. Since BG colour is white, I'm not sure if it will refuse black because the digits wrap round. That can be avoided with use of min and max functions, but I left them out for the sake of brevity.
> 1 votes

# Answer
For a RGB format, this seems to work well enough and is trivial:

diversity\_score = (abs(r1 - r2) + abs(g1 - g2) + abs(b1 - b2)) / 765.0

This will give you a score between 0.0 and 1.0. The lower, the harder it is to distinguish two colors.

It should be obvious, but for the sake of completeness: the r, g, b values must be cast to a floating point number first, and it is assumed that their maximum value is 255.
> 1 votes

---
Tags: algorithm, color
---


# Question
Title: Is there a good alternative to a world state data structure?
How do you avoid one big data structure containing all the current world state ?

Let's pretend we're in a real-time strategy game, how would you code a skill that decrease mana of units around it ?

With a world state it would look like that :

```
class MySpell : ISkillWithoutTarget
{
  void Cast(Unit caster, World world)
  {
    foreach (Unit target in world.Units)
    {
      if (target.distanceWith(caster) <= N)
      {
        target.Mana -= X;
      }
    }
  }
}

```

So my question is : Does a good alternative to "world object" exist ? Or world object is the best way to deal with these kind of interactions ?

I'm not looking for a way to organize/optimize my big data structure, but how to avoid it. I would prefer not using this architecture because almost every piece of code can touch every game object. I'm looking for decoupling to avoid ending with bug almost untraceable.

# Answer
> 5 votes
Because operations dealing with objects and their locations, such as collision detection and filtering nearby objects, are so heavily used in games, it is common practice to use one or more spatial data structures to describe your world. Some examples of these structures are grids, octrees, or the classic scene graph - a tree storing relative transformations in each edge. They are a perfect example of the tradeoff of using a little more memory to reduce algorithmic complexity.

These structures are useful because they allow you to exclude large numbers of objects from queries simply based on their approximate locations. For example, with an octree or a grid, you only need to be concerned with objects in the cells that intersect your query volume, and you can discard the objects in other cells, allowing you to prune lots of objects using only a few AABB checks.

However, I would refrain from having these structures actually store the objects themselves, and instead store pointers or references. If you do this, you can keep your objects tightly packed to improve iteration performance while allowing your scene graph to constantly adjust as your objects move around.

---

If you want to implement a messaging system, I would still use spatial data structures so that you can skip sending messages to objects that are too far away to care. In that case, you might implement a "message radius" and have the message dispatch system automatically make the query using, for example, an octree for objects within that radius, then send the message to the objects that the query returns. You'll save a lot of precious cycles that don't deserve to be wasted on sending messages to objects that don't need to receive them!

---
Tags: architecture, software-engineering, game-loop
---


# Question
Title: Is Physics a prerequisite to learn Unity3D
I have got a basic knowledge about the Unity 3D platform but I coding in Unity has not been that easy for me. For the simple reason I can see is, I cannot understand which function to use for what purpose, for example, velocity, angular velocity or torque. My question is do I need to learn Physics and Trignometry to properly learn the usage of functions in Unity script. What level of knowledge should I need to poses with respect to Physics and Trignometry in order to properly understand the code in Unity? Please be specific as I am not a science student and I have really very basic knowledge in Unity.

# Answer
Well, you do need a basic understanding of physics, but I mean like what they teach in physics class in highschool. Assuming you went to highschool, then no there isn't any additional knowledge of physics that you need as a prerequisite.

That said, you're going to be learning a number of new concepts and/or applying concepts in ways that are new, because there frankly aren't many other places other than game development where that stuff would come up. I mean sure, high-end car engineering for example, but it's hardly the case that you need a degree in mechanical engineering before you can program a game.

Don't worry that you're missing prerequisite knowledge, but do accept that you're going to encounter unfamiliar concepts, so you're going to have to lookup what they mean and then spend lots of time experimenting.

---

Now that's with regards physics. As for trigonometry, that's a bit more crucial. Again, not much more than what they teach in highschool, but a lot of people reject even that level of math and you're going to need to be comfortable with things like sines and the Pythagorean Theorum. Depending on exactly what you program, you might also need to use some 3D math concepts, but again it's not really a prerequisite and more stuff you can learn as you go.

Here's one good resource http://blog.wolfire.com/2009/07/linear-algebra-for-game-developers-part-1/
> 2 votes

---
Tags: unity, physics, trigonometry
---


# Question
Title: Is texture 1D array a valid way to handle object coloring?
I would like to render game UI, and for that I need rectangles. However, since a button could be textured just as well as solid color or (multistop)gradient a problem arises. I would also like all types of rectangles(buttons) somehow at least partially uniform at handling.
I have been puzzled by this issue for quite a time and idea came across my mind - what if I stored colors to a 1D texture array and treat all rectangles as textured. Could you give me some example how to do this? Or event better a reason not-to solve it this way and point to better solution?

# Answer
> 1 votes
You could do this:

* Create a texture holding all the colors you want.
* For the actual button geometry, set the texture coordinates to the appropriate region of the color texture (they can all be the same value, in fact).

---
Tags: opengl, textures
---


# Question
Title: How to send components in an ECS System?
I'm trying to send a CreateEntity packet from a server to client, but I can't figure out how to send the information about components over the network. I gave each component an ID, but then I realized I'd have to send the associated data (E.X size of entity for the transform, etc). Is the easiest way to just create an Enum of entities and have the client create the components based on what it knows about the entities? I'd prefer to not do that as it makes modding much harder.

# Answer
> 2 votes
Serialization can be implemented in any number of ways, but I would strongly suggest that you find ways to decouple entity/component semantics from network serialization as it will make it easier as new things are added to keep them in sync.

For for creating of entities, I would have a packet that gets sent perhaps on some periodic basis that contains all entities within an area of interest radius. This packet could be sent once the player enters the game world or as objects enter/leave the interest radius. Such a packet would be a combination of necessary attributes to begin rendering the object, such as but not limited to:

1. GUID
2. Object Type (NPC, Dynamic Object, likely a finite list here).
3. Transform (position, rotation, perhaps scale)
4. Race & Gender (in case of NPCs)

With the above information alone, a game could lookup the race & gender from some client install files, determine which skeletal mesh to use, physical attributes of the entity and begin rendering it.

A client often only needs a limited view of the entity's composition, just enough to enable rendering and whatever client functionality happens to exist.

---
Tags: entity
---


title: What is deferred lighting?

text:
# Question
Title: What is deferred lighting?
There is plenty of information on what deferred rendering is but there is a lack when it comes to deferred lighting and the information that there is there is not clear.

My question is simple, what is deferred lighting and what is its advantage and disadvantage.

# Answer
In deferred shading all the material properties are rendered into the G-buffer, e.g. albedo, normals, roughness, metalness, etc. that are needed for BRDF evaluation. After this step shading is performed for pixels within light volumes using light and material properties as input to the BRDF. The problem with deferred shading is that more complex BRDF's (e.g. subsurface scattering or anisotropic reflections) can require quite a lot of properties which inflates G-buffer space and bandwidth requirements, thus it's important to have compact representation of the material properties.

Deferred lighting tries to address this problem by decoupling constant and non-constant BRDF terms, evaluating partial BRDF, and combining these terms in the second geometry pass. The properties needed for non-constant terms are rendered to G-buffer, and then partial BRDF is evaluated for pixels within light volumes whose results are written to diffuse & specular lighting buffers. These buffers are then combined in the second geometry pass with constant terms (e.g. albedo & emissivity).

The bandwidth issues of deferred shading has been addressed with tiled approaches though, which makes deferred lighting less of an interesting option, IMHO. Multiple BRDF's can also be supported in deferred shading but memory requirements of the G-buffer is still a concern (though diminishing one as GPU's have increasing amount of memory). Deferred lighting doesn't really have big benefit in memory savings either since most terms in BRDF's are not constant and having two passes over geometry adds quite a bit of overhead in more complex environments.
> 11 votes

---
Tags: 3d, lighting, deferred-rendering, terminology
---


title: Making Player Jump

text:
# Question
Title: Making Player Jump
I have been editing a piece of code and I have already implemented gravity so I would like to know how i could make the player jump when the screen is touched. I would like the player bucket to jump. Here is my code you tell me how I add this to it.

```
public class Drop implements ApplicationListener {

Texture dropImage;
Texture bucketImage;
Sound dropSound;
Music rainMusic;

float GRAVITY  = -5f;

OrthographicCamera camera;
SpriteBatch batch;

Rectangle bucket;
Array<Rectangle> raindrops;
long lastDropTime;

@Override
public void create() {
    // load the image for the droplet and the bucket, 48X48 pixels each
    dropImage = new Texture(Gdx.files.internal("drop.png"));
    bucketImage = new Texture(Gdx.files.internal("bucket.png"));

    //load the drop sound effect and the rain background "music"
    dropSound = Gdx.audio.newSound(Gdx.files.internal("drop.wav"));
    rainMusic = Gdx.audio.newMusic(Gdx.files.internal("rain.mp3"));

    //start the playback of the background music immediately
    rainMusic.setLooping(true);
    rainMusic.play();

    camera = new OrthographicCamera();
    camera.setToOrtho(false,800,480);

    batch = new SpriteBatch();

    bucket = new Rectangle();
    bucket.x = 250;
    bucket.y= GRAVITY;
    bucket.width = 100;
    bucket.height = 100;

    raindrops = new Array<Rectangle>();
    spawnRaindrop();
}

/* (non-Javadoc)
 * @see com.badlogic.gdx.ApplicationListener#dispose()
 */
@Override
public void dispose() {
    dropImage.dispose();
    bucketImage.dispose();
    dropSound.dispose();
    rainMusic.dispose();
    batch.dispose();
}

@Override
public void render() {
    Gdx.gl.glClearColor(0x64/255.0f, 0x95/255.0f, 0xed/255.0f,
             0xff/255.0f);
    Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);

    camera.update();

    batch.setProjectionMatrix(camera.combined);
    batch.begin();
    batch.draw(bucketImage,bucket.x,bucket.y);
    for(Rectangle raindrop: raindrops){
        batch.draw(dropImage,raindrop.x,raindrop.y);
    }
    batch.end();

    if(TimeUtils.nanoTime() - lastDropTime > 900000000) spawnRaindrop();

    moveRainDrop();
}

private void moveRainDrop() {
    Iterator<Rectangle> iter = raindrops.iterator();
    while(iter.hasNext()){
        Rectangle raindrop = iter.next();
        raindrop.x -= 200 * Gdx.graphics.getDeltaTime();
        if(raindrop.x + 48 < 0) iter.remove();

        if(raindrop.overlaps(bucket)){
            dropSound.play();
            iter.remove();
        }
    }
}

private void spawnRaindrop(){
    Rectangle raindrop = new Rectangle();
    raindrop.y = MathUtils.random(0,450-48);
    raindrop.x = 800;
    raindrop.width = 110;
    raindrop.height = 100;
    raindrops.add(raindrop);
    lastDropTime = TimeUtils.nanoTime();
}

}

@Override
public void resize(int width, int height) {
}

@Override
public void pause() {
}

@Override
public void resume() {
}
 }

```

# Answer
> 0 votes
Setting `bucket.y` only sets the buckets position, so that should not be -.5, it should be the bottom of the screen (0), or at least the ground, to start. To move the bucket you should add a method called `jumpBucket()` or something similar. Then call that method whenever a touch is performed (check this within your `render()` method). This method should add some sort of y-directional speed (stored as a variable in your class) to the bucket and, if you want, set a boolean called `isBucketJumping` to true.

Then to apply gravity: you generally want similar gravity between all objects on the screen, but since you probably want the raindrops to move without acceleration, you can just leave the `moveRainDrop()` method alone (although you shouldn't use *magic numbers*, like the 48 and 200; instead use a constant for the 200 and use `raindrop.height` for the 48). Make a `moveBucket()` method and whenever `isBucketJumping == true` move the bucket upwards by it's y speed and then subtract your gravity value from it's y speed. By playing around with the value for gravity and the balloon's initial y-directional speed you should be able get the bucket to hop as you want it to.

```
// in your render method
if(Gdx.input.isTouched())
{
   bucketJump();
}
moveBucket(); // this method will be called every tick

// in your bucketJump() method
isBucketJumping = true;
bucketYSpeed = 100;

// in your moveBucket() method
if(isBucketJumping())
{
   bucket.y += bucketYSpeed;
   bucketYSpeed -= GRAVITY;

   if(bucketHitGround()) // I purposely left out the method in this if statement for you to do as practice
   {
      isBucketJumping = false;
   }
}

```

---
Tags: java, android, libgdx, box2d, eclipse
---


# Question
Title: Determining desktop bounds by D3D9 adapter
I've got a Direct3D 9 application which normally runs full-screen. The user is able to select a display adapter to determine which screen it is shown on.

I also offer a `Windowed` mode which launches on the Primary display - but the user can move it if they wish.

I want to offer a `Windowed maximised no border` (slight performance hit but it avoids alt-tab issues). The problem is, since the user can't drag the window now, I need to make sure it opens on the appropriate display.

How can I determine the desktop bounds managed by a given adapter index?

```
Device = New Direct3D9.Device(D3D9,
             Settings.Display.Adapter, //Only applies if PresentParams.Windowed = False
             Direct3D9.DeviceType.Hardware,
             Window.Handle,
             Direct3D9.CreateFlags.HardwareVertexProcessing,
             PresentParams);

```

# Answer
The desktop bounds, or 'WorkingArea' of the adapter can be found using the Screen(System.Windows.Forms.Screen) class. First you must have the handle of the device window(System.Windows.Forms.Form) displayed on the adapter. Then you can get the working area like this:

```
// get the adapter monitor
Screen adapterMonitor = Screen.FromHandle(GetForm().Handle);

// get the working area(System.Windows.Forms.Rectangle)
Rectangle workingArea = adapterMonitor.WorkingArea;

```

Screen.FromHandle(): Retrieves a Screen for the display that contains the largest portion of the object referred to by the specified handle. (From MSDN)

Also, the Direct3D9 object has a function that returns the handle(IntPtr) of the adapter monitor. I haven't worked with multiple monitors yet so I couldn't say that this method will work well but here is code for SlimDX:

```
// get the index for the desired adapter
int adapterOrdinal = ?

// you should have this function somewhere in order to retrieve your Direct3D9 object
SlimDX.Direct3D9.Direct3D d3d9 = GetDirect3D9();

// get adapter monitor handle
IntPtr ptr = d3d9.GetAdapterMonitor(adapterOrdinal);

```

You'll need to compare the monitor handle returned to the list of screens found on the system. Screen.AllScreens is a list of all screens.

As for the adapter mode comments above you should see the DirectX SDK and check out the DXUT classes, especially DXUTenum.cpp. This class is necessary for an application. It will enumerate all adapter display modes and build a collection of 'combinations' that can be used. Display Modes have specific capabilities. Certain modes cannot go fullscreen. Certain modes require a particular back buffer format for use with the adapter format. Certain depth/stencil buffer formats conflict with multisample types...and so on. Were you to try and create a device using improper settings the API will throw an exception...or return 'Invalid Call'. DXUT is very useful and is a great tool for avoiding conflicts.
> 1 votes

---
Tags: c#, directx, slimdx
---


# Question
Title: How do I switch between the game screen and score screen without redrawing everything?
I'm working on a multiplayer game in Libgdx and want to display the scores of say, the top 10 players on the map. The player should be able to checking the scores at any point during the game and return to the game screen (with themselves in the same location they were at earlier), much like pressing `Tab` during a game of *Counter Strike* displays the scores.

Changing the screen to the score screen is simple enough using `setscreen`, but how can I return to the previous view without calling a `setscreen` on the game screen and rendering everything all over again?

# Answer
Then make something like:

```
enum gameState = { PLAYING = 0, MAINMENU = 1, SCOREBOARD = 2, ... }

if(Player.action = PLAYING)
{
    ... do stuff ...
}
else if(Player.action = MAINMENU)
{
    ... do stuff ...
}
else if(Player.action = SCOREBOARD)
{
    ... do stuff ...
}

```

And about the rendering. It's hard to get around that.
> 0 votes

# Answer
you have to create some table, whatever. that will be displayed on the current screen.

the values is the question important here. You have to call from where? got it?

if you saved the values on SQLite you can make a method that load the top scores.

you can read something about multiple input processors to alternate inputs when the user

click on score button (active scoreinputprocessor) and reactive gameinputprocessor when close score.

i did it just like this. i did got nice results.

**REFERENCE:**

Ok man, the files that you have to read to learn and use your creativity:

Multiple processors: InputMultiplexer

Table: Table Layout

**EXAMPLE**
> 0 votes

---
Tags: libgdx, rendering, menu
---


title: How do I decompile Minecraft?

text:
# Question
Title: How do I decompile Minecraft?
I'm trying to get started modding Minecraft. I opened up the `minecraft.jar` file in Eclipse, but it doesn't contain what I expected.

In this tutorial the presenter decompiles `minecraft.jar` and finds things like armor and blocks packages, but when I put my `minecraft.jar` file (from `[user]\appdata\roaming\.minecraft`) into Eclipse, I only see Apache and Ydggrassil authentication and such.

What am I doing wrong?

# Answer
> 8 votes
You can't just open the jar in Eclipse. Even if you have some kind of decompiler-plugin, you will only see obfuscated code.

You will need the Minecraft Coder Pack to decompile *and deobfuscate* the jar (as well as MCP can anyway) so you can work with the code.

Additionally, if you want do develop Minecraft-Forge mods you should check out this page. Forge also requires MCP to decompile the jar, but it's automatically downloaded during installation.

---
Tags: java, minecraft-modding, modding
---


# Question
Title: Should I shade models before or after importing them into Unity?
Is it better to shade a model inside the 3D modeling software or inside Unity?

As an example, if I need to use a transparent model, should it be made transparent inside the modeling application or inside Unity?

# Answer
Shaders in 3D art applications almost never have anything to do with shaders within the game engine. The parts of the model that carry over are fundamentals like the mesh geometry.

That said, fairly standard stuff like an alpha channel in the texture (to make parts of the model transparent) usually operate the same way in both places. Alpha transparency and diffuse color are about the only two things that you can make this assumption about.

In other words, create diffuse texturing and alpha transparency in your 3D art application so that you can see what the model will look like in Unity, but realize you'll be setting it up again (this isn't hard, just telling Unity which image to use for transparency) within Unity.
> 1 votes

# Answer
> Is it better to shade a model inside the 3D modeling software or inside Unity?

Any effects brought by shaders in your modeling software have to be recreated in Unity, those won't be carried over. When you import a 3D model into Unity you import structural data (geometry, material info, texture coords and in some cases the list goes on, for example, Unity recognizes and applies modifiers from .blend files).

> As an example, if I need to use a transparent model, should it be made transparent inside the modeling application or inside Unity?

Model your art without making it transparent, then make it transparent once it gets in Unity. To make a model transparent in Unity you will have to use a shader that supports transparency. Unity comes with a few, including Transparent (Bumped) Diffuse, which you'll probably use most often.
> 0 votes

---
Tags: unity, 3d, shaders, graphics
---


# Question
Title: How do games handle rendering Asian unicode text?
I'm currently in the process of implementing text rendering in my game engine, and I decided to utilize AngelCode's BMfont to generate font textures, and then have OpenGL render textured quads for each character. This worked great, even when rendering every single glyph supported by FreeFont (FreeMono in particular), until I tried to render Japanese (My Japanese font of choice is Noto, provided by Google).

Rendering every single glyph supported by FreeMono at 16px resulted in a single 1024x1024 8bit texture, perfectly reasonable considering how many languages are covered by it. Rendering everything supported by Noto Japanese, at the same size, resulted in 13 times as many textures, and at this size most of the glyphs are too cramped to be readable (I can't read Japanese, but if I could I think I would still have a lot of trouble reading this text).

My question is twofold:

1) How do games, or mobile apps, handle small Japanese text? Do they stick to a subset of the kanji, use a special font, or is there a minimum font size?

2) How do games typically handle the absurdly massive number of glyphs required by Japanese, Chinese, Korean, and other languages? Do they use FreeType (or something similar) to render the text on-the-fly?

Note: I tried Meiryo (which I do not have the license to use in my game) and the result was *far* more readable at 16px (still cramped though), but still required 14 textures to fit everything.

# Answer
> 6 votes
I'm using the freetype library (http://www.freetype.org/) to load glyphs from freetype fonts and then use bin packing to generate a glyph texture/atlas during runtime, similar to how freetype-gl does it (https://code.google.com/p/freetype-gl/).

When the game is initialized, I generate a glyph atlas with the printable characters from the ASCII range. This atlas won't change during the game. An additional atlas is used for non-ascii characters.

Whenever a string is enqueued for drawing, I check if there is a glyph which has not been loaded yet. If such a glyph is encountered, I mark the glyph atlas as dirty and regenerate the glyph atlas before rendering. If the atlas is full, non-ascii glyphs are dropped if they have not been in use for a certain amount of time/frames.

There's a certain overhead induced by loading glyphs on the fly and rebuilding the glyph atlas, but on the other hand, any glyphs supported by the font can be used with this system.

Then again, I'm not drawing a lot of stuff besides text yet...

# Answer
> 5 votes
In the games I've worked on, we restricted the subset of characters used for Chinese, Japanese, and Korean (together referred to as CJK) to only those required to display the text in the game.

In other words, we didn't attempt to cram in every possible character; we just took the database of CJK text from our localization teams, did a pass over it to find all the Unicode code points that occurred at least once in the text, and generated a BMFont configuration file to lay out an atlas for exactly those characters. (It was all automated, so every time we got a new loc drop, we could regenerate the list of characters and the fonts as needed.)

As you can imagine, this vastly reduces the number of characters required. We also compressed the font bitmaps with DXT1, which works quite well for text (even antialiased). BMFont also has an option to use all four color channels of an image as separate pages (thus getting 4x the number of characters per page), but this doesn't play as nicely with compression, so we didn't end up using it.

I'm not sure about font sizes, though. If you haven't got any CJK-reading friends who can take a look and tell you if it's too small, you could try looking at CJK-subtitled movies to get an idea of how big the text is there.

---
Tags: opengl, text, localization
---