title: Remove gravity from single body

text:
# Question
Title: Remove gravity from single body
I have multiple bodies in my game world in andengine. All the bodies affected by gravity but in that I want my specific body does not affected by the gravity.

For that solution after research I found that I have to use `body.setGravityScale(0)` method for my problem solution.

But in my andengine extension I don't found that method so please provide guidance about how get access about that method.

Also for the above problem any other guidance will be acceptable. Thank You!

I apply following code for reverse gravity `final Vector2 vec = new Vector2(0, -SensorManager.GRAVITY_EARTH
 * bulletBody.getMass());`

`bulletBody.applyForce(vec, bulletBody.getWorldCenter());`

# Answer
> 6 votes
If you are using a version of Box2D that does not provide the `SetGravityScale` method, the best option is to disable gravity entirely and manually apply *gravity itself* to all but one object.

Applying the opposite of gravity is not significantly more expensive, but it is often unusably imprecise when multiple forces are acting on the same object.

It is also possible you may want to make bullets kinematic objects rather than dynamic ones. This will stop them from being affected by gravity, and allow you to move them by setting their velocity rather than applying forces, often a more useful approach for a bullet. If you do this, however, they will no longer interact with static objects either.

# Answer
> 2 votes
To make bodies "immune" to gravity simply apply an equal and opposite force for every step. Opposite forces will cancel each other out, leaving you with zero force (no gravity). This method means your object will still react to other forces.

Alternatively you can set the mass of the object to zero. Massless objects are not affected by gravity. However the second option may have some unintended consequences. Some physics engines make things with zero mass static. Which means they don't respond to collisions either (you'd likely not want such an interaction with a massless object anyways).

# Answer
> 1 votes
Possibly *kinematic* bodies is what you want, notice they are not affected by collision response.

---
Tags: box2d, andengine
---


# Question
Title: Pixelated and incomplete image when loading with pygame.image.load
This is the image I'm trying to load on the surface, an 40x40 Ubuntu logo:

Ans this is how it looks when trying to show the image on the surface via the `blit` method:

I'm trying to load different Linux logos, the majority have PNG extension and a couple of GIF. The Ubuntu logo is a PNG image, it's weird that the other PNG and GIF images load just fine (Ubuntu and Kubuntu logo are the exceptions, they look pixelated and incomplete).

This is how my code looks like (I'm just starting with pygame):

```
#-*- coding: utf-8 -*-
import sys
import os
import random
import pygame
from pygame.locals import *

PROJECT_DIR = os.path.abspath(os.path.dirname(__file__))
LOGOS_DIR = os.path.join(PROJECT_DIR, 'data/images/logos')
WINDOW_WIDTH = 640
WINDOW_HEIGTH = 480
FPS = 30

# Colors
WHITE = (255, 255, 255)

BACKGROUND_COLOR = WHITE

pygame.init()
MAIN_SURFACE = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGTH))
CLOCK = pygame.time.Clock()

def get_linux_logos():
    logos = []
    for img in os.listdir(LOGOS_DIR):
        try:
            logos.append(pygame.image.load(os.path.join(LOGOS_DIR, img)))
        except pygame.error, e:
            continue
    random.shuffle(logos)
    return logos

def main():
    pygame.display.set_caption('Geezle - Memory Puzzle')
    MAIN_SURFACE.fill(BACKGROUND_COLOR)
    LINUX_LOGOS_IMGS = get_linux_logos()[:12]

    while True:
        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                sys.exit()

        MAIN_SURFACE.blit(LINUX_LOGOS_IMGS[0], (300, 220))
        pygame.display.update()
        CLOCK.tick(FPS)

if __name__ == '__main__':
    main()

```

# Answer
Images with an alpha channel require an extra step of conversion when loaded. Instead of:

```
logos.append(pygame.image.load(os.path.join(LOGOS_DIR, img)))

```

Try the following:

```
logos.append(pygame.image.load(os.path.join(LOGOS_DIR, img)).convert_alpha())

```
> 3 votes

---
Tags: python, pygame, image
---


# Question
Title: How can a load and play an .x model using vertex animation in XNA?
From a game I developed years ago, I still have character models that my former 3D engine designer created and that I'd like to reuse in a Windows Phone project now.

However, the files are in DirectX format (.x) containing keyframe animation only. No bones. No skeleton.

There are a lot of animation keys defined on several frames to animate the characters.

I don't quite understand how that works, to be frankly. However, I did a lot of research regarding a possible way of getting the characters animated via XNA on Windows Phone and all I found are hints that it is generally possible but not supported. Possibly by implementing own Content Importers and Processors.

I didn't find anyone who successfully did something like that yet. How should I go about loading and displaying these models in XNA?

# Answer
This helped me alot: http://www.enchantedage.com/node/24
> 1 votes

# Answer
As far as I know .x doesn't support vertex animation. What it *does* support, and what you're probably seeing, is an old style of 3D animation sometimes called "hierarchy animation". In this animation style, a model isn't a single mesh but rather a series of meshes all linked together in a hierarchy (eg. a human character isn't a single mesh but rather separate meshes for the head, torso, upper arm, lower arm, etc.) The individual meshes don't deform, but instead by applying rotations to the separate meshes the model is animated.

Think of it like a robot arm. The pieces of the robot arm don't bend, but the overall arm bends when the pieces rotate.
> 1 votes

---
Tags: xna, 3d, animation, xna-content-pipeline
---


title: How to make a character jump?

text:
# Question
Title: How to make a character jump?
I am currently making a game in C# using Direct X 9.0. The game remake is Donkey Kong NES. I have nearly everything completed, but I am having problems with the physics of Mario's jump. I have variables declared for the Y and X co-ordinations.

I was wondering if there was a simple method of doing this. I have searched high and low for an answer but the answers I have found are either irrelevant/ or using a different programming language such as XNA.

I currently have a bool variable set to check to see if W has been pressed then that will trigger any code to make him jump. I have been messing around such as.

```
  if (jump == true)
    {

        Playerypos -=  vel;
        Playerxpos +=  vel;
    }

```

Which didn't work that well. I have searched high and low for an answer and now I am desperate, if someone could point me in the right direction to a simple solution. That would be great. Much appreciated for any responses.

# Answer
First of all, XNA also uses C# too so it's the same programming language. And although the underlying API might have some differences from DirectX, that has nothing to do with jumping, so the same tutorials or answers should apply here. Also, there are numerous ways to implement this, depending on a lot of factors. What I'll describe below is just one of the possibilities.

**Basic Physics Requirements**

First you need some basic physics variables and calculations on your update loop. In particular, you need position, velocity, and gravity defined, and your update loop should be doing something roughly similar to this (collision detection and response omitted for simplicity):

```
float positionX, positionY;     // Position of the character
float velocityX, velocityY;     // Velocity of the character
float gravity = 0.5f;           // How strong is gravity

void Update(float time)
{
    positionX += velocityX * time;      // Apply horizontal velocity to X position
    positionY += velocityY * time;      // Apply vertical velocity to X position
    velocityY += gravity * time;        // Apply gravity to vertical velocity
}

```

**Fixed Height Jump**

Now the easiest way to implement a jump that always has the same height, no matter how long you press the key, is simply to change the vertical velocity once. This will make the character start rising, while gravity will automatically take care of bringing him down:

```
void OnJumpKeyPressed()
{
    velocityY = -12.0f;   // Give a vertical boost to the players velocity to start jump
}

```

*Important* You don't want to be able to start a jump if your character is not on the ground, so you'll need to add a check for that.

**Variable Height Jump**

But games like Mario and Sonic have a variable jump where the height of the jump depends on how long you press the button down. In this case you'll need to handle both pressing *and* releasing the jump key. You could add something like:

```
void OnJumpKeyReleased()
{
    if(velocityY < -6.0f)       // If character is still ascending in the jump
        velocityY = -6.0f;      // Limit the speed of ascent
}

```

Tweaking all of these values (i.e. the numbers like `0.5`, `-12.0f` or `-6.0f`) in the code above you can change the feel of your jump, how high he jumps, how much momentum does he keep even after releasing the jump button, how fast he falls, etc.

*Important* Don't call these functions every frame. Call them only once when the key is pressed or released. Otherwise your character will fly instead of jump.

**Working Example**

I have just created a quick example of the techniques described above, which you can try on your browser here (press mouse button to jump, release it midway to control the height of the jump). It's in JS but like I mentioned earlier, the language is irrelevant in this case.

http://jsfiddle.net/LyM87/
> 88 votes

# Answer
Like in physics. Only at the moment You press `jump key` and character is on the ground add upwards velocity (it is called impulse), but make character fall by gravity all the time.

If You do not want character to be jumping every time it hits the ground - because You are holding `jump key` \- add `jump key is being pressed` variable which You clear after `jump key` is released and set after. Pseudocode:

```
if jump being key pressed == false && jump key just pressed
   add y velocity
   jump being key pressed = true

if jump key released
   jump being key pressed = false

decrease velocity by gravity
check for collisions // to not penetrate ground ...

```

If I used Your way:

```
if jump key not pressed
     jump height = 0            // imaginary height donkey would travel without gravity

if jump key pressed
     // going up
     if jump height < maximal height donkey might jump
         jump height += 5
         donkey.y    += 5        //
     // going down
     else if jump height < 2 * maximal height donkey might jump
         jump height += 5
         donkey.y    -= 5

```

How `donkey.y` will change is up to Your imagination. Velocity should get smaller heigher donkey is in the air to make it look good.
> 1 votes

---
Tags: physics, input, jumping
---


# Question
Title: Puzzle game: clipping of non-convex polygons on the figures
I have an original figure in the SVG file. I need to break it randomly on parts, an example of which is specified below:
I have an idea, to use for partitioning Voronoi diagram (Fortune's algorithm). Can I then change the line of intersection of figures to give them a curvature? Can be obtained to identify each shape as a path? To create a game I'll be using cocos2d-x.

# Answer
I think you've got the right idea, but the execution is going to be immensely challenging. I'm presuming when you say 'in an SVG file' you mean that the shape is defined by one (or more — your sample figure has an internal hole!) stroke paths. Unfortunately, SVG paths can be remarkably complicated, with both quadratic and cubic Bezier curves and elliptical arc segments. The intersection of a line with any of these is a solved problem, but a highly non-trivial one, and even the matter of re-parametrizing Bezier curves to split them in two at the point of intersection is a little tricky — basically, what you're looking for is complex enough to take a small book to answer, not a forum post! That said, there are several excellent references out there; the short *short* version of the answer is that you want to use recursive subdivision along with the so-called 'variation diminishing' property of the Bezier curve (essentially, the property that a Bezier curve is contained within the convex hull of its control points) to narrow down the possible locations of an intersection (and note that a line can have multiple intersection points, and that's another special-case that you may have to take into account). And once you solve the intersection problem, you've still got a long road ahead — you're going to have a ton of bookkeeping to do to keep track of curve and line segments and partition them correctly into pieces. This isn't to discourage you at all; just be aware of the magnitude of what you're trying to do!

Fortunately, your other question — 'can I change the line of intersection of figures to give them curvature?' — has an easier answer: absolutely. Since you're already in SVG-land, I'd use Bezier curves here too: first, choose five points p1..p5 along the line segment you want to 'curve out', probably somewhat at random in roughly equally-spaced intervals; then displace them a small random distance off the line, and use them as the control points of two separate Bezier curves, one using points p0, p1, p2, p3 and the other using points p3, p4, p5, and p6 (where p0 and p6 here are the two endpoints of the original line segment). You can take advantage of the convex-hull property of the Bezier curve here too, making sure that your displaced points don't displace too far so that the two regions to either side of the curve(s) are still simple regions. This should give you the sort of curved boundary that you're after.
> 2 votes

---
Tags: geometry, cocos2d, cocos2d-x, puzzle, clipping
---


# Question
Title: Detecting collision on a grid with a fast-moving object
I am working in a 2D collision system where I need to detect a collision of a rectangle on a grid, but since the rectangle may be fast enough to jump more than one of the grid squares (sometimes several) I need to check collision of everything in the middle of point A to B.

Does anyone know a way to achieve that?

In the image below, I am starting at point A and in one update it's at point B. I would need to check collision on the whole gray area. As you can see in the image, the rectangle don't need to be on a fixed position on the grid.

The grid squares in my case have 30x30 pixels and the rectangle has 35x65. My grid is also on a list, but this can change if needed.

Thank you in advance for any help.

# Answer
After some more research I decided against box2dxna or Farseer.

What I am (still) building is a solution using Bresenham's line algorithm and ray casting.

I will consider each square on the grid as a pixel, and this should be pretty fast.

So I will actually do more than one ray cast. One for each of the squares on position A facing position B.

So in the image above I will do 4 calls to ray cast. Each ray will hit something like 10 squares, giving me 40 to 50 checks in total.

I hope this help someone else in the future.

Ray casting

Bresenham's line algorithm
> 3 votes

# Answer
You could move the rectangle in discrete steps and check collision for every step. For example, instead of moving 10 units, move it 5 times 2 units and check every time. More steps you have, more demanding the processing is but is more precise. In order to reduce processing you could do this only for fast moving objects because slower ones won't produce tunneling (one object passing through other).

Another approach would be to construct a rectangle that would be around the entire movement. In your example, construct the rectangle around the gray area and check collision against it.
> 1 votes

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


# Question
Title: AS3 Symbol not showing returns no errors?
I haven't touched Flash in a while and I've forgotten a lot.

I'm trying to get a space-ship symbol to show in the middle of the screen. For some odd reason it isn't showing in the middle of the screen or even appearing. There's no error in the output or an error in the debug.

Here's some code below.

I'm coding in Coda 2 and using Flash to manage the library. I currently only have one class called Game.As and the ship symbol is a MovieClip with the name shipSymbol and the class is defined as shipBase with the base class being flash.display.MovieClip;

package {

```
import flash.display.MovieClip;
import flash.display.DisplayObject;
import flash.display.Stage;
import flash.events.Event;

public class Game extends MovieClip {

    //Spaceship Symbol
    private static var ship = spaceShip;

    private function initShip(startX = number , startY = number):void {
        ship = new spaceShip();
        this.x = startX;
        this.y = startY;
        startX = stage.stageWidth /2;
        startY = stage.stageHeight /2;
        stage.addChild(spaceShip);
        trace("Space-Ship Spawned");
    }
    public function runGame():void {
        stage.addEventListener(Event.ENTER_FRAME , update);
    }
    override public function update(e:Event):void {
        initShip();
    }
}

```

}

Thanks, for the help :P

# Answer
> 2 votes
Few things wrong...

parameters should be...

```
initShip(startX : Number , startY : Number)

```

and not

```
initShip(startX = number , startY = number)

```

This seems misplace:

```
startX = stage.stageWidth /2;
startY = stage.stageHeight /2;

```

This should change from:

```
stage.addChild(spaceShip);

```

to

```
stage.addChild(ship);

```

Change this

```
this.x = startX;
this.y = startY;

```

to

```
ship.x = startX;
ship.y = startY;

```

probably not legal:

```
private static var ship = spaceShip;

```

set it to null.

If ship still does not appear, then make sure you check the "export symbol" via the library where you typed in "spaceShip" for this symbol (I don't have flash to tell you correct/specific name).

You should have got errors anyway and since you didn't you probably not got the class name field setup in the project dialogue. I can't be more specific on this, someone who has flash on their machine will probably give you a better answer on this.

---
Tags: actionscript-3
---


# Question
Title: How can I more efficiently write my Math-Code in AS3
So this might be an odd question to ask. But I'm not really the biggest mathematician out there, and I have a weird habit of writing code. So I'm going to post what I'm working on. I'm doing a self-game jam this weekend which will be 48 hours long, and I've kind of cheated by already starting. The question is -- well what I'm trying to do is create a ease-in / bouncing effect without using a Tween library.

I feel that what I have is suffice, but I don't think it is very efficient and that I'm overcomplicating my code with clutter.

Below is code from my Engine class with comments that should help decipher what I am doing.

```
package {
    import flash.display.MovieClip;
    import flash.ui.Mouse;
    import flash.display.Stage;
    import flash.events.Event;

    public class Engine extends MovieClip {

        public var spaceShip:Ship = new Ship(stage);
        private var logo:IcarusLogo = new IcarusLogo();

        //Math, Velocities , Numbers
        private var vF : Number = 0.5; // Velocity Forward
        private var vX : Number = 0; // Velocity X
        private var vY : Number = 0; // Velocity Y
        private var iV : Number = 0.2; // Initial Velocity
        private var fV : Number = .90; //Friction
        private static var pI:Number = 3.14; // pI

        public function Engine() {
            initGraphics();
            runGame();
            Mouse.hide();
        }
        //INIT EVERYTHING
        private function initGraphics():void {
            initShip();
            initLogo();
        }
        private function initShip():void {
            spaceShip.x = stage.stageWidth/2;
            spaceShip.y = stage.stageHeight/2;
            stage.addChild(spaceShip);
        }
        private function initLogo():void {
            stage.addChild(logo);
            logo.x = stage.stageWidth - 1200;
            logo.y = 200;
        }
        //RUN THE GAME
        private function runLogoStyles():void {
            logo.x += vX;
            iV = .025;
            vX *= fV + iV;
            if (logo.x <= 450) {
                logo.x += vX;
                vX += fV + iV;
                iV = -.2;
            }
        }
        public function runGame():void {
            stage.addEventListener(Event.ENTER_FRAME, update);
        }
        public function update(e:Event):void {
            runGame();
            runLogoStyles();
        }
        //TRASH EVERYTHING THATS NOT NEEDED.
        //AS3 HAS NO NARC RULE SO JUST REMOVE.CHILD
        public function trashCan():void {
            //TrashCan is similar to init. Create Sub-Functions // and init everything in here.
        }
    }
}

```

Here's a screenshot to give a better understanding : http://f.cl.ly/items/3X3j0L052v0M2b0v2p1b/screen.png

# Answer
> 2 votes
One way quick and easy way of doing this which I've used many times

ease in:

```
private function runLogoStyles():void {
    var speed = 5;
    var maxSpeed = 50;
    logo.x += Math.min((450 - logo.x) / speed, maxSpeed);
}

```

wobble:

```
private function runLogoStyles():void {
    var wobbleSpeed = 1.4;
    logo.x = 450 - ((450 - logo.x) / wobbleSpeed);
}

```
1. Try the ease in forumla and see the effect working.
2. Try the wobble forumla to see the effect.

Once you are happy that these forumla works. Play ease in until it like 10 pixels or so away from the target then kick in the wobble forumla.

Some tweaking with with speed, wobbleSpeed and maxSpeed values and when to kick in the wobble is needed.

Added: The wobble could well be too violent for your liking so I've combined both forumla to form this:

Tip: Experiment with all the numbers shown in red

```
private function runLogoStyles():void {
    logo.x += Math.min(50,(currentTarget - logo.x) / 3);

    if (Math.abs(logo.x-currentTarget) < Math.abs(target-currentTarget) / 1.9) {
         currentTarget= target + ((target - logo.x) / 1.2);
    }
}

```

Before calling this function add and initialise the following class member variables:

```
private var target:Number = 450;
private var currentTarget:Number = 450 + 20;

```

---
Tags: mathematics, actionscript-3
---


title: Framerate control and physics engines?

text:
# Question
Title: Framerate control and physics engines?
I am reading this article on how to control the framerate and physics calculations.

But in the game I am writing, I use a third party physics library and the only thing I do to update my physics is call a single function (`runSimulation()`).

Since I cannot do things like "interpolation" in the above tutorial, how can I make my game runnable in different hardware/at different framerates?

# Answer
Looks like the SteeringBehaviors library is determining the simulation time by calling `System.currentTimeMillis()`, so (unless you modify the library) your only option is to call `runSimulation()` at exactly the right time.

**Consider spawning 2 threads:**

1. Execute Thread 1 every time the display needs to be updated (e.g., by syncing to the display's refresh interval)
2. Execute Thread 2 every time you want to update the simulation. Make sure this thread executes at the same rate on different platforms (e.g., by setting it up to fire using a fixed-rate timer).

(And, of course, be sure that any data structures shared between those two threads (the locations of the particles, for example) are protected from thread collisions (e.g., using locks).)

That way, if the rendering thread stalls, or if the rendering speed differs between hardware devices, your simulation thread will continue to update the simulation at a constant rate.
> 2 votes

---
Tags: physics, rendering, game-loop, frame-rate
---


title: Distance to a sphere, in Screen Space

text:
# Question
Title: Distance to a sphere, in Screen Space
Is it possible to find the distance of a pixel to a rendered sphere, in screen space? All my naive solutions for just using the 2D screen distances are failing because of the warping that occurs during projection.

# Answer
> 2 votes
It's definitely possible, though it doesn't have a clean explicit formula. The projection of a sphere is an ellipse, and given the projection matrix you should be able to find an explicit formula for the ellipse, something of the form ax^2+bxy+cy^2+dx+ey+f=0 (the canonical formula for a conic section); from this you can find a rational parametrization of the ellipse (of the form x=f(t), y=g(t) with f and g rational functions). The problem then comes down to minimizing (f(t)-x\_0)^2+(g(t)-y\_0)^2 as a function of t, and it turns out that rootfinding methods work pretty well for this - there are exact solutions but they require solving a degree-4 equation, which can involve hairy complex arithmetic and tends to be less numerically stable (and thus less accurate) than the approximate methods anyway.

# Answer
> 0 votes
Your screen is a plan. Your sphere is an elipse. When the user clicks somewhere on the screen it's easy to find the coordinates on the screen plan. Then you just have to apply basic elipsis equation in order to know if the selected point is inside or outside the elipsis and how far it is.

---
Tags: directx, hlsl
---


# Question
Title: Validating multiplayer actions when using Javascript Game Engines client-side
I am using one of the many javascript game engine (impactjs, craftyjs, melonjs, easeljs etc) out there to handle the animation client-side. And I have a way of calling server-side functions and syncing variables between client-server (can be done using node.js/socket.io or libraries like nowjs). Everything is written in javascript.

I was wondering if I am doing the multiplayer right?

```
playerPosition = { x : 0; y : 0 }

updatePosition = function (a,b)
{
  playerPosition.x = a;
  playerPosition.y = b;
}

```

"playerPosition" is a server-side array containing the x and y position of the player. "updatePosition" is a server-side function that updates the position.

What I am doing now is when the player presses a movement key, I let the client-side Javascript engine handle all the movement and collision. Then call "updatePosition" to update his position on the server. The relevant values in the "playerPosition" array is passed to the client to sync.

Obviously, players can cheat by hacking the client and feeding whatever value they like for inputs "a,b". (updatePosition is server-side but it is called from client-side) To stop that, I added a check to see if the next position values "a,b" is too far off. E.g. I call updatePosition every frame, and I know players move only 5 pixels per frame, so I ignore "a,b" inputs that differs from the old position by more than 5. (essentially, the client processes keypresses and moves the sprite but this movement is only updated on the server if the server thinks its valid)

Collision is entirely handled by the client-side Javascript game-engine so I am not sure how to check it server-side. Perhaps I will have an array server-side holding all the coordinates that the player is not allowed to move to (solid, colliable objects etc) and use the check as before.

Question: Am I doing it "right"? Or is this totally naive and prone to catastrophic failure? :D

If I am not wrong, I should be doing movement and collision server side? Javascript game engines are written to draw stuff on the HTML5 canvas client-side. I am not sure how to run those engines server side. Or is it enough to be validating moves and what I am doing above, and let the client handles all the movement and collision?

# Answer
After some more reading, asking on other forums and comments from Patrick Hughes, this question is pretty much resolved.

Based on what I gathered, this should be a viable approach: when the player press a movement key, the input is sent to the server and his position is updated server side. The Javascript engine remains client-side and is used to draw the animation of this movement.

I would validate the movement server-side. E.g. check if each move does not exceed certain bounds. Also, collision has to be validated server-side. E.g. keep an array of coordinates that would result in collision and make sure moves does not cause player coordinates to take values in this array.
> 1 votes

---
Tags: javascript, networking, multiplayer
---


title: Synchronizing Movement in an MMO

text:
# Question
Title: Synchronizing Movement in an MMO
I'm trying to decide how to implement player movement in an MMORPG. Player positions must be synchronized in a way that meets the following requirements:

* Low lag
* Difficult to hack or cheat
* Authoritative server with constant accurate knowledge of player positions
* Fairly simple to implement

I already know of two approaches:

1. The client sends position: Every so often, the client sends the player's current position to the server. This is simplest.
2. The client sends input: Basically the player's machine sends keypresses to the server, and the server handles all simulation and state, sending back the player's position every so often.

Both systems have their advantages and disadvantages. Is either one superior to the other, or is there a better alternative?

# Answer
Neither is better than the other.

You can send cheat positions with the first method but it is easy for the server to check them so it is rare to gain an advantage this way - just compare the current position with a past position and see if the distance travelled is further than the character's speed would allow. This method may require a bit more data being sent but it is easy to form and to process.

The second method cuts down on bandwidth but usually you have to send positions one way or the other anyway to keep the two sides synchronised, as jitter (change in latency) will mean that the client and the server will end up with different ideas of how long a character spends travelling, which adds up to a large error if not corrected. It can also get complex if there are different types of movement

Neither approach has significantly worse latency than the other - one or both sides will predict future positions anyway, where necessary, but that is always a tradeoff with accuracy, because any change in velocity takes time to reach the server from the client, during which the prediction is incorrect.
> 1 votes

---
Tags: networking, mmo, movement
---


# Question
Title: Are bounding volumes created by artists?
I'm interested in where in the tool chain bounding boxes are created. Are they made by the artists? In the modeling tool? How are they exported? Can Maya/3DS Max/Blender/... mark geometry as bounding box? How does that work in Collada/FBX?)

Or is there a tool which calculates them? Are they calculated at run time?

I basically know how bounding volumes work, but I'm a little bit confused on where to get them from.

# Answer
> 4 votes
Bounding volumes are usually computed procedurally. For example, an axis-aligned bounding box can be computed by iterating the vertex set of a mesh and saving the minimum and maximum X, Y and Z coordinates, although there are other volumes such as spheres, oriented boxes, and capsules which can involve more complex algorithms. Because such computations are typically expensive they tend to be done offline, either as part of an export step from the modeling package or as part of a data packing or compilation step during the build of a game.

In some cases, loose bounding volumes (those that do not conform as tightly as possible to the object) are desirable. Typically this is when the volume will not be used for rendering/optimization purposes but instead for design or gameplay mechanics purposes. In such cases the volumes could be created by hand. This would probably be done in a content creation tool, or by marking a phantom primitive in the modeling tool as a bounding volume (note that modeling tools need not have a built-in "mark as bounding volume" operation, as most can tag objects with user-defined values that custom exporter pipelines can process).

There are no industry standards for how and when bounding volumes are computed (or authored, if applicable). Most asset pipelines are proprietary, designed to serve the specific needs of a studio and/or project, and this operation falls under the realm of an asset pipeline task.

# Answer
> -2 votes
BBoxes are generated in runtime, engine process geometry to get min,max in x/y/z axes.

---
Tags: tools, bounding-boxes
---


title: in/out keywords in GLSL

text:
# Question
Title: in/out keywords in GLSL
I don't really understand how to use the **`in`** / **`out`** keywords in GLSL, and google is being uncharacteristically unhelpful.

What exactly do they do? How would I use them if, for example, I want to pass a varying variable set per vertex to the fragment shader?

Literally every tutorial I find uses the **`varying`** / **`attribute`** keywords and that's not helpful.

# Answer
> 77 votes
The storage qualifiers `in` and `out` actually have a purpose that contains and supersedes that of `varying` and `attribute`. They define what variables are respectively **in**puts and **out**puts for the shader. See the GLSL 4.2 reference card page 7:

* **`in`**: linkage into shader from previous stage
* **`out`**: linkage out of a shader to next stage
* **`attribute`**: same as `in` for vertex shader
* **`varying`**: same as `out` for vertex shader, same as `in` for fragment shader *(Note: these are erroneously flipped around in the above-mentioned reference card.)*

With the side note that the latter two are sort of deprecated: they are not present in the 4.2 core profile, only in the compatibility profile.

---

## What exactly do they do?

As for usage, take the vertex shader from An intro to modern OpenGL. Chapter 2.2: Shaders:

```
#version 110

attribute vec2 position;
varying vec2 texcoord;

void main()
{
    gl_Position = vec4(position, 0.0, 1.0);
    texcoord = position * vec2(0.5) + vec2(0.5);
}

```

It should be rewritten in 4.2 core as:

```
#version 420

in vec2 position;
out vec2 texcoord;

void main()
{
    gl_Position = vec4(position, 0.0, 1.0);
    texcoord = position * vec2(0.5) + vec2(0.5);
}

```

---

## `in`/`out` for function parameters

From the `Parameters` section in the Khronos wiki:

> ```
> void MyFunction(in float inputValue, out int outputValue, inout float
> inAndOutValue);
>
> ```
>
> Functions in GLSL use a calling convention called "value-return." This means that values passed to functions are copied into parameters when the function is called, and outputs are copied out when the function returns.
>
> The `in`, `out`, and `inout` qualifiers are not the same as type qualifiers, even though some of them are named the same. These are parameter qualifiers, and they have a different meaning here.
>
> A parameter declared as `in` means that the value given to that parameter will be copied into the parameter when the function is called. The function may then modify that parameter as they see fit, but those changes will not affect the calling code.
>
> A parameter declared as `out` will not have its value initialized by the caller. The function will modify the parameter, and after the function's execution is complete, the value of the parameter will be copied out into the variable that the user specified when calling the function. Note that the initial value of the parameter at the start of the function being called is undefined, just as if one had simply created a local variable.
>
> The `inout` declaration combines both. The parameter's value will be initialized by the value supplied by the user, and its final value will be output
>
> The default if no qualifier is specific is `in`.

---

## Unhelpful Tutorials

I'm guessing the main reason you find "outdated" tutorial code is that not everyone has access to GLSL 3.3+ compatible hardware. Regardless, for a good and more up to date tutorial I'll gladly point you in the direction of Nicol Bolas' Learning Modern 3D Graphics Programming.

---
Tags: opengl, glsl
---


title: glScalef - game math issue

text:
# Question
Title: glScalef - game math issue
I can't get my head wrapped around this issue. The issue is my latest code is making the camera zoom in and out really quickly.

My approach is built on -

http://www.zdnet.com/blog/burnette/how-to-use-multi-touch-in-android-2-part-6-implementing-the-pinch-zoom-gesture/1847?tag=content;siu-container

The opengl scale will be getting the variable - scale.

```
gl.glScalef(scale, scale, 1);

```

the distance is obtained by between two fingers, old distance (initial touch points), and new distance (dragging touch points). The zooming in and out works well. However, it would reset glScalef each time the user start using pinch zoom.

```
scale = newDistance / oldDistance;

```

I tried calculating by additive ratio. The oldtscale handles the previous distance, if it is same, then it doesn't need to add up anything to scale. The zooming is really quick, I moved the fingers closer by mere 1 cm to 5 cm, zoom goes down or up fast. I think additive ratio is a bad solution. I think it might be incomplete solution. I'm trying to figure out what's wrong with it.

```
//additive ratio
tscale = (newDistance / oldDistance) - 1;
                    if(oldtscale == tscale) {
                        oldtscale = tscale;
                        tscale = 0;
                    }
                    else {
                        oldtscale = tscale;
                    }
                            //adding up the additive ratio and scale
                    tscale = scale + tscale;
//checking tscale for limiting the maximum/minimum scale
if(tscale >= 2) {
                        tscale = 2;
                    }
                    else if(tscale <= 1) {
                        tscale = 1;
                    }
                    //supply scale
                    scale = tscale;

```

# Answer
> 0 votes
It's not clear if your problem is the lacking of smoothness or something else. Does the code work as it is? Also, you're saying that additive ratio is a bad solution, why?

You are doing an inner ratio to get a scale, with the possibility of getting either: 0/oldScale or newScale/0

The div by zero is an obvious error, but the scaling by zero is wrong too. In your case, the zoom won't be smooth since you are applying a div result, that could be a sudden *huge* zoom if newScale \>\> oldScale.

If the initial values are something like 15/10 (1.5x scale), later it could get 20/15 (now it's ~1.3x) with the same amount of movement. Unless you want to confuse the users, an additive zoom level using (newDistance-oldDistance)\*constMultiplier with a fixed min and max scale will result in a better feeling.

# Answer
> 0 votes
Not very clear what your problem is, but you almost definitely don't want to scale the Z by zero. Anything multiplied by 0 is 0, so you're effectively making the depth of any object 0 . You probably want to scale Z by 1.0 instead, which would leave its depth unchanged.

---
Tags: opengl
---


# Question
Title: How to rotate an object so it stands correctly (back always facing the camera)
I have the following scene:

And I have two 3D vectors, the camera position, and the focus position. The focus vector is always behind the monster. I know how to rotate the camera around the focus with the help of my mouse, but the monster is always facing the same direction, and I'd like to change that!

I'd like it to work almost as in World of Warcraft; while I'm standing still I can move the camera around freely, but as soon as I move, the monster should change the direction according to the `camera.position >>> focus` vector. Also, I need to make it move in that direction, I guess I could have a 2D vector called `speed`, which I should change accordingly (it would look like a rotating radius of a circle I guess).

How do I do this?

For reference, I'm working in Three.js, and this is the code with which I rotate the camera:

```
onDocumentMouseDown = function(event)
{
    event.preventDefault();

    game.isMouseDown = true;

    game.onMouseDownTheta = game.theta;
    game.onMouseDownPhi = game.phi;
    game.onMouseDownPosition.x = event.clientX;
    game.onMouseDownPosition.y = event.clientY;
}

onDocumentMouseMove = function(event)
{
    event.preventDefault();

    if (game.isMouseDown)
    {
        game.theta = -((event.clientX - game.onMouseDownPosition.x) * 0.5) + game.onMouseDownTheta;
        game.phi = ((event.clientY - game.onMouseDownPosition.y) * 0.5) + game.onMouseDownPhi;
        game.phi = Math.min(160, Math.max(20, game.phi));

        game.cameraBuff.x = game.radious * Math.sin(game.theta * Math.PI / 360 ) * Math.cos( game.phi * Math.PI / 360 );
        game.cameraBuff.y = game.radious * Math.sin(game.phi * Math.PI / 360 );
        game.cameraBuff.z = game.radious * Math.cos(game.theta * Math.PI / 360 ) * Math.cos( game.phi * Math.PI / 360 );
    }
}

```

And at render time I do this:

```
self.camera.position.x += self.cameraBuff.x;
self.camera.position.y += self.cameraBuff.y;
self.camera.position.z += self.cameraBuff.z;

self.camera.lookAt(self.focus);
self.renderer.render(self.scene, self.camera);

self.camera.position.x -= self.cameraBuff.x;
self.camera.position.y -= self.cameraBuff.y;
self.camera.position.z -= self.cameraBuff.z;

```

# Answer
> 2 votes
If you know how to turn the mesh to a desired rotation vector, you can just get the direction the object should walk with the following formula `direction = normalize(position - focus)` Where position is the mesh position and focus is your focus position. If the focus is really behind the mesh as you said, just multiply it by -1.

If as you said, you can't use the focus here, you can do the same with the camera position `direction = normalize(position - camera)` Multiply by -1, and as you want to move just on the XZ plane, set Y to 0. Should look like this:

```
direction = position - camera;
direction.Y = 0;
direction = normalize(direction);
direction *= -1;

```

# Answer
> 0 votes
I assume you still want the monster to stand upright, so if you want it to face away from the camera while aligned to the ground, simply create a LookAt rotation matrix like so: `LookAt(eyePos, targetPos, up)` where eyePos would be monster.pos, targetPos would be \[monster.pos.x - camera.pos.x, monster.pos.y - camera.pos.y, monster.pos.z\] (ignoring the camera's height), and up would be \[0,0,1\] , assuming z is the "up" axis. If there is no LookAt matrix function provided, you find find an implementation here

---
Tags: 3d, mathematics, camera, webgl, three.js
---


# Question
Title: where can I get people to create project with me?
I've almost finished my studies. Actually I am looking for job to get experience but besides this I have a lot of free time. Could you tell me where can I (make relationship with ) find new people who also likes create new games or apps in java/c# and work together?

# Answer
> 0 votes
You can have a look at specialized indie game dev forums like tigsource. This forum is perfect to meet other game dev and to share some points of view about game dev.

# Answer
> 0 votes
depending on your target (platform/engine/framework) there are full communities of people, and many times there will be a section in these community forums whose sole purpose is "help wanted" (where people either post their skill set requesting a job, or post a job requesting applicants)

for Example

there are also general forums that are not specific to platform/engine/framework, but at some point that question may come up especially if your posting a job opening.

---
Tags: human-resources
---


# Question
Title: Map a fbx model between 2 VertexPositionColor Positions
I have created a VertexPositionColor position and drew it in the XNA like this

```
VertexPositionColor[] backbone;
backbone = new VertexPositionColor[2];

backbone[0].Position = new Vector3(0, 22, 0);
backbone[0].Color = Color.Black;
backbone[1].Position = new Vector3(0, 10, 0);
backbone[1].Color = Color.Black;

```

In the draw method

```
graphics.GraphicsDevice.DrawUserPrimitives<VertexPositionColor>(PrimitiveType.LineList, backbone, 0, 1);

```

My question is, is it possible to map a 3d bone (Model exported as fbx) to these coordinates. or is there a much easier way to achieve this.

# Answer
Yes, is possible to visualize model bones. This article http://www.digitalrune.com/Support/Blog/tabid/719/EntryId/129/Visualization-of-a-Model-Skeleton.aspx help you with it. Result can be seen for example on this my video http://www.youtube.com/watch?v=H8SRPFsB6lc
> 1 votes

---
Tags: xna, 3d, xna-4.0
---


# Question
Title: How does having the Debugger change the game execution on an XBOX 360?
So I thought my issue was relating to the difference between a Debug and a Release build as per this question: What's the difference between a "Release" Xbox 360 build and a "Debug" one? but I've since found that if I go ahead and build a Creators Club version of the game using a Debug build and deploy to the XBOX, I get the same experience I had with the Release version of my game.

However if I run the game from Visual Studio using F5 and having set the XBOX as the default platform, then the game runs as expected. If I change from Debug to Release and run with CTRL+F5 then the game also works as expected.

How would running the game with the debugger attached change the results I am getting in game? Is there any way that I can use the same approach or change the default compilation of the game so that I can use this approach to release my game?

# Answer
> 1 votes
On Windows there is actually a way to change the behaviour of the JIT \- it's clear that you can't create such an INI on the XBOX: so this is unavailable.

Remember that a compiler is *not allowed to change the behaviour of a piece of code.* You have either found an XBOX runtime bug, or the library you are using is sensitive to delays introduced by debugging (somehow, the antithesis of a heisenbug): and it's very likely the latter.

Remember, it's Microsoft's job to ensure that the JITter does not change the behaviour of a piece of code: and they do a very good job at it (if I remember correctly the XBOX interprets MSIL - so the chances of it doing it incorrectly are next-to-none). Expecting DEBUG/RELEASE to change the behaviour of your application is the wrong mindset to begin with: debug your DEBUG build, and test your RELEASE build without the debugger attached.

From your comments it sounds like they have heisenbug in BEPU: made apparent by the fact that they are using multi-threading. I would recommend attempting to disable the multi-threading (not sure how, but it's clear that you can) and seeing if the behaviour persists: if it doesn't there is a problem with the threading in BEPU and you should report it to them.

---
Tags: xna
---


# Question
Title: How to iterate through a list of enemies and display results?
I'm making an turnbased RPG and I wanted to add a traditional multiple enemy system where a user could attack different enemies when it's there turn. I started by making a list of everybody who is going to attack and having that as the turn order. My question is how do I go through that list, and for every enemy that attacks display the damage they did and wait for the user input to continue to the next enemy.

Getting it to process all the attacks is easy, but a computer will do it in milliseconds and I need it to wait for the user input to continue.

I have started the following code:

```
for (int i = 0; i < turnOrder.Count; i++)
{
     if (turnOrder[i].isMonster)
     {
          ProcessEnemyChoice(enemyToAttack);
     }
     else if (turnOrder[i].isMonster == false)
     {
          ProcessUserChoice(enemyToAttack);
     }
     //enemyToAttack is assigned as a the enemy the user selected
}

```

I tried a do-while loop but that stopped my program from doing any updating, which makes sense. I'm at a loss here and any input from the geniuses here would be much appreciated.

# Answer
> 2 votes
> I tried a do-while loop but that stopped my program from doing any updating

You don't need to do a while loop to wait for the input. You just maintain a global gamestate and whos\_turn\_is\_it so that you know what to do on each update *loop*:

```
public override void Update(GameTime gameTime)
{
    if(gamestate == WAIT_FOR_INPUT)
    {
        if(turnOrder[whos_turn_is_it].IsMonster == false)
        {
            if(UserInput != null)
            {
                ProcessUserChoice(UserInput);
                gamestate = WAIT_FOR_ANIMATION;
            }
        }
        else if(turnOrder[whos_turn_is_it].IsMonster)
        {
            ProcessEnemyChoice();
            gamestate = WAIT_FOR_ANIMATION;
        }
    }

    // Do the animations
    // idle animation, NPC movement, fight/heatlh bar animation
    ProcessAnimations(gameTime);
}

public void ProcessAnimations(GameTime gameTime)
{
    // an example of health animation (as a form of input feedback)
    player.current_health += (player.current_health - player.health_after_fight) / 20.0f

    // an example of 2D graphic animation
    player.current_sprite_index = (int)(gameTime.ElapsedTime * player.animation.fps);

    // we need to stop the animation and current state after sometime when input feedback complete
    if(player.current_health - player.health_after_fight < 0.001f && player.current_sprite_index == player.sprite_frame_count_max)
    {
        whos_turn_is_it++; // next person's turn since our animation is now done.
        gamestate = WAIT_FOR_INPUT;
    }

    // do animations for other stuff
    DoOtherAnimationUpdate();
}

```

# Answer
> 0 votes
Since it's turn based, of course a single turn will take as much time as the slowest player spends to send input. You don't need to wait for *everything else* just for turn-related stuff.

If you want to make it independent form user input, then you have basically two options: 1- assign a max amount of time to act (the same situation as a real life chess game)

2- use some sort of real time system with filling action bars (like many RPGs do).

Using an action bar (the fill rate will depend on the unit's initiative) you'll get you a dynamic stack of actions and the game will solve the top action for each time step.

The game won't ever have to wait (beyond a defined amount), but a player that takes ages to decide his/her move could lose server actions.

Edit: Since there 1 human player, the enemies are considered AI players. The above still applies.

What should the human player be able to do while the cpu is computing? If you let the user send the next input while the cpu decides, the user won't be able to see the current turn result so it could be risky or simply wrong.

Or if your problem is just that the game hangs up completely, you just need to avoid having the AI loop inside the main game loop. That's just a common multi-threading problem. Look at this to get some more details (answers cover AI updates) :

https://stackoverflow.com/questions/1941573/multithreading-in-xna-game

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


# Question
Title: as3 flash game: How to stop gotoAndPlay('label') from looping?
I'm working on a flash game with a main character who helps people around town. It's moveable with the arrow keys because of a function called keyPressed();

When the main character hitTests with a person and you press spacebar the person should gotoAndPlay a label within itself. This works great, but because I've put these if statements in the keyPressed function, everytime the main character moves (keyPressed) the label plays from the beginning. I understand why this is happening but my question to you is:

It went great so far but now I realize I have a lot of if statements and they all are in the keyPressed function. This causes my problem (the looping of the gotoAndPlay) and I'm pretty sure this will cause more trouble in the future. I should use more functions, but where and when do I use these to accomplish my goal?

More info: I'm coding on the timeline (F9), maincharacter = char, client = the person wich label should go to 'leaving'

```
var clients:int = 0;
var orders:int = 0;
var delivery:int = 0;
var hodling:int = 0;

var isRight:Boolean=false;
var isLeft:Boolean=false;
var isUp:Boolean=false;
var isSpace:Boolean=false;
var isDown:Boolean=false;
var speed:Number = 3;

var mazeRect:Rectangle = bounds.getBounds(this);
var charRect:Rectangle = char.getBounds(this);
var boundsBmpData = new BitmapData(mazeRect.width, mazeRect.height, true, 0);
var charBmpData = new BitmapData(charRect.width, charRect.height, true, 0);

boundsBmpData.draw(bounds);
charBmpData.draw(char);

stage.addEventListener(KeyboardEvent.KEY_DOWN, keyPressed);
stage.addEventListener(KeyboardEvent.KEY_UP, keyReleased);
stage.addEventListener(Event.ENTER_FRAME, moving);

    function keyPressed(event:KeyboardEvent):void
        {
             if(event.keyCode==39){
             isRight=true
             char.gotoAndStop('right')}
             if(event.keyCode==37){
             isLeft=true
             char.gotoAndStop('left')}
             if(event.keyCode==38){
             isUp=true
             char.gotoAndStop('up')}
             if(event.keyCode==40){
             isDown=true
             char.gotoAndStop('down')}
             if(event.keyCode==32){
             isSpace=true
             }
            if(char.hitTestObject(order) && isSpace == true && orders <3)
     {
     orders++ ;
     }
     if(char.hitTestObject(orderz) && isSpace == true && orders > 0 && holding <3 )
            { orders--;
            holding++;}
            if(char.hitTestObject(order2) && isSpace == true && orders > 0)
            { orders--;
            holding++;}
            if(char.hitTestObject(order3) && isSpace == true && orders > 0)
            { orders--;
            holding++;}
             if (char.hitTestObject(client) && client.currentLabel == 'seated' && isSpace == true && holding>0){
    delivery++;

}

            if( char.hitTestObject(order) && isSpace == true && orders == 1){
                orderz.gotoAndPlay('one')
            }
            if( char.hitTestObject(order) && isSpace == true && orders == 2){
                order2.gotoAndPlay('two')
            }
            if( char.hitTestObject(order) && isSpace == true && orders == 3){
                order3.gotoAndPlay('three')

            }
            if( char.hitTestObject(orderz) && isSpace == true){
                orderz.gotoAndPlay('zero')
            }
            if( char.hitTestObject(order2) && isSpace == true ){
                order2.gotoAndPlay('zero')

            }
            if( char.hitTestObject(order3) && isSpace == true ){
                order3.gotoAndPlay('zero')
            }
            if (counterDisplay.text == ('3') && delivery == 3)
        {
        served ++;
        //trace("ready");
        client.gotoAndPlay('leaving');
        }
        if (counterDisplay.text == ('2') && delivery == 2 )
        {
        served ++;
        //trace("ready");
        client.gotoAndPlay('leaving');
        }

        if (counterDisplay.text == ('1') && delivery == 1 )
        {
        served ++;
        client.gotoAndPlay('leaving');
        }

        if ( served == 1)
        {
        trace("ready");
        }

        }

    function keyReleased(event:KeyboardEvent)
        {
             if(event.keyCode==39){
             isRight=false}
             if(event.keyCode==37){
             isLeft=false}
             if(event.keyCode==38){
             isUp=false}
             if(event.keyCode==40){
             isDown=false}
              if(event.keyCode==32){
             isSpace=false}
        }

    function moving(e: Event): void
        {
              var newx: Number = char.x - (isLeft ? speed : 0) + (isRight ? speed : 0);
              var newy: Number = char.y - (isUp ? speed : 0) + (isDown ? speed : 0);
              if(!boundsBmpData.hitTest(new Point(bounds.x, bounds.y),
                                        255,
                                        charBmpData,
                                        new Point(newx, newy),
                                        255))
              {
                 char.x = newx;
                 char.y = newy;
              }

        }

```

Some additional info: the 'leaving'label is 200 frames in length and then it should stop at the next label. (the next label is not in the code yet, but the problem is that every time a key is pressed, the label 'leaving' repeats from the first frame. And the maincharacter should be movable during this animation so keys will be pressed, wich causes the label to loop/start over from the first frame.

# Answer
> 2 votes
The code only executes gotoAndPlay if the specified condition is true. You need to modify your if statements so that the condition is more strict. For example:

```
if(char.hitTestObject(order) && isSpace == true && orders == 1 && PREVIOUS_PLAY_IS_FINISHED){
     // only when previous animation of "one" finished then we play again.
     orderz.gotoAndPlay('one')
}

```

Without knowing exactly what you want to do, it's hard to tell you how to implement the stricter condition.

EDIT: You can use the `MovieClip.currentFrame` property to check whether the animation is still playing so that you do not repeat the animation again from start.

```
if(char.currentFrame == 200) // change 200 to the actual frame number, 200 from the "leaving" label.
{
    client.gotoAndPlay('leaving');
}

```

ALTERNATIVELY, to deal with the organisation of your general structure, you can consider making the animations of char as individual movieclips nested inside the char movieclip. Then can do things like

`char.leaving.play()` where leaving is the movieclip animation for "leaving" etc. then you can do things like

```
if(!char.leaving.isPlaying) // if not playing the leaving animation
{
   char.leaving.play();
}

```

---
Tags: flash, actionscript-3
---


# Question
Title: Stack based state design for isometric character movement, am I doing it right?
I have been reading around about stack-based FSM, and I found it to be perfect for my game. However, when a character moves, it consequently have to face in some direction (and animation of each direction will be different), now the problem that I am facing in my state machine design is the scope of each state.

For example, should I divide the state into `MOVE_LEFT, MOVE_RIGHT, MOVE_UP, MOVE_DOWN` or should I create one `MOVE` state with some direction argument in it. Now, the latter seems to be better, however, if I am to trigger direction change, how would I do it for a one-state `MOVE`? I could directly change the direction argument and manually change the animation sequence, which will destroy the whole purpose of state machine (State machine should change animation sequence OnEnter() state). Else, I would have complicate the state machine into hierarchy of states (Sub-states,etc.), and this seem unconvincing for me.

Or maybe I should implement some type of multiple, simultaneous states ---- Character's State (Jump, Move, Idle, Attack, etc) and Direction's State (Up down left right), then make it works concurrently, and apply stack-based architectue on Character's State only.

# Answer
I find it easier to think of what you see on the screen as a state.

For example, is "MOVE" in MOVE + LEFT and MOVE + RIGHT the same visually? If it is not, then you need at least 2 different states for MOVE, and since LEFT and RIGHT are different states as well, you might be better off combining MOVE and LEFT as one MOVE\_LEFT and so on.

As a counter example, is "HIT" in CRITICAL + HIT and NORMAL + HIT the same visually? Possibly. So we can have HIT as a state on it's own and CRITICAL, NORMAL as separate states.
> 1 votes

---
Tags: movement, fsm
---


title: Object-oriented Snake game design

text:
# Question
Title: Object-oriented Snake game design
I'm going to make a snake remake with SDL library and right now I'm thinking heavily about the object-oriented design.

I can imagine that I will have classes like `GameEngine`, `Snake`, `Board` and `Food`, but the interesting part is - how shall they interact between each other? How shall the game logic be designed?

For example, let's imagine here are some of the possibilities:

1. Every class except of `GameEngine` will hold only it's data (position of snake, food, etc.). All the game logic will be done in engine's `Update()` function. Therefore this function will be very big and every other part of the program fairly small.
2. `GameEngine` will only call appropriate functions of every object with the reference to `Board` and these individual functions will take care about the game logic.
3. something other

So I would like to know your opinion - what approach do you think is the best? I'm not aiming at low number of lines the game will have, but at the quality and "modularity" of the game object design.

# Answer
1. Option 1 is a very bad idea, you might aswell be coding in BASIC.
2. Option 2 sounds good enough for a Snake remake. Now start coding! :-)
3. If you were making something bigger than Snake, or are just using Snake as a toy project to get to know more advanced software engineering practices for games, go for option 3: .
> 10 votes

# Answer
Here's what I would suggest:

Start with a `GameObject` class. These will be objects that can interact with each other. Then, derive three children from it:

`Snake`, `Food` and `Wall`. Each will have its own `Update` function. Finally, you have a `Scene` which holds a list of `GameObject`'s. The main loop calls the Scene's `Update` every frame, which calls the `Update` function for each object.

Then you can start thinking about how each object interacts with each other. A final suggestion: let the Scene keep track of the score. It will probably make things easier.
> 4 votes

# Answer
My approach is create two main classes:

* Sprite: Background, npcs, etc. has methods and properties related to loading images, etc.
* Object: Inherits from Sprite, it's a more advanced Sprite, usually an npc or player, since it has properties/methods for collision, moving etc.

Then you create different classes/objects from those classes.
> 0 votes

---
Tags: c++, objects
---


title: Randomly generated track

text:
# Question
Title: Randomly generated track
I would like to create randomly generated track from one point to another with specified length of that track (it can be 2 more or less as a result of that function) in matrix. I have function called buildRoad(x,y,length) where x is width of my matrix and y is the height.

I separately generate start and end point.

I have to do it as a stack by use of Vector class, so every point is connected to each other horizontally or vertically (e.g. (0,1)-\>(0,2)-\>(1,2)).

And here is the point that I really don't know how to do: I don't know how to connect start and end with such a track. Track cannot cross. It would be easy, but it needs to be random. I've already made easiest and shortest route to the end and I tried to implement some kind of probability of choosing (randomly) direction where track will go on next step.

But when track turn into corner (because it can) it's dead end and I should try to build track again. And it can fail again and again. I just need an idea how to solve it.

EDIT:

# Answer
> 1 votes
One way to do it is with a Depth First Search (DFS) where at each step you look to place a new node in a random square which is:

* Unoccupied.
* Adjacent to the previous square.
* Close enough to the end point so that you can reach it given the distance remaining.
* Not been rejected previously via backtracking.

If there are no valid squares you backtrack and try a different option on the previous node.

You stop searching when you've reached the destination with a route in the length range you require.

The first and last nodes can obviously be placed before you start the search as there's no option over where those should be.

# Answer
> 0 votes
To make things easier, I would probably cut the requirement the algorithm should be able to generate tracks of different lengths. Since you've specified a range, it will need to keep track of the length anyway. You might as well pick one before, at random if you like, keeping in mind the starting and ending locations determine whether the length will be odd or even. Imagine a checkered board to see why.

Start out by drawing any one of the shortest possible tracks. If it is too short, select a random point on the track, then a second point a few nodes (Q) beyond the first, break up the track in between, and redraw the section using the two points as start and finish, but this time with a length of (Q+2), for instance by moving up at random until the traveled distance plus the minimum distance between the current node and the finish equals (Q+2), and start moving one tile in the direction of the finish every step after that. If at any point, you get stuck, revert to the last valid track and try again.

This algorithm will probably try to draw a lot of invalid paths, but leaves a lot of room for optimization, allows you to balance efficiency against 'flatness' of the probability distribution of all theoretically possible tracks, doesn't use relatively expensive tree searches and scales well, because you can make the redrawn sections as small as you want.

---
Tags: algorithm, matrix, random
---


title: 2D Tile-based Collision Detection

text:
# Question
Title: 2D Tile-based Collision Detection
I've been planning an indie game project for a while now. I'll summarise it for you so I can get right to the question.

It's done entirely using the latest version of XNA through Visual Studio. Hoping to put it on 360 and PC, but am only really looking for a PC-oriented solution at this stage.

It's a 2D side-scrolling shooter (think Metroidvania-style, or even Terraria). It will eventually include an in-game map editor with maps being tile-based (16x16). There will be upwards and downwards scrolling. I'm hoping to implement tile layers in the dev map editor (reason for a dev map editor is it's going to be heavily leaning towards a content-focus, so there will be a lot of maps).

Physical tiles will be very simple with only two major types. Block tiles, which are just a solid tile, and angled tiles, which are tiles with an incline that characters can walk on. I'm strongly considering abandoning angled tiles entirely, but not sure yet.

The character/NPC movement will be simple. Moving side-to-side, jumping, falling, flying (with appropriate items/situations), teleporting. All very static, no dynamic physics necessary. Only basic gravity. When a character steps off the edge of a tile, it falls. When it jumps and a tile is above it, it stops short and falls back down. When it reaches a protruding tile/wall, it can't move further unless it jumps over or flies. All the basic stuff.

Projectiles can be affected by gravity as well, and some situations may arise where a projectile may be manipulated mid-flight, but nothing requiring heavy physics. Some projectiles will move characters as well (think a simple "pushing" mechanic).

**So here's the question:** I'm at the stage where I'm starting to work on movement and collision-detection but I just can't set myself on a way to go about them. I need ways to determine when character, tiles, and projectiles collide. Given what I've said about the style I'm going for and the tile-based system I'm using, **can I get some recommendations+links to some tried and true collision detection methods others have used in similar situations, and maybe an example of a game using a similar approach?** What I need more than anything else is inspiration.

*And just a quick note, I have several years of experience as a programmer, so I'm not a total newbie :)*

# Answer
> 9 votes
I just discovered http://higherorderfun.com/blog/2012/05/20/the-guide-to-implementing-2d-platformers/ and seems a pretty good overview on 2D platformers. I haven't finished reading it, but i think it can help you a lot!

Also i can recommend http://info.sonicretro.org/Sonic\_Physics\_Guide, which is broad overview on physics techniques used in Sonic.

# Answer
> 5 votes
> But the amount of projectiles I'll have on screen at any given time means I'll be looking to implement something like QuadTree to keep things smooth performance-wise.

You might be okay without a quadtree:

1. Collisions between projectiles and *static* environment tiles can be done directly on the tiles array, without the need for any additional data structure. In other words, you can easily find which tiles an entity (e.g. a projectile) is intersecting directly, with a few calculations based on the bounds of the entity and the tile size. The platformer sample has an example of this problem which I'll transcribe below:

```
int leftTile = bounds.Left / TileSize;      // bounds = Rectangle of your entity
int topTile = bounds.Top / TileSize;
int rightTile = (int)Math.Ceiling((float)bounds.Right / TileSize) - 1;
int bottomTile = (int)Math.Ceiling(((float)bounds.Bottom / TileSize)) - 1;

for (int y = topTile; y <= bottomTile; ++y)
{
    for (int x = leftTile; x <= rightTile; ++x)
    {
        // Entity is touching tile[x, y] so check and handle collision
    }
}

```
2. For other *dynamic* objects such as characters, you could dynamically register/unregister them with the tiles that they're intersecting as they move, so that at any moment and for any tile you can directly know if any objects are there (here's an example, article about spatial hashing). If you implement that, then you can just do the same as step one to find which tiles the projectiles are interesecting, then check your grid to see if any objects are there, and if there are, iterate over them linearly.

This data structure can be as simple as:

```
var grid = new List<Entity>[width, height];

```

Or:

```
var grid = new Dictionary<int, List<Entity>>();

```

In which case you'd convert `[x,y]` to a single `int` key like `x+y*width` and then store in the dictionary.

# Answer
> 1 votes
If you are thinking about the high level flow of the movement and collision detection, something like this is common:

1. Handle logic and player input
2. Update object positions
3. Detect & handle collisions

When detecting collisions you want to filter out tiles and objects that are too far away to make it more efficient. If your level is defined as a 2d array for example you want to just consider the tiles in a certain range around each object. If your level is made out of tile objects, you might need to use some kind of spacial partitioning to avoid iteration through all of them.

To keep it simple you should probably use axis aligned bounding boxes for the collision shapes. This might help http://www.wildbunny.co.uk/blog/2011/12/14/how-to-make-a-2d-platform-game-part-2-collision-detection/

If you want to handle slopes and more general convex shapes you could use the separating axis theorem: http://rocketmandevelopment.com/2010/05/19/separation-of-axis-theorem-for-collision-detection/, but it might be simpler to make an ad-hoc solution for slopes if you only have a small number of slope types.

---
Tags: xna, 2d, collision-detection, xna-4.0, tiles
---


title: Score vs. Kills in a casual game

text:
# Question
Title: Score vs. Kills in a casual game
I am making a simple phone game and having a conceptual argument with my partner. The argument might end up being inconsequential, but I would like to hear some opinions from actual devs who are making games.

This will be a pretty standard beat-em-up style game where you beat up lots of easy enemies and build up a huge kill count. There will be many different types of enemies. The question emerged when we had to put up some display on the UI.

**Should the kill count be represented as a 1:1 number? For example, on your HUD, it will constantly show:**

Kills: 15

--or--

Defeated: 31

**Or, should it be represented by a score? For example: 1 enemy = 100 points and it will display something like this:**

Score: 1200

This may be a matter of taste in the end. But, for the casual games market, what do you think a mainstream audience will enjoy more? I think people love big numbers, in general, what do you guys think?

# Answer
> 2 votes
If you've only got one type of enemy, it doesn't *really* matter: 1 enemy or 100 points still adds up the same in the end, the only difference being the need to mentally divide by 100 points to get the kill count (if you go down the score road).

On the other hand, if you've got different types of enemy, then points are definitely the way to go. That way, you have the option of making it so killing a large/powerful/hard enemy can earn the player more points than killing a small/weak/easy enemy.

**EDIT**: Given that you seem to imply you're working with just one type of easy enemy, I'd personally just go with a kill count - multiplying it by 100 and calling it a "score" doesn't add anything useful.

Ok, so you've got lots of types of enemy - definitely go with a score, not just a kill count. That way players can get some extra "flavour" by having different point values for different enemies. Also note I said "not **just** a kill count" - there's no general reason you can't have both a kill count **and** a score.

# Answer
> 5 votes
I'd go with calling it score, and awarding more than one point per kill.

That way if your game design changes later to include say bonus points for killing more than one enemy simultaneously or other factors then it makes it less disruptive to add them in.

I think big numbers also feel better to the user. For example play almost any arcade game and you won't score less than 10 points for anything.

# Answer
> 1 votes
You should definitely go with a score count - even if you only give 1 point per kill. If you implement a score system, you will have an easier time later on if you decide to implement more enemy types, or a combo system in the future.

---
Tags: game-design, leaderboards, ui-design
---


# Question
Title: How do mobile mmo's deal with the graphical resources?
I'm am creating an MMO(probably won't be so *massive*), and was wondering how to deal with the graphical resources. Obviously, I can't have what could be possibly a few gigs of images and animations loaded up to the client, so I need another way of doing it. I have tried having a php webserver that updates itself and writes to a file that the client draws, however this seems slow. How can I speed up the process of updating the graphics while not having too much into the client?

# Answer
Networking is usually a bottleneck for real-time multi player games and as such, information sent needs to be kept to an absolute minimum. Adding image deltas (or even full images?) to the packet of information sent to every client during every frame can (as you have discovered) easily reduce your networking to an unusable speed and would not scale well (imagine the network load with a couple of thousand players).

A few random ideas for minimising the amount of texture data on the client are:

* Querying the OS for the screen size and downloading a texture set to suit when the game is first run (that way a large tablet could be given a large texture set while a small phone only gets a small one).
* Asking the user which texture set they want to use and letting them know how much space they need for each option.
* Including a high resolution texture set as a free/cheap add-on in the app store/Google play, which ensures there is enough space before installing it.
> 3 votes

# Answer
You could try the "curling method". I may be butchering this but bare in mind. I went to a talk on social games and how they handle large images and what they do is a technique called curling where they have a high-res, and low-res image. So when the user isn't using the image they get the low-res version, and when they are using it they receive the high-res version. I'm not sure if this helps at all, but it might make the loading be faster.
> 0 votes

# Answer
1. Using Highres and lowres pictures for different distances is a pretty good thing to take care of.
2. Also you should unload objects that aren't used.
3. Everything should be stored local or loaded at the startup of the game.
> 0 votes

---
Tags: graphics, mmo, mobile
---


# Question
Title: What Do I Pass for inputGeometryTransform Parameter of ID2D1Geometry::CompareWithGeometry?
I have a list of ID2D1Geometry objects and I'm trying to use CompareWithGeometry to detect collisions in Direct2D; unfortunately, I'm not getting the results I need. I suspect I am improperly using the inputGeometryTransform parameter.

If I pass in D2D1::Matrix3x2F::Identity() or nullptr for this parameter, I almost always get D2D1\_GEOMETRY\_RELATION\_CONTAINS (3) or D2D1\_GEOMETRY\_RELATION\_IS\_CONTAINED (2) results back for the returned D2D1\_GEOMETRY\_RELATION. On the other hand, if I try and pass in the product of the scale and translation matrices that I used to generate the primary geometry, then I never get collisions.

Can someone help me understand what I need to pass in for the inputGeometryTransform parameter?

The source code that I believe to be relevant appears below:

```
// This is Shawn Eary's broken code and it is licensed 2012 under the
// Microsoft Public License (Ms-PL) which is compatible with the
// Open Source Initiative
//
// Shawn Eary is not affiliated with Microsoft.
// He just likes the Ms-PL
void SpaceObject::updateDynamics(
    Microsoft::WRL::ComPtr<ID2D1DeviceContext> const i_d2dContext,
    D2D1::Matrix3x2F const & tranformMatrix)
{
    D2D1_SIZE_F renderTargetSize = i_d2dContext->GetSize();
    float const worldWidth = renderTargetSize.width / 2.0f;
    float const halfWorldWidth = worldWidth / 2.0f;
    float const worldHeight = renderTargetSize.height / 2.0f;
    float const halfWorldHieght = worldHeight / 2.0f;

    // Update the position in ideal coordinates
    double idealX = m_p.x + m_v.x;
    double idealY = m_p.y + m_v.y;

    // Account for wrap around
    m_p.x = getWrappedResult(idealX, worldWidth);
    m_p.y = getWrappedResult(idealY, worldHeight);
    m_p.theta += m_v.theta;

    m_v.x += m_a.x;
    m_v.y += m_a.y;
    m_v.theta += m_a.theta;

    // Compute results of elastic collisions
    for (list<SpaceObject *>::iterator it = m_myObjectWorldP->begin(); it != m_myObjectWorldP->end(); it++) {
        SpaceObject * const SOP = (*it);

        // This eventually needs to be fixed, but for now assume all
        // spaceObjects are GeometrySpaceObjects
        GeometrySpaceObject * thisGSOP = dynamic_cast<GeometrySpaceObject*>(this);
        GeometrySpaceObject * currentGSOP = dynamic_cast<GeometrySpaceObject*>(SOP);

        // Don't compare this SpaceObject with itself
        if (thisGSOP != currentGSOP) {
            ID2D1PathGeometry * const thisGP = thisGSOP->gGeoP();
            ID2D1PathGeometry * const curGP = currentGSOP->gGeoP();
            D2D1_GEOMETRY_RELATION theRelation;
            thisGP->CompareWithGeometry(
                (ID2D1Geometry *)curGP,
                tranformMatrix,
                &theRelation
            );
            if (theRelation != D2D1_GEOMETRY_RELATION_DISJOINT) {
                // A Collision has occured.
                //
                // Use conservation of momentum to update
                // velocities after collission here
                int placeHolder = 0;
            }
        }
    }

    this->updateAcceleration();
}

```

Note: At the time I asked this question, the documentation I found on the MSDN site was a bit unclear regarding the inputGeometryTransform Parameter. The documentation I viewed was visible at this URL: http://msdn.microsoft.com/en-us/library/windows/desktop/dd316638(v=vs.85).aspx

# Answer
> 1 votes
As said in the comment, the inputGeometryTransform Parameter is used to scale, rotate or translate the target geometry before it is compared with the host geometry. Without that translation, geometries will be processed relative to where their figure began in their associated Geometry Sinks; unfortunately, only being able to scale the target geometry was a bit awkward for me so I found an interesting function called CreateTransformedGeometry. Using a few MSDN examples, I was able to create this function that was useful to me:

```
// This is Shawn Eary's code and it is licenced under the
// Microsoft Public License (Ms-PL) which is compatible with the
// Open Source Initiative
//
// Shawn Eary is not affiliated with Microsoft.
// He just likes the Ms-PL
//
// References and Influences Used:
// http://msdn.microsoft.com/en-us/library/windows/desktop/dd742769(v=vs.85).aspx
// http://msdn.microsoft.com/en-us/library/windows/desktop/dd742730(v=vs.85).aspx
HRESULT TransformGeometry(
    ID2D1Geometry *ipGeometryToTransform,
    ID2D1Geometry **oppTranformedGeometry,
    D2D1_MATRIX_3X2_F const & transform
    )
{
    HRESULT hr;
    ID2D1Factory *pFactory = NULL;
    ipGeometryToTransform->GetFactory(&pFactory);

    ID2D1TransformedGeometry *pTransformedGeometry = NULL;
    hr = pFactory->CreateTransformedGeometry(
        ipGeometryToTransform,
        transform,
        &pTransformedGeometry
     );

    *oppTranformedGeometry = pTransformedGeometry;
    (*oppTranformedGeometry)->AddRef();
    pTransformedGeometry->Release();

    return hr;
}

```

Then, using the new TransformGeometry function, my UpdateDynamics code could then could be rewritten for hit-testing like this:

```
// This is Shawn Eary's code and it is licenced under the
// Microsoft Public License (Ms-PL) which is compatible with the
// Open Source Initiative
//
// Shawn Eary is not affiliated with Microsoft.
// He just likes the Ms-PL
void SpaceObject::updateDynamics(
    Microsoft::WRL::ComPtr<ID2D1DeviceContext> const i_d2dContext)
{
    D2D1_SIZE_F renderTargetSize = i_d2dContext->GetSize();
    float const worldWidth = renderTargetSize.width / 2.0f;
    float const halfWorldWidth = worldWidth / 2.0f;
    float const worldHeight = renderTargetSize.height / 2.0f;
    float const halfWorldHieght = worldHeight / 2.0f;

    // Update the position in ideal coordinates
    double idealX = m_p.x + m_v.x;
    double idealY = m_p.y + m_v.y;

    // Account for wrap around
    m_p.x = getWrappedResult(idealX, worldWidth);
    m_p.y = getWrappedResult(idealY, worldHeight);
    m_p.theta += m_v.theta;

    m_v.x += m_a.x;
    m_v.y += m_a.y;
    m_v.theta += m_a.theta;

    // Compute results of elastic collisions
    for (list<SpaceObject *>::iterator it = m_myObjectWorldP->begin(); it != m_myObjectWorldP->end(); it++) {
        SpaceObject * const SOP = (*it);

        // This eventually needs to be fixed, but for now assume all
        // spaceObjects are GeometrySpaceObjects
        GeometrySpaceObject * thisGSOP = dynamic_cast<GeometrySpaceObject*>(this);
        GeometrySpaceObject * currentGSOP = dynamic_cast<GeometrySpaceObject*>(SOP);

        // Don't compare this SpaceObject with itself
        if (thisGSOP != currentGSOP) {
            D2D1_MATRIX_3X2_F thisTransform = thisGSOP->gTransformation();
            D2D1_MATRIX_3X2_F currentTransform = currentGSOP->gTransformation();
            ID2D1PathGeometry * const thisGP = thisGSOP->gGeoP();
            ID2D1PathGeometry * const curGP = currentGSOP->gGeoP();

            D2D1_GEOMETRY_RELATION theRelation;
            ID2D1Geometry * thisTGP;
            TransformGeometry(thisGP, &thisTGP, thisTransform);
            ID2D1Geometry * currentTGP;
            TransformGeometry(curGP, &currentTGP, currentTransform);
            thisTGP->CompareWithGeometry(
                (ID2D1Geometry *)currentTGP,
                NULL,
                &theRelation
            );
            thisTGP->Release();
            currentTGP->Release();
            if (theRelation != D2D1_GEOMETRY_RELATION_DISJOINT) {

                // A Collision has occured.
                //
                // Use conservation of momentum to update
                // velocities after collission here
                int placeHolder = 0;
            }
        }
    }

    this->updateAcceleration();
}

```

---
Tags: c++, collision-detection, directx
---


title: Vectors and corners of squares

text:
# Question
Title: Vectors and corners of squares
I am having some problems with some vector math.

Imagine a square and coming from each corner of the square is an invisible vector, which starts at the square's centre and ends at the edge of the screen.

```
   \          /
    \   a    /
     \______/
     |      |
  d  |      | b
     |______|
    /        \
   /    c     \
  /            \
THIS IS A VERY CRUDE IMAGE AND THE ANGLES OF THE VECTORS ARE NOT EQUAL

```

There are 4 areas: a, b, c and d

I would like to say that if you touch within one of the areas then something happens.

Is there a simple way to do this?

# Answer
> 2 votes
Translate and scale the input coordinates to have the origin in the center of the screen and have vectors towards the corners of the screen at 90° angles. Then, to exclude the inner square, use:

```
abs(x) > s
abs(y) > s

```

Where s is the size of the square. Then, to identify the area, use:

```
a: y > x and y > -x
b: x > y and x > -y
c: y < x and y < -x
d: x < y and x < -y

```

# Answer
> 1 votes
I would just use two point-in-triangle tests for each of the areas.

# Answer
> 0 votes
I would suggest that the easiest way is to look at the angle between one of these vectors and where the user touches. You can use the dot product method to work this out; see here.

The dot product will give you the angle between the chosen vector and the user's touch point (you may have to translate this touch point into the squares local coordinate space). Then if you use the top left vector for the comparison, you will find that if the angle is less than 90 then the user touches quadrant a, if it's more than 90 but less than 180, then it's quadrant b and so on.

Edit: Sorry dot product doesn't give you the angle, it gives you the cosine of the angle. So you have to do inverse cosine on the result. You can also use atan2 to get the angle.

# Answer
> 0 votes
For concreteness, let's say that your screen spans from sx\_0 to sx\_1 and sy\_0 to sy\_1 (so the four corners of the screen are (sx\_0, sy\_0), (sx\_1, sy\_0), (sx\_1, sy\_1) and (sx\_0, sy\_1) ) and likewise that the inner box runs from ix\_0 to ix\_1 and iy\_0 to iy\_1; finally, say the user has touched at (tx,ty).

The simplest way to order the tests is to first test the touch point against the inner square; knowing that it's not inside simplifies the other ones. This test is straightforward: if

```
(tx >= ix_0) && (ty >= iy_0) && (tx < ix_1) && (ty < iy_1)

```

then your point is in the inner rectangle. How you want to handle the edge cases with respect to points in the center box is, of course, up to you - be careful with them, though!

Once you know your point isn't in the inner box, the most straightforward way of testing each of the other regions is by doing two 'half-space' comparisons against the diagonal lines that bound them. To explain in slightly more detail: the equation of a line, generically, is 'A.P=b', where P=(x,y) is an arbitrary point on the line, A is a vector perpendicular to the line, and b is some constant; what's more, if a vector in the direction of the line is (vx, vy), then the vector (vy, -vx) is perpendicular to the line. What's that mean here? Well, consider the dividing line in the top-left corner: this line goes from (sx\_0, sy\_0) to (ix\_0, iy\_0), so a vector in the direction of the line is (ix\_0-sx\_0, iy\_0-sy\_0) and a vector perpendicular to the line is (iy\_0-sy\_0, sx\_0-ix\_0) (be careful - notice how the second coordinate got flipped!) What's more, we can find the value of b by plugging in one of the two points we know is on the line: for instance, using (sx\_0, sy\_0) we find that the dot product is sx\_0\*(iy\_0-sy\_0)+sy\_0\*(sx\_0-ix\_0), or (cancelling out the sx\_0\*sy\_0 terms) sx\_0\*iy\_0-sy\_0\*ix\_0. In other words, the equation of the line is (iy\_0-sy\_0)\*x+(sx\_0-ix\_0)\*y = sx\_0\*iy\_0-sy\_0\*ix\_0. What's more, which side of the line a point is on is determined by whether the dot product is less than or greater than sx\_0\*iy\_0-sy\_0\*ix\_0.

Finally, to use this: consider for instance the top region. Then this is the section that lies to a specific side of the line from (sx\_0, sy\_0) to (ix\_0, iy\_0) and also on a specific side of the line from (sx\_1, sy\_0) to (ix\_1, iy\_0). In other words, to test your point (tx, ty), you'll know that it's in your region a if:

```
tx*(iy_0-sy_0)+ty*(sx_0-ix_0) > sx_0*iy_0-sy_0*ix_0

```

and

```
tx*(iy_0-sy_0)+ty*(sx_1-ix_1) <= sx_1*iy_0-sy_0*ix_1

```

Likewise, you can do similar tests for the other three regions using the appropriate lines from inner to outer corner. These tests may look complicated, but they're pretty straightforward and they have a lot of advantages: they'll work no matter where your inner box is (as long as the box is entirely contained inside your screen), whatever the dimensions of your screen and inner box are, and they don't involve anything more complicated than a few multiplies - they can even be done in purely integer math if need be.

---
Tags: android, mathematics, vector
---


# Question
Title: Unity3D: Touch and Objects have different coordinate systems
I would like to associate the same script to different empty objects I just use as placeholders in the game. The aim is to exploit their positions so that when the user touch a point in the screen, close to one of these objects, a dedicate GUI appears. The problem is that though the two objects are different their scripts seem to influence each other so that when the game is running and I touch one of these two objects both the gui appears. What am I doing wrong?

Some hours later... This happens because the object and the touch are in two different coordinate systems. For instance though I touch the object I get (-0.77, 0.46) for the object and (12.1,95.2) for the touch which, I guess, is measured in pixel. How to transform one into the other?

```
....
private var check: boolean;
var topCamera : Camera;
var customSkin : GUISkin;

function Update () {
   if (Input.GetMouseButtonDown(0)){
      if(Input.mousePosition.x > this.transform.position.x - Screen.width*0.20 && Input.mousePosition.x < this.transform.position.x + Screen.width*20){
        if(Input.mousePosition.y > this.transform.position.y - Screen.height*0.2 && Input.mousePosition.y < this.transform.position.y + Screen.height*0.2){
                check = true;
        }
    }
}

if(check){
   //the camera zooms forward
}else{
   //the camera zooms backward
}
}

function OnGUI () {
if (this.check){
var w = Screen.width;
var h = Screen.height;
var bw = 0.083;
var bws = 0.001 *w;
GUI.skin = customSkin;
GUI.Box(new Rect(w*0.6,h*0.3,w*0.38,h*0.45), "Stuff");
customSkin.box.fontSize = 0.04*h;
customSkin.textField.fontSize = 0.08*h;
customSkin.button.fontSize = 0.04*h;
textFieldString = GUI.TextField (Rect (w*0.62, h*0.39, w*0.34, h*0.1), textFieldString);
if (GUI.Button (Rect (w*0.62,h*0.50, w*bw, h*0.1), "+")) {
    if (this.check){
        this.check=false;

    }else{
        this.check = true;
    }
//...
}
 //...
    }

```

# Answer
> 2 votes
> Some hours later... This happens because the object and the touch are in two different coordinate systems. For instance though I touch the object I get (-0.77, 0.46) for the object and (12.1,95.2) for the touch which, I guess, is measured in pixel. How to transform one into the other?

As you said, touch/mouse clicks are measured in pixels, and transform.position is measured depending on the kind of GameObject you have. For example, for GUI Textures it is measured on Viewport coordinates; for a Mesh objects it is measured in World coordinates. Other objects like the GUI buttons etc, have pixels (screen) coords taken from the Rect that defines them.

Unity provides functions (actually accessible from a Camera Component) to change from one coordinate system into the other:

Camera.WorldToScreenPoint To change from world to pixels (screen)

\[Camera.ScreenToWorldPoint\] To change from screen to World

... and so on. Look for this kind of functions on the Camera Component specification

# Answer
> 0 votes
Hard to say without any code, but you seem to share the objects states in some way. I guess, there's a variable that determines whether the GUI is visible or not - does that happen to be a static variable? If so, make it non-static, because static variables only exist once (globally) und thus are shared among all object instances.

Another possible problem might be the code by which you determine whether an object is pressed by the user - even if the objects do not share a state, they might still trigger all at once due to some coding error. Again, hard to say without any code.

Edit: The code itsself doesn't seem to be wrong, but I'm not really experienced with UnityScript / JavaScript - I always used C# in Unity. However, you are comparing the transforms X and Y coordinates to X and Y screen coordinates - which *can* be correct but is not *necessarily* correct. Since transform describes a position in space (3D), it depends on the cameras view whether X-X and Y-Y comparisons are correct. If the camera looks at the scene at a different angle, it might be X-Z and Y-Y or even completely wrong due to non axis-aligned view or perspective projection parameters. I'm not using Unity anmore, but could you use an additional trigger-setting Collider Component to recieve mouse events? That should be a lot more robust and flexible.

---
Tags: unity
---


# Question
Title: How do I make a video preview of my Android game?
I noticed some apps have a link to a Youtube video instead of a screenshot in Google's Android Play store. How can I make a video of my Android game running on a physical device? The emulator won't work for me (my game uses the camera preview feed). I guess I could take a video of the phone with another device, but that seems a little cheesy to me.

# Answer
There are programs available to capture video on the physical device. See this question about that. Beyond that, I think you have an opportunity here to not just make a video capture of your game, but to make a trailer. Check out this article on making video game trailers to see what time/resources you have to making a excellent trailer.
> 3 votes

# Answer
Some phones(or tablets) have an HDMI output, you can connect your HDMI cable to a video recorder linked to your PC.
> 1 votes

---
Tags: android
---


# Question
Title: Best way to calculate unit deaths in browser game combat?
My browser game's combat system is written and mechanically functioning well. It's written in PHP and uses a SQL database. I'm happy with the unit balance in relation to one another. I am, however, a little worried about how I'm calculating unit deaths when one player attacks another because the deaths seem to pile up a little fast for my taste.

For this system, a battle doesn't just trigger, calculate winner, and end. Instead, it is allowed to go for several rounds (say one round every 15 mins.) until one side passes a threshold of being too strong for the other player and allows players to send reinforcements between rounds.

Each round, units pair up and attack each other. Essentially what I do is calculate the damage:

AP = Attack Points
HP = Hit Points

```
Units AP * Quantity * Random Factors * other factors (such as attrition)

```

I take that and divide by the defending unit's HP to find the number of casualties of defending units. So, for example (simplified to take out some factors), if I have: `500 attackers with 50 AP vs 1000 defenders with 100 HP = 250 deaths`. I wonder if that last step could be handled better to reduce the deaths piling up.

Some ideas:

1. I just change all the units with more HP?
2. I make sure to set the Attacking unit's AP to be a max of the defender's HP to make sure they only kill 1 unit. (is that fair if I have less huge units vs many small units?)
3. I spread the damage around more by including the defending unit's quantity more? i.e. in that scenario some are dead and some are 50% damage. (How would I track this every round?). This kind of seems like the best idea, but not sure how i'd track it in the DB.
4. Other better mathematical approaches?

# Answer
> 2 votes
There are several answers in this question which might help: Calculating the output of two armies fighting.

However, one simple answer is just to scale your values. If 1 point of attack power basically negates 1 hit point, and you think that kills too many units, then make 1 point of attack power negate 0.75 hit points (or whatever). eg.

`(Attack Power * Quantity of Attackers) * 0.75 / Defending Unit HP = Deaths`

These values are yours to do what you want with, so add whatever you need to make the outcome resemble the gameplay you want.

# Answer
> 1 votes
*-- It's hard to give you an accurate answer because we don't know how your turns are organized or how works your unit teams work --*

Let me make a point about what you have right know.

You have 500 attackers. Each attacker is defined by a number of Attack Power. They fight against defenders. They are 1000 and are defined by a number of Health Points.

It seems logic that 1 attacker can only fight 1 defender at the time (it seems that your game is turn based). For 1:1 combat the basic design would be to say "if AP are bigger than HP then there is as much as death that attackers; every defender dies". But on a real battlefield things are not that simple: people can kill more than one guy with a little luck, or no one with a lack of luck. You will have to add some randomness in your equation in order to basically simulate a real combat. I would suggest to pre-compute the winner of the battle (easy: the biggest, the strongest) and then to make the number of deaths vary a little bit.

For a 100:100 battle with 50AP and 100HP you have to wait 2 turns to kill your defenders with your equation, but if you apply something like:

```
X * ((Attack Power * Attackers) / (Health Point * Defenders))

```

With X a random value between 0.75 and 1 (up to 1.2 if the pre-computed winning team is more numerous than the loser one, in order to simulate the 'chance' to kill a little bit more than only with 1:1 ratio), you will obtain unpredictable results (from a player point of view).

Anyway you not necessarily need to manage each unit stats. At the end of the battle (a battle is composed of several turns until one of the team has no more unit), you will count deaths in each team (attackers and defenders) and reduce their actual total number of unit.

---
Tags: mathematics, browser-based-games, combat
---