# Question
Title: Is there a more general property or class of properties or concept that encompasses position and space?
Is there a more general property or class of properties or concept that encompasses the concept of position and space?

It does not seem clear to me that position is the most general property (if it is a property) applicable to an object, so I have been searching for a more general property, or class of properties, which will include the property of position, but I have been unable to find anything.

# Answer
The more general idea is *transformation*, which includes a frame of reference and typically rotation. The frame of reference with respect to position could be another object ie. 10 feet above earth's surface at lat X, long Y, or it could be implied to be the world origin (0,0,0). For rotation, we usually use a canonical rotation that is the result of whatever format, say, a model is in, and then the rotation is implied to be offset from that.

Unity actually takes frame of reference from parented objects, such that each item has a local position that is offset from its parent objects. For example, a driver's position is local to their car, and thus the world position of the driver is relative to the car's rotation and position.

This is an important concept because position at any given time can depend on attached objects' current rotation and position. An especially complex example:

Local Cluster -\> Galactic Center -\> Sun -\> Earth -\> Car -\> Driver -\> Driver's Hat -\> Spider on Hat

With this scale of simulation, we need to know the driver's hat's position relative to the driver, the position of the driver relative to the car, the rotation and position of the car relative to earth, the location and rotation of the earth, and so on.

Of course, unless you're working on something like Kerbal Space Program, this amount of parenting is unnecessary. Most often we use this to attach clothes and props to bodies and bodies to vehicles.
> 1 votes

---
Tags: terminology
---


# Question
Title: Set color by uniform per sprite using libGDX SpriteBatch
I am using a *SpriteBatch* to render large amounts of sprites very fast. Now I want to modify the sprites with shaders to tint them in a color.

**Problem 1**: Altering an uniform by getting the shader and setting it between the begin/end of the batch changes the whole scene not only a single sprite. E.g.:

```
"EngineView.getShader().setUniformf("u_blue", (float) Math.random());"

```

**Problem 2**: It is relatively slow.

Also I found this which seems to cover the same (no proper solution): (Setting uniform value of a vertex shader for different sprites in a SpriteBatch):

> You almost certainly don't want to actually do this. Changing a uniform for every quad/sprite is going to severely impact the throughput of your renderer. Much of the GPU will be sitting idle while you're drawing one measly sprite at a time. The whole point of a "sprite batch" is to draw as many sprites at the same time with as few draw calls or state changes as possible. If you need random data in your shader, use a noise texture or a noise function. stackoverflow.com/questions/4200224/… – Sean Middleditch May 23 at 21:22

My question is, if I don't want to actually do this, what is it I want to do?

# Answer
Setting a uniform per sprite is probably not a good idea, as Sean Middleditch already pointed out.

Tinting a sprite in OpenGL can easily be done by defining the vertex colors. Since the vertices in this case are defined by SpriteBatch.draw(), you should set the tint with SpriteBatch.setColor().

From the SpriteBatch source code:

```
200 public void setColor (float color) {
201     this.color = color;
202 }

```

and

```
499 public void draw (Texture texture, float x, float y,
    float width, float height) {
...
516 float color = this.color;
517 int idx = this.idx;
518 vertices[idx++] = x;
519 vertices[idx++] = y;
520 vertices[idx++] = color;
521 vertices[idx++] = u;
522 vertices[idx++] = v;
...

```

(which is repeated for all 4 vertices of the quad)

The color can then be used in the vertex shader. By multiplying it with 2.0 you can use the range from 0%-200% allowing you to darken and brighten it.

```
v_color = a_color*gl_Color*2.0;

```
> 3 votes

---
Tags: libgdx, shaders, sprites, spritesheet, spritebatch
---


# Question
Title: Java 2d: How to make animation only cycle once, despite control being held down?
I've been working on a 2d game, and I think I've been over-complicating how to make an animation only cycle through once. For example, if the user presses the 'a' key, the character's 'attack' variable is set to true, then the the game will continually render the animation sprite images to the screen in a loop until the key is released. The problem is, I want the attack animation to only happen once, whether the 'a' key is held down for .001 seconds or for 1 minute.

I am trying to solve this by raising a flag in the Animation's tick method when the last frame is hit. However when it comes to resetting this flag, I don't know how it would be done. This is a pretty broad question (with probably a lot of solutions), so let me know if I'm leaving out any details. Here is a sample of code with everything removed except for what pertains to 1 player action (attack, for this example):

Game class (w/ main()):

```
public class Game extends Canvas implements Runnable{
    private static final long serialVersionUID = 1L;
    public static final int WIDTH = 1200, HEIGHT = 600, SCALE = 1;
    public static boolean running = false;
    public Thread gameThread;

private BufferedImage p1AttackSpriteSheet;
private ImageManager im;

private static Player1 player1;

public void init(){
    ImageLoader loader = new ImageLoader();

    //Prepare sprite sheets (the loading takes some time...)
    p1AttackSpriteSheet = loader.load("/player1/attackSpriteSheet.png");
    SpriteSheet SS1 = new SpriteSheet(p1AttackSpriteSheet);

    im = new ImageManager(SS1);

    player1 = new Player1(-50, 200, im);
}

public synchronized void start() {
    if(running)return;
    running = true;
    gameThread = new Thread(this);
    gameThread.start();
}

public synchronized void stop() {
    if(!running)return;
    running = false;
    try {
        gameThread.join();
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

public void run() {

    // Credit for this run loop goes to MadProgrammer @ StackOverflow
    init();
    final long amountOfTicks = 60;
    long ns = Math.round(1_000_000_000 / (double)amountOfTicks);

    int frames = 0;
    long frameStart = System.currentTimeMillis();

    while (running) {
        long startedAt = System.nanoTime();
        tick();
        render();
        long completedAt = System.nanoTime();
        long duration = completedAt - startedAt;

        long frameEnd = System.currentTimeMillis();
        if (frameEnd - frameStart >= 1000) {
            System.out.println(frames);    //Take this out for final version
            frames = 0;
            frameStart = System.currentTimeMillis();
        } else {
            frames++;
        }

        long rest = ns - duration;
        if (rest > 0) {
            rest = TimeUnit.MILLISECONDS.convert(rest, TimeUnit.NANOSECONDS);
            try {
                Thread.sleep(rest);
            } catch (InterruptedException ex) {
            }
        }
    }
    stop();
}

public void tick() {
    player1.tick();
}

public void render() {

    BufferStrategy bs = this.getBufferStrategy();
    if(bs == null)
    {
        createBufferStrategy(3); //Use 5 at most
        return;
    }
    Graphics g = bs.getDrawGraphics();

    //RENDER HERE
    player1.render(g);
    //END RENDER

    g.dispose();
    bs.show();
}

public static void main(String[] args)
{
    JLabel controlKeyPanel;

    Game game = new Game();
    game.setPreferredSize(new Dimension(WIDTH * SCALE, HEIGHT * SCALE));

    JFrame frame = new JFrame("-");
    frame.setResizable(false);
    frame.setSize(WIDTH * SCALE, HEIGHT * SCALE);
    frame.setLayout(new BorderLayout());

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.add(game);

    frame.setVisible(true);

    game.start();
}

public static Player1 getPlayer1() {
    return player1;
}

public static Player2 getPlayer2() {
    return player2;
}

```

KeyManager Class:

```
public class KeyManager implements KeyListener{

    public void keyPressed(KeyEvent e) {

        int keyCode = e.getKeyCode();

        if(keyCode == KeyEvent.VK_A) //P1 Attack
        {
            Game.getPlayer1().attack1 = true;
        }
    }

    public void keyReleased(KeyEvent e) {

        int keyCode = e.getKeyCode();

        if(keyCode == KeyEvent.VK_C) //P1 Attack
        {
            Game.getPlayer1().attack1 = false;
        }
    }
}

```

Player1 class:

```
public class Player1 {

private ImageManager im;
public boolean attack1 = false;
private int x1, y1;

private Animation P1AttackLeftAnimation;

public Player1(int x, int y, ImageManager im) {
    this.x1 = x;
    this.y1 = y;
    this.im = im;

    P1AttackLeftAnimation = new Animation(im.player1AttackLeft, 20);
}

public void tick() {

    P1AttackLeftAnimation.tick();
}

public void render(Graphics g) {

    if(attack1)
    {
        P1AttackLeftAnimation.render(g, x1, y1, 400 * Game.SCALE, 400 * Game.SCALE);
    }
}
}

```

Animation class:

```
public class Animation {

    private BufferedImage[] images;
    private int interval, index;
    private long timer, now, lastTime;
    public boolean cycleComplete = false;

    public Animation(BufferedImage[] images, int interval) {
        this.images = images;
        this.interval = interval;
        index = 0;
        timer = 0;
        now = 0;
        lastTime = System.currentTimeMillis();
    }

    public void tick() {
        now = System.currentTimeMillis();
        timer += now - lastTime;
        lastTime = now;

        if(timer >= interval)
        {
            index++;
            timer = 0;

            if(index >= images.length)
            {
                cycleComplete = true;
                index = 0;
            }
        }
    }

    public void render(Graphics g, int x, int y, int width, int height) {

        g.drawImage(images[index], x, y, width, height, null);
    }
}

```

ImageManager class:

```
public class ImageManager {

    public BufferedImage [] player1AttackLeft;

    public ImageManager(SpriteSheet ss1) {

        player1AttackLeft = new BufferedImage[12];
        //trust that the individual images are in the array
    }
}

```

# Answer
> 2 votes
Your flag should be an indication of whether to *start* the animation, not whether to continue playing it. e.g.

```
if (IsKeyDown() && !pressed && !animation.IsPlaying())
{
  // record that we triggered the animation
  pressed = true;

  // start playing the animation
  animation.Start();
}
else if (!IsKeyDown())
{
  // we reset our pressed state since the user let go of the key
  pressed = false;
}

// play animation
if (animation.IsPlaying())
  animation.Update();

```

You can make this more generic by having functions like `IsKeyPressed` in addition to `IsKeyDown`, with the difference being that `IsKeyPressed` only returns `true` on the frame that the user pressed the key and returns `false` on all subsequent frames until the user releases the key and presses it again.

This can be generalized to:

```
// all keys starts out not being pressed
lastKeyState = false;
currentKeyState = false;

// at the beginning of your game loop, remember the state from the last frame, then query the new state
lastKeyState = currentKeyState;
currentKeyState = IsKeydown();

// now compare the two states to determine if the key was pressed this frame or released this frame
pressed = currentKeyState && !lastKeyState;
released = !currentKeyState && lastKeyState;

```

# Answer
> 0 votes
Well this is the way I did it (May not be the best solution): Requires two booleans, a and b. If the key is down, and a is false, then start the animation, and set a to true. Then, if the key isn't down, set a to false. That way the animation will cycle through once per click of the key. Depending on what engine you're using, you may have to do something to stop the animation from automatically repeating itself(usually something like animation.setLooping(false), or an if statement checking to see if it's on it's last frame, and stopping it)

Hope this was helpful, if not, I apologize.

---
Tags: java
---


# Question
Title: Unity 3d auto-move player forward script
Trying to write a basic script to attach to the player on Unity 3D, I want them to move forward automatically. I'm guessing that will be part of the Update function and using transform, but that's about as far as I get.

I'm assuming it's a Transform.translate function too, but not sure what parameters to use to move forward 1 m/s automatically (for example). Also, how do I block W and S keys moving forwards and backwards, and instead use the for up and down? (My character is 'floating' and I'm looking to incorporate space harrier style controls)

Thank you!

# Answer
The first sample code is what you want. http://unity3d.com/support/documentation/ScriptReference/Transform.Translate.html

```
function Update()
{
    transform.Translate(Vector3.forward * Input.GetAxis("Vertical") * Time.deltaTime);
}

```

Vector3.forward is the same as (0,0,1), and transform.Translate() is local translate, so Translate(0,0,1) is always moving forward. Time.deltaTime let speed equal to 1 m/s.

And you can change the default key in "Input Manager" http://unity3d.com/support/documentation/Components/class-InputManager.html
> 3 votes

# Answer
You should be using a Character Controller and use either SimpleMove or Move.
> 0 votes

# Answer
this is C# version

```
public float speed=1f;

void Update()
{
    transform.Translate(Vector3.forward * Input.GetAxis("Vertical") * Time.deltaTime*speed);
}

```

you will have a field in inspector to change speed when you add the script to a gameobject. :-)
> 0 votes

---
Tags: unity
---


title: Blender support for Android

text:
# Question
Title: Blender support for Android
I want to design 3D games for my android smart phone. Though I that two powerful game development software like Blender (under Linux) supports 3D game development. My question is:

How can a game developed under Blender can be exported to Android devices?

# Answer
> 2 votes
Blender and it's game engine don't directly support android.

Third party apps like Unity can import model and animation data created in blender, possible export to other formats may be required.

A more low level approach is gamekit. You can also code a game from scratch like any android app and have it read data from a blend file or other exported file format.

---
Tags: blender-game-engine
---


title: OpenTK GL.DrawElements is never called

text:
# Question
Title: OpenTK GL.DrawElements is never called
I found this C++ code here. It draws simple rectangle. Works great.

```
#define GLEW_STATIC

#include <iostream>
#include <glew.h>
#include <freeglut.h>

const GLchar* vertexSource =
"#version 150 core\n"
"in vec2 position;"
"in vec3 color;"
"out vec3 Color;"
"void main() {"
"   Color = color;"
"   gl_Position = vec4(position, 0.0, 1.0);"
"}";
const GLchar* fragmentSource =
"#version 150 core\n"
"in vec3 Color;"
"out vec4 outColor;"
"void main() {"
"   outColor = vec4(Color, 1.0);"
"}";

void Display()
{
    glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
    glClear(GL_COLOR_BUFFER_BIT);

    glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);

    glFlush();

    glutSwapBuffers();
}

int main(int argc, char** argv)
{
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_MULTISAMPLE);
    glutInitWindowSize(800, 600);
    glutInitContextVersion(4, 4);
    glutInitContextProfile(GLUT_CORE_PROFILE);
    glutCreateWindow("OpenGL");
    glewExperimental = GL_TRUE;

    if (GLEW_OK != glewInit())
        exit(1);

    GLuint vao;
    glGenVertexArrays(1, &vao);
    glBindVertexArray(vao);

    GLuint vbo;
    glGenBuffers(1, &vbo);

    GLfloat vertices[] = {
        -0.5f, 0.5f, 1.0f, 0.0f, 0.0f, // Top-left
        0.5f, 0.5f, 0.0f, 1.0f, 0.0f, // Top-right
        0.5f, -0.5f, 0.0f, 0.0f, 1.0f, // Bottom-right
        -0.5f, -0.5f, 1.0f, 1.0f, 1.0f  // Bottom-left
    };

    glBindBuffer(GL_ARRAY_BUFFER, vbo);
    glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);

    GLuint ebo;
    glGenBuffers(1, &ebo);

    GLuint elements[] = {
        0, 1, 2,
        2, 3, 0
    };

    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(elements), elements, GL_STATIC_DRAW);

    GLuint vertexShader = glCreateShader(GL_VERTEX_SHADER);
    glShaderSource(vertexShader, 1, &vertexSource, NULL);
    glCompileShader(vertexShader);

    GLuint fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
    glShaderSource(fragmentShader, 1, &fragmentSource, NULL);
    glCompileShader(fragmentShader);

    GLuint shaderProgram = glCreateProgram();
    glAttachShader(shaderProgram, vertexShader);
    glAttachShader(shaderProgram, fragmentShader);
    glBindFragDataLocation(shaderProgram, 0, "outColor");
    glLinkProgram(shaderProgram);
    glUseProgram(shaderProgram);

    GLint posAttrib = glGetAttribLocation(shaderProgram, "position");
    glEnableVertexAttribArray(posAttrib);
    glVertexAttribPointer(posAttrib, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(GLfloat), 0);

    GLint colAttrib = glGetAttribLocation(shaderProgram, "color");
    glEnableVertexAttribArray(colAttrib);
    glVertexAttribPointer(colAttrib, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(GLfloat), (void*)(2 * sizeof(GLfloat)));

    glutDisplayFunc(Display);
    glutMainLoop();

    glDeleteProgram(shaderProgram);
    glDeleteShader(fragmentShader);
    glDeleteShader(vertexShader);

    glDeleteBuffers(1, &ebo);
    glDeleteBuffers(1, &vbo);

    glDeleteVertexArrays(1, &vao);
}

```

So I decided to rewrite it on C# with OpenTK framework:

```
using OpenTK;
using OpenTK.Graphics.OpenGL;
using System;
using System.IO;

namespace OpenTKTest
{
    public class Game : GameWindow
    {
        private Int32 vao;
        private Int32 vbo;
        private Int32 ebo;
        private Int32 vertexShader;
        private Int32 fragmentShader;
        private Int32 shaderProgram;

        public Game() : base()
        {
        }

        [STAThread]
        public static void Main()
        {
            var window = new Game();
            window.Run(120, 120);
            window.Dispose();
        }

        protected override void OnLoad(EventArgs e)
        {
            GL.GenVertexArrays(1, out vao);
            GL.BindVertexArray(vao);

            GL.GenBuffers(1, out vbo);
            var vertices = new Single[]
            {
                -0.5f,  0.5f, 1.0f, 0.0f, 0.0f, // Top-left
                 0.5f,  0.5f, 0.0f, 1.0f, 0.0f, // Top-right
                 0.5f, -0.5f, 0.0f, 0.0f, 1.0f, // Bottom-right
                -0.5f, -0.5f, 1.0f, 1.0f, 1.0f  // Bottom-left
            };
            GL.BindBuffer(BufferTarget.ArrayBuffer, vbo);
            GL.BufferData(BufferTarget.ArrayBuffer, new IntPtr(sizeof(Single) * vertices.Length), vertices, BufferUsageHint.StaticDraw);

            GL.GenBuffers(1, out ebo);
            var elements = new Single[]
            {
                0, 1, 2,
                2, 3, 0
            };
            GL.BindBuffer(BufferTarget.ElementArrayBuffer, ebo);
            GL.BufferData(BufferTarget.ElementArrayBuffer, new IntPtr(sizeof(UInt32) * elements.Length), elements, BufferUsageHint.StaticDraw);

            vertexShader = GL.CreateShader(ShaderType.VertexShader);
            GL.ShaderSource(vertexShader, File.ReadAllText("vs.glsl"));
            GL.CompileShader(vertexShader);
            Console.WriteLine(GL.GetShaderInfoLog(vertexShader));

            fragmentShader = GL.CreateShader(ShaderType.FragmentShader);
            GL.ShaderSource(fragmentShader, File.ReadAllText("fs.glsl"));
            GL.CompileShader(fragmentShader);
            Console.WriteLine(GL.GetShaderInfoLog(fragmentShader));

            shaderProgram = GL.CreateProgram();

            GL.AttachShader(shaderProgram, vertexShader);
            GL.AttachShader(shaderProgram, fragmentShader);
            GL.BindFragDataLocation(shaderProgram, 0, "outColor");
            GL.LinkProgram(shaderProgram);
            GL.UseProgram(shaderProgram);

            var posAttrib = GL.GetAttribLocation(shaderProgram, "position");
            GL.EnableVertexAttribArray(posAttrib);
            GL.VertexAttribPointer(posAttrib, 2, VertexAttribPointerType.Float, false, 5 * sizeof(Single), IntPtr.Zero);

            var colAttrib = GL.GetAttribLocation(shaderProgram, "color");
            GL.EnableVertexAttribArray(colAttrib);
            GL.VertexAttribPointer(colAttrib, 3, VertexAttribPointerType.Float, false, 5 * sizeof(Single), new IntPtr(2 * sizeof(Single)));

            GL.Viewport(0, 0, Width, Height);
        }

        protected override void OnRenderFrame(FrameEventArgs e)
        {
            GL.ClearColor(0.0f, 0.0f, 0.0f, 1.0f);
            GL.Clear(ClearBufferMask.ColorBufferBit);
            GL.DrawElements(PrimitiveType.Triangles, 6, DrawElementsType.UnsignedInt, IntPtr.Zero);
            GL.Flush();
            SwapBuffers();
        }

        protected override void OnClosing(System.ComponentModel.CancelEventArgs e)
        {
            GL.DeleteProgram(shaderProgram);
            GL.DeleteShader(fragmentShader);
            GL.DeleteShader(vertexShader);

            GL.DeleteBuffers(1, ref ebo);
            GL.DeleteBuffers(1, ref vbo);

            GL.DeleteVertexArrays(1, ref vao);
        }
    }
}

```

Vertex shader:

```
#version 150 core
in vec2 position;
in vec3 color;
out vec3 Color;
void main()
{
    Color = color;
    gl_Position = vec4(position, 0.0, 1.0);
}

```

Fragment shader:

```
#version 150 core
in vec3 Color;
out vec4 outColor;
void main()
{
    outColor = vec4(Color, 1.0);
}

```

Both sources are almost identical. But in C# version `GL.DrawElements` function is never called (I found it out while debugging with gDEBugger from gremedy). Why this code doesn't work in OpenTK?

# Answer
There are two issues in the C# version, compared to the C++ version. When fixed, the project runs as expected.

1. The C++ version is using `glutInitContextProfile(GLUT_CORE_PROFILE);` while the C# version is not. You can fix that by changing the Game constructor to:

```
public Game()
    : base(800, 600, GraphicsMode.Default, "Example",
        GameWindowFlags.Default, DisplayDevice.Default,
        4, 4, GraphicsContextFlags.ForwardCompatible)
{
}

```

Without this, the project will not run correctly on drivers that do not implement ARB\_compatibility (Mac OS X and Linux/Mesa.)

2. The elements array should be `int[]`, not `Single[]`. Change the declaration to:

```
var elements = new int[]
    {
        0, 1, 2,
        2, 3, 0
    };

```

The project now runs correctly on my system (Mac OS X with Intel HD4000 & GL4.1).
> 1 votes

---
Tags: opengl, glsl, opentk
---


title: Constant buffer not updating

text:
# Question
Title: Constant buffer not updating
I'm trying to rotate models independently of each other however I cannot for the life of my figure out how. I have gotten to the stage of writing this:

```
std::vector<int>::size_type st = Models.size();
if (!Models.empty())
{
    for (unsigned x = 0; x < st; x++)
    {
        D3DXMATRIX matRotate;

        D3DXMatrixRotationY(&matRotate, D3DXToRadian((x + 1) * 60));

        cBuffer[x].Final = matRotate * matView * matProjection;
        cBuffer[x].Rotation = matRotate;

        devcon->UpdateSubresource(pCBuffer, 0, NULL, &cBuffer[x], 0, 0);

        devcon->VSSetShader(pVS, 0, 0);
        devcon->VSSetConstantBuffers(0, 1, &pCBuffer);
        devcon->PSSetShader(pPS, 0, 0);

        Models.at(x)->Render(devcon);
    }
}
swapchain->Present(0, 0);

```

but this only updates for the first assignment of rotation. Why isn't it rotating and how do I make it? Thanks in advance.

# Answer
> 1 votes
Your rotation will clearly always be the same every frame. The code you wrote there just sets the rotation to one single value every frame, if this code is run every frame, that is. Instead, have a variable , say `rotation_offset` that will be updated each frame, and will have a scope outside this for loop you have there. You should do something like this:

\`

```
//somewhere out side that function
float rotation_offset = 0;

/*...*/

//right before the code you posted
rotation_offset += 0.01f;  //the amount to increase rotation each frame

std::vector<int>::size_type st = Models.size();
if (!Models.empty())
{
    for (unsigned x = 0; x < st; x++)
    {
        /* ... */
        D3DXMatrixRotationY(&matRotate, D3DXToRadian((x + rotation_offset) * 60));
        /* ... */
    }
    /*...*/
}

```

\`

And that should make things keep rotating.

---
Tags: c++, directx, directx11
---


# Question
Title: Originating direction of shots in an FPS problem
Recently I have been asked on the interview about a maybe simple task to solve a problem.

We have a player, that looks in some direction, and a shooter, who already is shooting the player. I must find out whether the shots come from the left or right in the same way Counter Strike does when you get hit: the game shows from which direction and it looks like a red half-circle.

I know the vectors of players and enemies position. I tried different answers f.e. to build a line from the player see's and solve a linear system equation or rotate the player vector and then find out the angle of scalar product, but he says there's a better way to do it. I don't need the answer to this particular question, but a 'way' to find out the answer. F.e. any books related to this problems, some similar problems, etc.

# Answer
The answer to this problem: Get the dot product of the player's left direction with the direction from the player to the shooter. That'll be positive if the shooter is to the player's left, or negative if the shooter is to the player's right.

In general, learn about useful linear algebra operations like dot and cross product. Start here http://blog.wolfire.com/2009/07/linear-algebra-for-game-developers-part-2/
> 1 votes

---
Tags: game-mechanics, first-person-shooter
---


title: How to edit colliders in Unity2D

text:
# Question
Title: How to edit colliders in Unity2D
I can edit colliders by holding down the shift key. But when i add a second collider, the shift key always selects the first one. And there is no "Edit Collider" button in the editor (Win/4.5.4f1). I'm testing it with two EdgeColliders2D.

# Answer
> 3 votes
In Unity 4.6 there's a dedicated button in Inspector labeled "Edit Collider" that you could use to edit the collider.

# Answer
> -2 votes
One GameObject can only have one BoxCollider, just choose GameObject you want edit and modify your box collider

---
Tags: unity, editors
---


# Question
Title: Move camera from wherever camera is to pinned point
So, I need to switch/ move/ animate camera from point X (not point A,as I don't know where the camera is at that momemnt) to point B (place where you want your camera to move).

This is for cinematics...like when you press a button in game which does something (opens doors maybe) but you can't see where nor what did you activate, so you show the player with the camera where and what happened.

1. I tried to animate camera to position, camera just goes crazy.
2. Then I tried to make an empty object placed at the position where the camera should be and move camera with code to that objects position.
3. I tried enabling Camera 2 and disabeling Camera 1 but it just doesn't work.

Enable/ Disable Code:

```
public var door: DoorAnim;

public var triggered : boolean = false;

function OnTriggerEnter() { triggered= true; }
function OnTriggerExit()  { triggered= false;}

function Update(){
    if (triggered && Input.GetKeyDown(KeyCode.JoystickButton1)){
            Debug.Log("Door 1 built");
            camera1 = GameObject.Find("Camera1");
            camera1.enable = false;
            camera2 = GameObject.Find("Camera2");
            camera2.enable = true;
            door= GameObject.Find("door1");
            door.animation.Play();

    }

```

# Answer
> 0 votes
In the approach you want to follow that is disabling other camera use GameObject.SetActive.

---
Tags: unity, javascript, camera
---


# Question
Title: if statement is executed even when condition is false
I've made some code that is triggered when the player is in range of the enemy. Everything was working fine until I tried to implement a condition when the countdown reached zero. I made a method (PlayerHit) that returns true if the player's melee skill is greater than a random range between 1 and 10 and false if not. I only want the enemy's health to be subtracted in the AdustCurrentBeastHealth method if the PlayerHit method is true. The problem is, the health is subtracted whether the health is true or false and I cannot understand where I went wrong. I have attached the script below.

```
private void AttackEnemy()
{
    //other code....

    if (playerCharacter.PlayerHit() == true)
    {
        Debug.Log (PlayerHit());
        enemyVitals.AdjustCurrentBeastHealth(-damage);
        attackTimer = Random.Range(1,6);
        attackCoolDown = attackTimer;
    }
    else
    {
        enemyVitals.AdjustCurrentBeastHealth(0);
        attackTimer = Random.Range(1,6);
        attackCoolDown = attackTimer;
    }
}

public bool PlayerHit()
{
    if(meleeSkill > Random.Range(1,10))
    {
        //Debug.Log(hitChance + "From block skill > hitChance condition");
        return true;
    }
    else
    {
        //Debug.Log(hitChance + "From else condition");
        return false;
    }
}

```

# Answer
```
        if (playerCharacter.PlayerHit() == true)
        {
            Debug.Log (PlayerHit());

```

This code does not do what you think. It gets a new value when it does the Debug.Log, because the randomizer is called again.

You want

```
        value = playerCharacter.PlayerHit();
        if (value)
        {
            Debug.Log (value);

```
> 1 votes

---
Tags: unity
---


# Question
Title: Unity Guitext object always triggering a collision - 2D
I have a guitext object which I can drag. I have attached a 2d rigid body. I have also attached the collider with the following code:

```
void setCollider()
    {
        Rect box = this.guiText.GetScreenRect ();
        BoxCollider2D boxCollider = (BoxCollider2D) gameObject.AddComponent (typeof (BoxCollider2D));
        var boxX = box.width;
        var boxY = box.height;
        Debug.Log ("boxX = " + boxX + "boxY = " + boxY);
        boxCollider.size = new Vector2(boxX, boxY);
    }

```

I have a sprite with a collider set as trigger. However, it triggers as soon as the game starts and is not anywhere near the trigger sprite. It will only trigger the one time when it starts. My Trigger on my sprite is as follows:

```
void OnTriggerEnter2D (Collider2D other){
        Debug.Log ("Order Right Arm");
        Debug.Log (other.bounds);
    }

```

EDIT: based on answer I have changed the size of the collider to account for the pixel/unit difference:

```
void setCollider()
    {
        float pixelRatio = (Camera.main.orthographicSize * 2) / Camera.main.pixelHeight;
        Debug.Log ("Pixel Ratio "+pixelRatio);
        Rect box = this.guiText.GetScreenRect ();
        BoxCollider2D boxCollider = (BoxCollider2D) gameObject.AddComponent (typeof (BoxCollider2D));
        float boxX = box.width * pixelRatio;
        float boxY = box.height * pixelRatio;
        Debug.Log ("boxX = " + boxX + "boxY = " + boxY);
        boxCollider.size = new Vector2(boxX, boxY);
    }

```

Any ideas on how I can get this to trigger only when I drag the guitext over the sprite?

# Answer
> 1 votes
The problem is with you using `Rect box = this.guiText.GetScreenRect ();` it returns size in pixels you need to convert it into unity3d units.

---
Tags: unity, collision-detection
---


# Question
Title: Why can't I reference a sprite loading variable in a separate class?
When I reference a sprite I declared in a separate class that I am using to load images and rectangles, I get an error.

Here's how I reference the image in the `render` method:

```
loading.playerSprite.draw(batch);
loading.wallSprite.draw(batch);

```

Here's where the variable is declared:

```
public Sprite wallSprite;
public Rectangle playerRect, wallRect;
public Sprite playerSprite;

public void player() {
    playerSprite = new Sprite(new Texture("img/player.png"));

    playerRect = new Rectangle(playerSprite.getX(), playerSprite.getY(),
            playerSprite.getWidth(), playerSprite.getHeight());
}

public void Wall() {
    wallSprite = new Sprite(new Texture("img/wall.png"));

    wallRect = new Rectangle(wallSprite.getX(), wallSprite.getY(),
            wallSprite.getWidth(), wallSprite.getHeight());
}

```

Here's the error:

```
Exception in thread "LWJGL Application" java.lang.NullPointerException
    at com.mediocre.game.Screen.PlayScreen.render(PlayScreen.java:33)
    at com.badlogic.gdx.Game.render(Game.java:46)
    at com.badlogic.gdx.backends.lwjgl.LwjglApplication.mainLoop(LwjglApplication.java:206)
    at com.badlogic.gdx.backends.lwjgl.LwjglApplication$1.run(LwjglApplication.java:114)

```

Its weird that this is failing, because it worked previously, but my hard drive corrupted and I cant remember how I did it before...

# Answer
You created the voids to instantiate the sprites from separate class but you forgot to call them before the `render()` method. Insert `separateClass.player()` and `separateClass.Wall()` in the `show()` method and it should work.

ps : Do not forget to first start your *separateClass* (`separateClass sClass = new separateClass(parameters)`)
> 0 votes

---
Tags: libgdx, architecture
---


# Question
Title: How do you determine the amount of moves/turns/lives that should be given to a player?
Let's take Candy Crush for example. The player is given 50 turns to complete a certain level.

How is such number determined? Are there educated ways to reach such numbers?

I also presume that these numbers are refined through game updates, but there must be a reasonable starting point to keep the player interested enough without making it extremely difficult or too easy.

Note: I'm only using Candy Crush as an example. I'm looking for general answers to this issue.

# Answer
If a game is relying on *static* values such as fixed player/enemy stats, allowed moves or frequency and effect of power-ups, those are usually refined through extensive beta / play testing until a good balance is found (those values might be adjusted for different difficulty levels within a game).

One thing to take into account when defining "good" starting values for a game is that the developers itself have a superior understanding of the game and its mechanics. This advantage needs to be considered when setting values for the average gamer to prevent frustration.

As opposed to static approaches, there however is also a growing research interest in figuring out approaches to *dynamically* react to the player capabilities and the game progress to always keep the game challenging without building up frustration for the player due to constants failures. The common terms for that field are "Dynamic Difficulty Adjustment" (DDA) or "Dynamic Game Balancing" (DGB). The respective Wikipedia entry gives a broad overview regrading some approaches and games utilizing such approaches.

Additionally, some research papers that might be helpful in that regard:

* Paper: "A Temporal Data-Driven Player Model for Dynamic Difficulty Adjustment" from Georgia Tech University
* Paper: "Game Challenges and Difficulty Levels: Lessons Learned From RPG" from National University of Singapore
* Paper "AI for Dynamic Difficulty Adjustment in Games" from Northwestern University
> 3 votes

# Answer
I'm a big believer in simplicity.

If you're trying to determine a starting value or even a max value of something like player lives, turns and so forth. Then this is where statistics and research come into play. Simply testing the game with players, analyzing the results and comparing it to similar games can help you find the sweet spot for anything.

There is no need to dive into the psychology of the human mind to find out how many lives players should have. You should, like statistics, let the data speak for itself and tell you that sweet spot for any given mechanic or system.

For example with unlimited turns: 80% of players completed this puzzle in 10 turns or less on the first time of playing the game.

With that piece of information, I have a pretty good idea of the turn value for that particular puzzle for first time players. Everything else falls into place and adjustments can be added later based on the actual players and not some research paper.
> 1 votes

---
Tags: game-design, game-mechanics, user-experience
---


# Question
Title: How are flow fields different from potential fields?
I've heard of of both flow fields and potential fields for pathfinding in games. They sound similar, but I never see them mentioned in the same contexts. Places that mention one never mention the other, as if they're completely unrelated.

How are they different? Why would I choose one over the other?

# Answer
A potential field is a type of **scalar field**. In contrast, a flow field is a **vector field**. These are essentially just multidimensional arrays that are used as low level data structures for various pathfinding designs; there really is no "standard" algorithm equivalent to the ubiquity of A\* for point-to-point pathfinding.

Typically, a potential field maps the "desirability" of a particular location on the terrain for AI entities (henceforth I will call them *agents*). They will try to travel in whichever direction will cause the greatest increase in potential. Hence, if you think of the potential as a height, they're playing a game of *king of the hill*. Once agents reach a local maximum, they stop moving. This can be a problem depending on how the field is generated, because agents can get stuck in corners and dead-ends.

One ingenious method of getting around this problem with potential fields is to allow the field to be modified in real-time. This is known as **collaborative diffusion**. In this system, "potential" acts somewhat like molasses or lava; it *diffuses* slowly toward any adjacent location with less potential. The target becomes a producer of potential, as if a mountain were constantly springing up beneath its feet. Agents become consumers of potential, simultaneously moving towards locations with greater potential, and reducing the amount of potential on their current location. In addition to solving the problem of local maxima, this means multiple agents will tend to move away from each other, taking different paths towards the target, and thus appearing to *collaborate*. Additionally, potential may naturally decay over time to prioritize the current and recent locations of the target over older locations.

For flow fields, I'll assume you're talking about a system similar to **this one**. In this system, you have two scalar fields and a vector field. You start out with a scalar *travel cost* field, which is integrated to find the total cost to travel from any starting location to the target location. Essentially, this integration field is a potential field, but instead of seeking higher potentials, agents seek lower potentials, and thanks to the integration that generates it, the potential field is well behaved: agents won't get stuck in a local minimum because there is only one minimum (the target location). Finally, a vector field is created by taking the **gradient** of the potential field (essentially the local derivative at each point in the field). This type of system can be thought of as an answer to the question "What direction would Dijkstra's algorithm (or A\*, or any other algorithm that guarantees minimum path length) initially direct me to reach a specific target from every other location on the map?"

**TL;DR** A flow field is usually just the gradient of a potential field. If the number of agents in the simulation is significantly smaller than the number of locations in the field, then a potential field is probably better, because it uses less memory (a vector is larger than a scalar). On the other hand, if you have tons and tons of agents, you might be recalculating the same partial derivatives over and over for each agent, and caching them in a flow field might be beneficial.
> 10 votes

---
Tags: path-finding
---


# Question
Title: Random generation of interesting puzzle levels?
I'm making a Sokoban-like game i.e. there's a grid that has some crates on it you can push and you have to get the crates on crosses to win the level (although I'm going to add some extra elements to it). Are there any general algorithms or reading material I can look at for how I could go about generating interesting (as in, not trivial to solve) levels for this style of game? I'm aware that random level generators exist for Sokoban but I'm having trouble finding the algorithm descriptions.

I'm interested in making a game where the machine can generate lots of levels for me, sorted by difficulty. I'm even willing to constrain the rules of the game to make the level generation easier (e.g. I'll probably limit the grid size to about 7x7). I suspect there are some general ways to do level generation here as I've seen e.g. Traffic Jam-like games (where you have to move blocks around the free some block) with 1000s of levels where each one has a unique solution.

One idea I had was to generate a random map in its final state (i.e. where all crates are on top of their crosses) and then the computer would pull (instead of push) these crates around to create a level. The nice property here is that we know the level is solvable. However, I'd need some heuristics to ensure the level was interesting.

# Answer
> 6 votes
See the paper: Automatic making of Sokoban problems

From the abstract:

> This paper describes our program that makes Sokoban problems automatically. Sokoban is one of one-person puzzles invented in Japan. The program consists of three stages: generation, checking and evaluation. First, candidates for problems are generated randomly by a prototype and three templates . Second, unsolvable candidates are removed by the Sokoban solver. Finally trivial or uninteresting candidates are removed by the evaluator. The problems that the program made are judged good by human experts. Creation of art by computer is an important target of Artificial Intelligence. Our work can be characterized one of the attempts to create some arts by computers.

# Answer
> 2 votes
For solvable puzzles, it's often easy to just play the game in reverse, starting from a solved state and un-making moves either planned or at random (or in an editor.)

Sokoban fits this approach very well, and will be much easier to implement than an exclude-and-solve strategy.

---
Tags: game-design, level-design, random, puzzle, procedural
---


# Question
Title: Should an NPC shop provide a unique or shared inventory for each player?
I am working on a browser-based text game. I have implemented NPC shops where the players can buy items in exchange for coins.

Currently, the inventory of the NPC shop is shared among all players. For example, if I sell the shop a Sword, any other player can go to the shop and buy that Sword. This also means if I purchase an item before one of my fellow players, it is no longer available for them. Shop stock is randomly regenerated from a database of possible items and quantities periodically.

I see two options: A shared NPC inventory, or private instances of the NPCs inventory.

**What considerations should I have, as far as user experience and the virtual economy, when trying to determine which option to go with?**

# Answer
Both methods definitely result in large gameplay variations, so it depends what you're looking for. Here are some thoughts, based on common implementations:

**Shared**

* Basic necessities should be accessible to everyone. If the shops can be bought out by other players, then there should be an alternate means of acquiring the items (such as crafting). Otherwise you end up with a situation where a rich player buys up everything to hinder the progress of new players.
* You're going to end up with people sitting around shops, waiting for the refresh. They won't have as much fun (arguably) as the people out exploring, and the people exploring are going to return to empty shops.
* Inflation of the virtual currency as time goes on is inevitable. If the shop pricing isn't player controller, then quickly enough you will stop seeing any items of value getting sold to the shops, because the price paid is too low (unless you price adjust regularly...).

**Private**

* Certain items will become commoditized very quickly; you don't have control over how many of a certain item exist in the world, and thus don't have any control over their economic value.
* Decreases the sense of a "connected" world.
* Anything sold through shops won't be rare, and thus will be of lesser "status".

Here are some ideas to make things interesting:

* **What if the stores were shared, but the shop keepers had limited money?** They would make more money by selling, lose by buying. They wouldn't need to restock either, everything would be supplied to them by players (from monster drops/crafting). It would keep the store inventory more "balanced", and you could keep the economy from blowing up. Plus, going to the store would always be a new experience. You would only find rare items at high-class stores, because they would be the only ones to afford them.
* Have a fusion. Basic items, like iron swords, sticks, and so on, would be private instances. But the stores would also have shared items; items sold to them by players. You still run into commoditization issues, but circumvent the problem of rich players hogging everything.
* Tried-and-true: private instances for basic shops, plus an auction house for shared items.

I'd personally love to try a \[multiplayer\] game where shopkeepers had limited money; it's not something I've seen before, and I think it would create a really unique kind of game and economy.

As a final note, there are plenty of studies on virtual economies, especially for massively popular games such as World of Warcraft, EVE Online, and Second Life. But I think for this question, RuneScape makes for an excellent case study. This Wiki page has some information on the store system, and how it has change over the years, as well as what the implications were.
> 3 votes

# Answer
All the MUDs I played had the shared shop, infinite money model.

In best one the price was a function of supply, thus selling the first 'rabbit foot' got 250 while the tenth might only get 15. The purchase price was a function of supply also. Thus buy the only 'rabbit foot' cost 400. Also the shop had generation/consumption rates for each item.

The "awesome" items where custom items not limited stock, so in effect you provide input beside money.

Now the mud was still affected by dumping of gear, but higher levels tended to get different dropped gear than the lower levels so there was less cross over.

Which ever model you chose, there is a immersion breaking issues with:

* a shop have infinite money
* a shop accepting the 100th item
* a shop selling unlimited items
* a shop buying stuff no player/npc needs

which means you have to ask what purpose is the shop serving, a in-out supply shop so more "gaming" can happen? or is trading a large part of the game? or just a money sink?
> 2 votes

# Answer
I feel the other answers make too many assumptions outside the scope provided. I think that shared has these pro and con considerations.

Furthermore, I think the restocking option should be revisited on the purpose no matter what option is chosen. Restocking, unless for more realistic impact on the game world, doesn't make any sense if there is a delay. I think a reason on why there is a restock should be clarified more in the underlying mechanics.

**Shared**

*Pros*

* More realistic system that could be attractable to players.
* Ability to lock the market, where you can buy everything and resell for higher.
* Ability to prevent others from buying certain items such as a warfare tactic.

*Cons*

* Players can troll other players by buying everything in the shop until it's restocked.
* Players could get frustrated in the buying process if they are to slow to purchase before someone else snags the item.
* Restocking times can conflict with players play times, especially in diverse time zones.

**Private**

*Pros*

* Potentially unlimited and exclusive supply could devalue immersion to the player.
* No one person controlling the entire market.
* No one person denying you access to items in the shop.

*Cons*

* Could devalue immersion for those who want more realism in the shop system.
* Limited ability to lock the entire market and resell for higher.
* No ability to deny others access to items in the shop

**Explanations**

*Locking Down The Market*

EVE Online is a player driven economy. Buying low and selling high is a trader tactic that is common in the game. Regardless of who you are buying from, NPC or not, the tactic is very attractable to players.

Likewise, buying all items or useful items from a station is considered a warefare trade tactic. This is to prevent your enemies from getting much needed supplies to fight you or escape. Like the previous example, this is a tactic that is very attractable to players regardless if the seller is an NPC or not.

I feel that this being a negative is entirely subjective.

*Market Control*

Having control of the market may be attractable for players who want to trade. Although it may be bad for the economy, a bad economy may be a good scenario for the game. I know that sounds bad, but trading in most games is widely popular. Simulating trade, both good and bad trade can be good for the gameplay experience.

For example, a game that include both bubbles and when they burst. Surviving a great depression and more could be both rewarding and challenging for traders, while also destroying the economy. The act of destroying and repairing could be fun for players.

*More Realistic*

Buying out items and restocking can be looked at as being realistic or a sign of realism in the game. Some players really enjoy these types of designs. Restocking for one good example could include a trade merchant that physically arrives at the shop and restocks it. This opens up additional gameplay experiences for players who may want to hijack the shipment before it even arrives. Likewise, players who want to protect it.
> 2 votes

---
Tags: user-experience, economy
---


title: How to determine an "Assists" statistic

text:
# Question
Title: How to determine an "Assists" statistic
My game is a top-down multiplayer shooter where you control a space pod with 4 different weapons that do varying damage. We have all the usual stats like Kills, Deaths, and Damage Inflicted/Taken, etc. However, the one stat we have had trouble with is an Assists statistic, mainly because we can't seem to determine what should constitute an assist.

In our game, the player spawns with 224 points of health (ya random number I know), and each weapon they are hit with will take a different amount of health away (anywhere from 11-224). If the player kills another player, they recoup any lost health by 40 points.

When a player only has 40 points of health left, their pod starts to smoke to signify their low health.

Players constantly complain of being "vulched", where they will inflict 223 damage on a player, only for someone else to get the last shot and get credit for the kill.

Given this information, how would you determine when a player gets an Assist?

# Answer
To prevent players from acting like vultures, you might want to think about having the person who does the most damage being credited with the kill. Though this approach would most likely not work in a FFA environment. Granted you're talking about assists, so I'd imagine this is some semblance of a team game. Another thing I just thought of that would probably increase the cohesiveness of the team is completely eliminating the individual kill counter, and only displaying an overall team kill count. Suddenly the goal shifts from being I have to be the last one to hit this, or I have to snipe this kill, to I have to kill him and I'm glad this guy is helping me secure the kill for the team. If you implemented this approach, you could track an individual stat like damage done which is completely representative of your contribution to the team instead of only representing how good you are at getting the last hit.

Edit to further address your question:

Something you might want to keep in mind for calculating assists are metrics other than pure damage. For instance, say two pods are trading fire. If the two fire at equivalent rates, the result is dependent on who started shooting first/who is the most accurate. Assuming all factors are equal, add a healer into the mix. Now the player being healed with come out on top barring intervention by others. In my mind, the player doing the healing should get an assist. without him, the player doesn't get the kill. Other ideas to keep in mind are debuffs applied to the enemy and other buffs applied to the killer.
> 7 votes

# Answer
I'd start with something simple. All players who do some minimum threshold of damage to a player who is then killed before that player kills someone else gets an assist. Then extend it from there if testing proves it to be problematic (i.e. if you die before the other player does, you lose the assist).
> 4 votes

# Answer
This is a bit tricky, as it's possible that someone is damaged in a long timespan and when someone finally gets to whack them, they'll be really disapointed if they don't get awarded for it.

To solve this, I would try something like this;

* Each time someone gets hit, track who made the damage and how much.
* In case of kill, give awards based on damage collected.
* Add cooldown to the tracked values; say, if the damage is 60 seconds old, it doesn't count at all.

Whether you want to award everyone who has doled damage that is still valid, or only the killer and whoever has doled most damage (or second most) is up to you.
> 3 votes

# Answer
I took the same basic approach to this in Savage 2 and Heroes of Newerth, it's a flexible system that allows you tweak the specific rules easily.

Each entity has a collection of records that store an attacker id, point value and time stamp. At this point you might also trim the damage log of any records that are too old to count as an assist, if you set a threshold for that. If there aren't too many records being generated, you could also just wait for the entity to die. When it dies, Step through the damage log and get the total damage recorded as well as the total damage belonging to each attacker id. Now you can either award assists at a fixed threshold (i.e. 20 or more damage grants an assist) or as a percentage (20% or more of the total recent damage grants an assist). This system accounts for any changes in health like healing, or loss of health other than credited damage.

If you don't need the granularity of every single attack, you can simplify this by only storing a single record for each attack id and just accumulate their score with each update. What you lose is the ability to ignore credit given to them outside of the assist time threshold, if you wanted to have one.

You can also use this system to give credit for non-damage events. For instance, if one entity can apply a buff to another, each damage event can also record points for the buffer, either at some flat rate or as a percentage of the buffed entity's damage.
> 3 votes

# Answer
As near as I can tell, Tribes: Ascend has the following algorithm:

* The person who made the final hit gets the kill credit.
* If someone besides that person did the most damage, they get the assist credit.
> 2 votes

# Answer
Simplistic is key here.

I think you need to define assist at the core. If you think of basketball, asset refers to equal portions of the play until the end result (IMHO). That means, someone has the ball, they pass the ball and the ball is put into the hoop. If the play involves 2 people then both players are doing 50% of the work.

With that said, equal portions or 50% in my example means that assist is given to those who are closer to the equal portion.

For example, if a player does 223 points of health to another player, then that's pretty much 99% of the work. Although the second player kills, the one who did the most damage gets the credit. Options for the player who actually delivered the killing blow is credit with the assist.

In another example, if a player did 100 points of health to another player, then that's 44% of the work. When the second player kills, the one who did 44% is credited with the assist.

Therefore, a line has to be drawn in the sand. Something like 70% or more damage is credited to the kill even if they did not kill. That way if 5 people are attacking, all contributing to the kill below 70%, the last attack is always credited with the kill and all other contributors are credited with the assist.
> 0 votes

---
Tags: game-design, statistics
---


title: What does a C++ expert need to know?

text:
# Question
Title: What does a C++ expert need to know?
so the other day I was looking for jobs in the gaming industry (software engineer/game programmer/gameplay programmer, etc) just to get a look at what are some of the requirements. Most of these jobs require 5+ years of experience with C++, and to be an "expert" in this language. My question is, what does exactly an expert in C++ need to know, apart from pointers, STL, memory allocation, inheritance, polymorphism? Do you need to know the programming language from A to Z? Every bit of the language? Or what are some of the most important topics that you need to know in order to qualify as a "C++ expert"?

# Answer
> 2 votes
C++ is really a family of languages that are all in one compiler, so it's difficult to be truly a master of everything. There's a 'core' language which is a 'better C', there's an objected oriented langauge (i.e. classes, inheritance, virtuals, etc), the Standard Library (including but not limited to the STL), and a meta-programming template language. Add in the complexities of evolution from C++98 to C++11 to C++14 and it can be a bit daunting.

Personally, I'd suggest once you have the basics of C++ down, read the three Scott Meyer's books: *Effective C++*, *More Effective C++*, and *Effective STL*. Then read his blog for the notes on what he thinks is most important about C++11. I think his list is pretty good, but I wish he'd have mentioned `std::unique_ptr` which I've found to be extremely useful. You may also find the content in my article Dual-use Coding Techniques for Games useful even if you are not targeting Microsoft platforms in particular.

Being a really great coder in any language requires experience mostly learned 'on the job'. Looking at examples of code can also be a good way to learn it. You may want to dig into some existing code that has been well code reviewed by peers and generally judged to be 'good code' in terms of style. I've had lots of good feedback on DirectX Tool Kit, DirectXTex, and DirectXMesh which all make use of C++11 standards and have been though many peer reviews.

Of course, being an "expert in C++" doesn't mean much if you are not also proficient in whatever specific area of computer science or technology you are supposed to be addressing with your "expert C++" code. There's many well-known classic books in each field, so figure out which one is most relevant to your job search.

# Answer
> 0 votes
I think this is subjective and a way to highlight someone who has both the experience in the language and the experience in the chosen industry. In that example, someone with 5+ years using C++ and working in the game industry may imply they are an expert and should apply. Another assumption is that you meet the same qualifications in the example above, but have the self-confidence in yourself as being an expert in the language, but not a master.

But for me, it's more than just knowing the language. In my humble opinion, anyone can learn a language. It's more about the experience of working with said language in the desired industry the language is being applied.

Think of it like this. Even though you can read and write in your spoken language. It doesn't mean you are a professional writer or that it means you can write a best-selling novel. Expert implies that you know the language, have used the language in a professional capacity and that capacity includes the specific industry for the opportunity.

---
Tags: c++
---


# Question
Title: How can rotate a 2D textured quad in legacy OpenGL immediate mode?
I have a texture of a tank, and I want to it appearance on the screen depends on its current direction, so I decided to use rotating texture functions of OpenGL. I followed some advices through Google and received unsuccessful results. Anyone can help me with this problem?

This is my render() function:

```
#define UP 0
#define DOWN 1
#define LEFT 2
#define RIGHT 3

void GameObject::render()
{
    glBindTexture(GL_TEXTURE_2D, textureID);
    glLoadIdentity();
    glTranslatef((GLfloat)coord.getX(), (GLfloat)coord.getY(), 0.0f);
    glDrawArrays(GL_QUADS, 0, 4);
}

```

# Answer
> 3 votes
**`glRotatef(GLfloat angle, Glfloat x, GLfloat y, GLfloat z);`**

The Above function is what you need for your purpose. It " *multiplies the current matrix by a rotation matrix*", as the OpenGL documentation says. Here's how you use it-

`angle` is the angle you want to rotate. (Duh.) The next three parameters define the axis around which you would like to rotate. You input the x, y, and z components of the unit vector pointing in the direction of your desired axis of rotation. For example, if we wanted to rotate in the x axis, our vector would be \[1.0f,0.0f,0.0f\]. You can choose any arbitrary axis you want here. For our case, since we are doing 2D, we want to rotate around the z-axis, so we set x = 0.0f, y = 0.0f and z = 1.0f.

And as @concept3d mentioned, you need to specify that you want to make this rotation apply to the texture matrix, and he gives a way of tell OpenGL that.

**Note** that after setting the rotation with `glRotatef` all things renderd after that will be rotated by that angle you specified. Be sure to set this for each object, if different rotation are need.

Hope that helps. Happy rotating!

# Answer
> 1 votes
As I understand from your question is that you to rotate the actual textures and not the polygon vertices. This can be done by modifying the Texture Matrix not the ModelView Matrix.(you're using fixed pipeline).

In order to modify the texture matrix that actually transforms the UVs you need to enable it first.

```
glMatrixMode(GL_TEXTURE);
glLoadIdentity();
glRotatef(50.0, 0,0,1);

glMatrixMode(GL_MODEL_VIEW);

```

---
Tags: opengl, c++, textures
---


# Question
Title: Does Libgdx being "for Desktop" mean dependency-free native executables?
I want to clarify whether the Java Framework "LibGDX" can be used to compile games to native executables. The description/tagline says "Desktop/Android/HTML5/iOS Java game development framework".

I presumed that when they say "desktop", what is meant is native executables and not that they'll be `.jar` that needs JVM/Java installed on the native machine to run.

Can Libgdx games run without a Java dependency?

# Answer
It means desktop.

You have two options to deploy your libGDX app to the desktop:

* Create a self-runnable JAR. This is easier (Eclipse can export it pretty easily).
* Create an EXE, via launch4j (or some other wrapper). This is possible too (especially with Gradle).

I've used both approaches and they work equally well as far as I can tell.

Both rely on Java being installed. You still need a JVM; there's no way around it.

Launch4j also includes an option to bundle a JRE with your app, which would make it a "true" standalone application (doesn't need Java installed on the user's PC). Your app will be quite big, though.
> 3 votes

---
Tags: java, libgdx, platform, distribution
---


# Question
Title: What kind of gaming experiences does hiding game play stats and formulas cultivate?
There are varying degrees of providing players with information on their characters abilities - including but not limited to showing players their character's stats and how they tie into formulas such as total damage, damage reduction, etc. When these numbers and formulas are provided outright it can lead to a lot of min maxing / work to create an optimal build which can detract from simply enjoying the game by worrying too much about the numbers behind the scenes.

From a game design perspective I am looking for insight on:

* Personal experiences with designing stat systems where most if not all the information was hidden from the player. Include the types of decisions you made on what to hide and what to show to the player as well as the reasons behind those decisions and how they impacted the way players play the game.
* Personal experiences where you actively chose to provide as much information to the player as possible because you were against hiding information. Explain the thought process that drove you to this decision and the impact it had on the way players play the game.
* References to / resources on how different games have approached designing their stat systems that hide most of the information from the players and how the design has impacted the way players play the game

# Answer
> 24 votes
This answer is me taking a **gamasutra** article and summarizing it with the question asked in mind. As with any soft science there are disagreements even among the experts on the field so I would recommend looking into the links to specific schools of though.

## The Types of Players

> **The Fictionalists:** They see the game's story and fictional world as the most central aspects of video games, and want the game worlds to look and sound exactly like the fictional worlds presented in film. They are negative to all features that disturb the illusion of a coherent world existing separately from our own. They want to immerse into the story world and find all interface elements to be disturbing for the ability to suspend disbelief.
>
> **The Systemists:** They see the game as a formal system of rules and regard understanding the system as the most central and interesting game activity. They see the fictional environment as an overlay to the game system, and find the fiction to be present only as a supportive feature that is mainly unnecessary and only there to represent the system beyond. They accept the interface without question since it provides contact with the game system and presents information necessary for controlling and understanding the system.
>
> **The Relativists:** They are in the middle ground between the Fictionalist and the Systemist, and appreciate both the fictional and the game system layers. They see attempts at integrating the user interface or fictionalizing it as elegant solution, but accept that certain kinds of information may be hard to include.

I believe this bit does a good job of clarifying the definition of a Relativists.

> Necessity is therefore an important explanation for the Relativists. Although it may be more elegant to present all interface features as natural to the fictional game environment, there are many game system features that cannot be represented as such. For instance, verbal messages such as World of Warcraft's "I cannot cast that yet" and "Not enough rage" would appear as a negative intrusion for the Fictionalists, as they would argue that it makes no sense that the avatar would say that out loud, but for the Relativists this is perfectly acceptable.

## Tying it All Together.

I would argue that displaying statics such as damage on screen in a manner such as Borderlands or Diablo deter Fictionalists who are *"negative to all features that disturb the illusion of a coherent world existing separately from our own"* and cater towards Systemists who *"see the game as a formal system of rules and regard understanding the system as the most central and interesting"*.

**Now to directly answer the question.** Hiding statistics would attract Fictionalists and (so long as you are not leaving out needed information in your minimalizm) Relativists while also it would deter Systemists. It will attract people looking to immerse them selves in a new world but deter those looking to quantify and solve a new system.

# Answer
> 7 votes
## Hiding stats stops some casual players from optimizing their builds. However, it will not stop hardcore players from doing so.

For example BF3 had completely inaccurate and misleading weapon stats ingame. There are sites dedicated to testing and analysis of all the weapons in the game with nice graphs and charts. This is the most popular one. http://symthic.com/bf3-weapon-charts

No matter how much you attempt to obfuscate what is happening behind the scenes people will do their own testing and figure out what builds are the most efficient for certain tasks.

Hiding the stats in this way just ensures that the hard core players will have far better builds than casuals, further increasing the skill disparity.

# Answer
> 6 votes
This is my first post on this stack, so bear with me! This is just my simple opinion.

**Hidden**

I am a huge believer in hiding certain mechanics in a game. This is mainly to add some mystery to the game where I--as the developer--am not showing my entire hand to the player.

When I say hand, I'm referring to the game of poker. It's me against you, you against me. If I show you my hand, it takes the fun out of playing the game much like it can take the fun out of the game I'm developing for the end user.

For example, when working on my first text-based online game in the late 90's, I stuck with the original design of not showing how stats played a role in damage. I didn't show how stats played a role in skill check success rates. These, among many others, were an entire mystery to the players. They had to figure it out for themselves by actually playing the game.

This decision caused players to focus more on playing and most importantly, discovering the game. They spent time applying different theories in order to discover a definitive answer. But, with no true definitive answer to be 100% proven, this lead to different playing styles, different approaches to simple or complex problems and heartache.

The impact was acceptable with the decision to hide. Most players enjoyed the mystery and enjoyed the path to discovery where I didn't show my entire hand. They felt that every log-in, there was something new to discover and something new to learn where there was no definitive answer. So, you could be wrong and still be right, which is key to maintaining a healthy player base in online games in some cases.

On others, the impact was harsh. The need to know and be given everything quicker rather than later was growing strong. This was mainly due to certain games where consequences, downtime and more were reduced to make playing easier, quicker and accessible.

**Visible**

I am not a big believer in sharing everything, but when I have, I felt the discovery and the need to play from the end user had been reduced. Knowing everything, much like having a god mode option, can take the fun out of playing the game in some cases.

For example, when we introduced a game mechanic in a game that I will not say, and revealed too much behind the mechanic and the underlying game system, it lead to increased exploits because the end user knew definitively what will work, not work and how to exploit the system. When the exploits were resolved, it lead to a definitive answer to what will work and what will not work, which is in some cases, still a problem

What will work could be one element or many different elements that cannibalize or compete with other elements to the point of being void. Like for another example, character equipment.

We had a hard cap on a stat for hitroll and damroll. These define if you can hit a target based on an AC check and when you passed, determines how much damage you dish out. Having a character class designed around hitroll and damroll forced players to pick only the highest hitroll and damroll bonused equipment. Therefore, voiding any other pieces of equipment that did not meet the criteria.

In return, a good number of world zones were not being used. The NPC (monsters) that didn't carry those certain sets of equipment were not being used. No one cared to kill them because it wasn't the best and time spent in development of those zones is wasted.

**Mystery**

I think that mystery behind what you develop is important to a healthy game. That doesn't mean you should hide everything, but in some cases, you should let the players discover it. This is what adds to the fun, but not all the fun. It's like a enhancement that adds something delicious to hopefully, an already good recipe for success.

When that mystery is revealed. The paths are clear. Having a clear path can mean other paths are less traveled. If you take the approach of eliminating paths, then game depth becomes shallow. That's exactly why you have variety and why you see 2 or more types of different game elements such as different damage stats, armor stats, class stats and ETC. It adds depth to the game, it adds more options to the game and in most cases, can add more mystery to be discovered to the game.

# Answer
> 2 votes
If you want the game to cater to specific audience, you need to know what the audience is looking to get out of the game. I always refer to this article when planning out content and game interface ( http://mud.co.uk/richard/hcds.htm )

The FPS gamers, on average, do not care about the exact numbers for their armor, health, damage etc. They will most likely shoot each other to a point where they can figure out which build is good for which situations, the min-maxer players that will dig out stats and chart them will always be there but they will be a minority.

The RPG players, most often need stats to build their character. Stats are kind of important for two reasons, you want to invest in your character and you want to understand the consequences of your decisions. Stats play a big role in mechanics, especially skill tests. Lack of stats in RPGS may frustruate an RPG player because they will often have to reroll to get something that works, or they won't understand the game at all because mechanics are not clear.

My approach to designing the game interface is therefore understanding who the audience is and what they are looking to get out of game play, and exposing enough stats so that the rules of the game are clear, even to a newbie. If I choose to hide exact numbers from the users, then there should at least be some written rule or hint like (using armor-piercing rounds allows you to do more damage to vehicles). I may not need to give exact stats, but at least the player may not get confused why one weapon does damage and others do nothing at all. The only stats I usually hide on purpose, are the random chance ones : lucky hits, loot drop, random events etc, but those things player's will most likely know or expect from the game.

---
Tags: game-design, statistics, mathematics
---


# Question
Title: texconv produces texture with same size using BC1 or BC4
According to msdn, the BC1 block compression format is for images with 3 color channels and 1 bit alpha channel and the BC4 is for images with 1 color channel and no alpha.

Using the same RGBA input image I would expect the output of this command

`texconv.exe -f BC1_UNORM diffuse.tga`

to be larger than the output of this other command

`texconv.exe -f BC4_UNORM diffuse.tga`

Since the resulting DDS should only have information on one channel, but both DDS have the exact same size. The only difference being that the BC4 compressed one appears red (as expected).

Is this the expected output?

# Answer
Given the documentation, it would seem that is the expected output.

BC1 represents the data before compression as 5 bits red, 6 bits green, 5 bits blue, and 0 or 1 bits alpha, for 16 or 17 bits per pixel. BC4 represents it as one 8-bit channel, for 8 bits per pixel.

However, then it compresses it. I'm not sure how exactly the compression works, but if you look at the tables provided that give specific information on each compression, you'll note that both BC1 and BC4 achieve 8 bytes per 4x4 pixel block (or an average of 4 bits per pixel).

As I said, I can't explain exactly how it achieves that, maybe someone will explain in a comment, but ultimately the docs do seem to say that your results are exactly what are expected.
> 1 votes

---
Tags: textures, compression, dds
---


# Question
Title: How can I make an object move in four directions relative to its rotation?
I want to make a game object move in directions relative to the direction it is facing. That is, if the user presses the "W" key the object goes "forward"; if they press "D" the object goes to its left. etc

So far I am having trouble, because I can't make it move in the correct direction when its rotated.

I just want some pseudo code to point me in the right direction, thank you.

# Answer
One way to do it is to keep track of the Front and Up normalized vectors and transform the front vector whenever your character turns, and calculate the Right vector using cross product ( I am assuming Up vector won't rotate). Or you can keep track of the three vectors and rotate them. Once you rotate them you update the position by adding the offset in the needed direction.

In order to move the position in the intended direction you only need to add the front or right vector to the position given that

```
front = Rotate(front, degree);
vec3 right = Cross(front, up);
// if player input D
position += right;
// if player input W
position += front;

```

You only need to negate the front/right vector if the player presses A or S
> 4 votes

# Answer
I think some trigonometry classes would help you.

Meaning of variables `position.x` is the x coordinate, and `position.z` is the y (if 2D game) or z (3D game) coordinate. Yaw is the rotation (in radians I think). So when user presses A do `yaw--;` and when user presses S do `yaw++;`. Distance is how far to move (sort of like speed).

NOTE: This is written in Java. Converting to c/c++/c# should be no problem. Also, remember to replace `position.x` and `position.z` with the variables your using for x and y.

```
public void walkForward(float distance)
{
    position.x -= distance * (float)Math.sin(Math.toRadians(yaw));
    position.z += distance * (float)Math.cos(Math.toRadians(yaw));
}
//moves the camera backward relative to its current rotation (yaw)
public void walkBackwards(float distance)
{
    position.x += distance * (float)Math.sin(Math.toRadians(yaw));
    position.z -= distance * (float)Math.cos(Math.toRadians(yaw));
}
//strafes the camera left relitive to its current rotation (yaw)
public void strafeLeft(float distance)
{
    position.x -= distance * (float)Math.sin(Math.toRadians(yaw-90));
    position.z += distance * (float)Math.cos(Math.toRadians(yaw-90));
}
//strafes the camera right relitive to its current rotation (yaw)
public void strafeRight(float distance)
{
    position.x -= distance * (float)Math.sin(Math.toRadians(yaw+90));
    position.z += distance * (float)Math.cos(Math.toRadians(yaw+90));
}

```

My Source
> 0 votes

---
Tags: rotation, movement, pc
---


# Question
Title: How should a player object to communicate with a map object?
I'm writing my first game (in Javascript / Node over WebSockets) and am running into a bit of chicken and egg problem, and am afraid how I'm doing it right now won't scale once the game gets more complex.

Here is how the game is architected. It's a tiled strategy game. When a user connects, a new Game object is created:

```
// width and height of the board / map
function Game(width, height) {
  this.map = new Map(width, height);
  this.player = new Player();
  // ...
}

game = new Game(100,100);

```

What's reasonable way for 2-way communication between a player object (or any object), and the map?

For example, if a player wants to move left, first I must check that there is no obstacle in his way, then, once this condition is true, his position must be updated, and he loses a stamina point, so both the map and the player objects are updated depending on conditions that most objects both meet (in the simplest case, where there is no interaction with other objects).

One way I can think, is to have a global GAME object, so that the map can access GAME.player and the player can access GAME.map, but this doesn't seem elegant (and will cause me a headache once I have multiple rooms with separate games running on the same node instance).

# Answer
Your question is a bit wider than you exposed I think. Player and Map are two objects and should be thought as it. They are not different, from an engine point of view, of a ping-pong table or a flying toaster.

That said the question is : how to make NORMAL objects findable and communicate?

For a map / player relation I usually put responsability... on a third object. Something called PlayerController who'd be in charge of moving the Player according to his current position and the possibilities the map offers. The PlayerController needs to have access to Player and also to Map, so how to do so?

Imagine that EVERY object in the game registers itself (at construction) in a static/global (whatever the langage you use) object, for it to act like a big collection containing all your game objects.

With such object you'd retrieve any object, from anywhere, like this:

```
game_map = GameObjects[typeof(Map)];
player = GameObjects[typeof(Player)];

```

(in this example I use typeof, C# style, but of course you can identify your game objects with anything you want, integer id, string name... whatever adapted to the langage you use.)

However I'd suggest you to take care of "global/static/Singleton" objects, and not use them too much in your game code (this topic is largely discussed everywhere on the Internet, but you can learn more here).

I hope it helps.

EDIT: This solution is obviously a naive approach. In case you have to manage several players or maps you will have to identify your objects in a better way (at least more precise way).
> 4 votes

# Answer
I would personally discourage you from any kind of direct map-player communication there is no need for it. It is game logic responsibility to handle such interaction. Often, there is some kind of GameObject manager or component system.
As for multiple players/maps, server should be resonsible for instantiating maps and moving players between them.
> 1 votes

# Answer
There is no reason for the Map and Player objects to communicate at all that I can see. So far as what you've told us we can assume that Player object only holds data about their position, but then what does the map hold? (rhetorical Q). It sounds like the objects are doing the same job. I.e. the map already knows the Player object's position.

If your map has some kind of internal data so that you can ask it to check who/what is at some position (See example below), then you are duplicating effort. The Player object may not need to know it's position at all if you leave that up to the user (i.e. we can see where our Player is on the screen) and the map knows where all the objects are. That is, the user tries to do something (based on the output shown them) and whether they are allowed to do that or not is dictated by game logic which checks the player and map.

```
-- Map Data
 0,0
[---][---][---][P2 ]
[---][---][---][---]
[---][P1 ][---][---]
[---][---][---][---]
________________3,3

```

-- Player Data stamina = 2 (can move twice)

-- Game Object Player2: I want to move from 0,3 to 1,3 (\>Game) check: player2 stamina \> 0 check: position 1,3 not occupied move: player2 to 1,3 Game: Player2 moves to 1,3 (\>Player2)

Player \<-\> Game Object \<-\> Map

So, the Player and Map only ever communicate with the Game object respectively. The client might have a local static map object that simply stores what the server says the state of the map is at the moment. The player indicates to the game object what they want to do and if it is possible the change is made and any consequences processed. Then the player is told that it's done and given the updated map data to display.
> 0 votes

---
Tags: architecture
---


title: Ground in AndEngine

text:
# Question
Title: Ground in AndEngine
I'm quite a newbie to AnEngine and I have a problem. I have been searching a lot, but I couldn't find answer. I'm trying to make my first game, but I have no idea how to make ground. I'd like to make ground like in this game: https://play.google.com/store/apps/details?id=com.fingersoft.hillclimb&hl=cs

That ground should be static and has a lot of curves. Should I make it as one big sprite and attach body to it ? But how to make it curvy then ? I really have no idea.

Tkanks for answers.

# Answer
You aren't suppose to create it with one big sprite. That would consume too much memory for one. While we cannot tell you how it was made in that game, the general idea is using Bézier curves. If you connect multiple curves like these, you can get a smooth flowing surface.

You can see an example here on how to create such a smooth surface for your game.

To render this surface, you would have to possibly use a Framework like OpenFL or convert the bezeir enclosed surface into polygons and apply a texture to them. There are possibly other ways to do this, we cannot tell you which way that specific game used.

To get the physics working, you would need a physics engine like Box2D or Nape with Haxe & OpenFL. You could roll your own physics engine in theory but it's subjectively highly not recommended because such work would possibly take a lot of time and the results are not likely to be on par with the existing solutions.
> 1 votes

---
Tags: physics, sprites, andengine
---


# Question
Title: Multiplayer and creeps (NPC enemies): how to compute bullet hits given the lag?
We are making a multiplayer co-op game, where players will shoot not each other but AI enemies (creeps), controlled by the game. The chosen implementation is client-server with an authoritative server. **Edit: we use client-side prediction for both creeps and avatats to give the illusion of immediate responses.** So far we managed to make creeps movement syncronized on the client and the server, that is at the same point in time each and every creep are located in the very same place on the client and on the server.

However, the player avatars cannot be syncronized in this way - it is simply impossible. Player avatar will always lag on the server. Now the problem arises when we try to shoot and hit the creeps. The two avatars (client and server ones) will fire bullets in different places (because one lags from another), but the creeps positions are equal. Bullets hit almost instantly, which means that quite often the bullets will not hit the creeps on one of the machines and, as the server is authoritative, it will have the final say in what actually happened. Ofcourse such behaviour is unacceptable.

One solution would be to force creeps to lag on the server, but that is a poor solution as the lag (ping) may vary dynamically and, more importantly, the game is designed to allow for up to 4 player multiplayer mode and I cannot even start to think, how to fit this solution to other players' bullets.

The only thing I could find so far on the internet is the fact that in FPS multiplayer shooters you see your opponent in the past and the server "rewinds" each of you before hit-scanning. But how do you exacly implement this? Do you keep the list of recent positions/actions on the server? But what if hit-scanning involves taking skeletal animation into account? Do you store recently played animations aswell? Any advice would be appreciated.

# Answer
> 5 votes
Something seems wrong to me in your implementation of the authoritative server. Basically an **authoritative server controls everything**. It is the pivot of your network architecture. Clients just "ask gently" when they want to do some actions, and the server has the authority to say "NO I DON'T WANT YOU TO DO THAT BECAUSE I'M THE BOSS HERE!"...

That said, I don't understand how your avatars can be at different positions. In a basic authoritative server, players can't move by themselves. Instead of something like :

> Player00: "Hey Server, I moved and my new position is {x:42,y:24}! Deal with it!"

The communication with an authoritative server is more like :

> Player00: "Hey Server, I want to move on my right... can I?"
>
> Server: "Yeah, Player00, you can, your new position is {x:42,y:24}."
>
> Server: "HEY OTHER PLAYERS! Player00 just moved to {x:42,y:24}!"

As you can see and as Tim Sweeney wrote : "The server is the man!"

Of course such strict authoritative server has hard time to be visually correct and synced when lag comes to play, and I would suggest you to read further readings about that, such as this very interesting piece from Valve about input prediction.

But for your "bullet position" problem, it will do the job. As the players will just inform the server that they want to shoot bullet, the server knows how they are oriented, and if they are allowed to shoot, so the server can say to every other players that a specific player has just spawned a bullet. That way every players is informed about spawned bullet position, orientation and time.

Time is an important thing to add to your network code. If you know where and WHEN things have been done, and if at moment you know that clients' internal clocks have been synced to server clock, then you can interpolate and predict the current exact position and state of things.

That's the trick.

I hope it helps.

---
Tags: multiplayer, client-server, bullet-physics
---


# Question
Title: Finding a vector perpendicular to a current vector
Assume, that we have a player that has a vector direction. We have an enemy, that is shooting a player. And the task is to find out from which side the enemy is shooting. I know the algorithm, how to find this.We need to find the left vector and then do a dot product with enemy direction vector. The question is to find the left or right side of player's current vision and it means to find out the vector perpendicular to the player's vector. What's the easiest and the most least computation way to find it.

# Answer
> 2 votes
In order to compute left and right, you need the concept of "up". For instance, if you are flying a spaceship and performing a "barrel roll" then the concept of "up" changes and with it, left and right change as well although you are facing in the same direction. Up can be based on the plain the character is standing on or simply be an absolute direction.

Once you figure out "up" you simply do the cross product like @JarkkoL already explained. If you multiply with the reverse order, you"ll get the opposite direction. So in other words, if `left == cross(forward, up)` than `right == cross(up, forward)`. You can also simply negate one to compute the other.

---
Tags: 3d, mathematics
---


# Question
Title: Java Slick2d - How to translate mouse coordinates to world coordinates
I am translating in my main class `render`. How do I get the mouse position where my mouse actually is after I scroll the screen

```
public void render(GameContainer gc, Graphics g) throws SlickException
{
    float centerX = 800/2;
    float centerY = 600/2;
    g.translate(centerX, centerY);
    g.translate(-player.playerX, -player.playerY);
    gen.render(g);
    player.render(g);
}

playerX = 800 /2 - sprite.getWidth();
playerY = 600 /2 - sprite.getHeight();

```

***Image to help with explanation***

I tried implementing a camera but it seems no matter what I can't get the mouse position. I was told to do this `worldX = mouseX + camX;` but it didn't work the mouse was still off.

Here is my Camera class if that helps:

```
public class Camera {
public float camX;
public float camY;

Player player;

public void init() {
    player = new Player();
}

public void update(GameContainer gc, int delta) {
    Input input = gc.getInput();

    if(input.isKeyDown(Input.KEY_W)) {
        camY -= player.speed * delta;
    }
    if(input.isKeyDown(Input.KEY_S)) {
        camY += player.speed * delta;
    }
    if(input.isKeyDown(Input.KEY_A)) {
        camX -= player.speed * delta;
    }
    if(input.isKeyDown(Input.KEY_D)) {
        camX += player.speed * delta;
    }
}

```

***Code used to convert mouse***

```
worldX = (int) (mouseX + cam.camX);
worldY = (int) (mouseY + cam.camY);

```

***Tile class***

```
public class TileGen {
Block block;
public Block[] tiles = new Block[2];
public int width, height;
public int[][] index;
int mouseX, mouseY;
int worldX, worldY;
boolean selected;

Image dirt, grass, selection;
SpriteSheet tileSheet;

int startX, startY, stopX, stopY;

Camera cam;
Player player;

public void init() throws SlickException {
    tileSheet = new SpriteSheet("assets/tiles/tileSheet.png", 64, 64);

    grass = tileSheet.getSprite(0,0);
    dirt = tileSheet.getSprite(1,0);
    selection = tileSheet.getSprite(2,0);

    tiles[0] = new Block(BlockType.Grass, new Vector2f(0,0), grass, true);
    tiles[1] = new Block(BlockType.Dirt, new Vector2f(0,0), dirt, true);

    width = 50;
    height = 50;

    index = new int[width][height];

    cam = new Camera();
    player = new Player();

    Random rand = new Random();
    for (int x = 0; x < width; x++) {
        for (int y = 0; y < height; y++) {
            index[x][y] = rand.nextInt(2);
        }
    }
}

public void update(GameContainer gc) {
    Input input = gc.getInput();
    mouseX = input.getMouseX();
    mouseY = input.getMouseY();

    worldX = (int) (mouseX - player.playerX);
    worldY = (int) (mouseY - player.playerY);

    if(input.isMousePressed(Input.MOUSE_LEFT_BUTTON)) {
        selected = true;
    } else {selected = false;}

    for (int x = 0; x < width; x++)
    {
        for (int y = 0; y < height; y++)
        {
            if(IsMouseInsideTile(x, y) && selected) {
                if(tiles[index[x][y]]== tiles[0])
                    index[x][y] = 1;
            }
        }
    }

    startX = (int) (cam.camX/64);
    startY = (int) (cam.camY/64);

    stopX = startX + (gc.getWidth()/64)  + 2;
    stopY = startY + (gc.getHeight()/64) + 2;
    System.out.println(worldX);
}

public void render(Graphics g, GameContainer container) {
    for (int x = startX; x < stopX; x++) {
        for (int y = startY; y < stopY; y++) {
            tiles[index[x][y]].texture.draw(x * 64, y *64);
            if(IsMouseInsideTile(x, y)) {
                selection.draw(x * 64, y * 64);
            }
        }
    }
}

public boolean IsMouseInsideTile(int x, int y)
{
    return (worldX >= x * 64 && worldX <= (x + 1) * 64 &&
            worldY >= y * 64 && worldY <= (y + 1) * 64);
}

```

}

# Answer
This could explain your issues. You're drawing your scene based on the position of your character. However, you're attempting to get the mouse coordinates based on the position of your camera. Try rendering like this:

```
g.translate(cam.camX, cam.camY);
gen.render(g);
player.render(g);

```

Or try your mouse coordinates like this:

```
worldX = (int) (mouseX + player.playerX);
worldY = (int) (mouseY + player.playerY);

```

I imagine you'll be seeing something completely different than before. At the moment your camera is rather unattached to your scene. You seem to be updating it, but I guess somewhere else you're also updating the position of your player. Unless those two updates were exactly the same, you're not going to have them in-sync. Basically you want to use your camera for what it is, use it to frame the scene. If you want to set it to exactly follow your character, that's fine, but use it's values for drawing your viewport.
> 2 votes

# Answer
I wrote a class camera i use to draw a Box2D world into slick2d. It's basically the same. You get the mouse position via:

```
float mouseX = Input.getMouseX();
float mouseY = Input.getMouseY();

```

and then to mouseX you add the cameraX (that's the camera horizontal position in world) and to mouseY you add cameraY. These are my functions:

```
public Vec2 screenToWorld(Vec2 screenV) {
    return new Vec2(screenV.x + Camera.x,
            screenV.y + Camera.y);
}

public Vec2 worldToScreen(Vec2 worldV) {
    return new Vec2(worldV.x - Camera.x,
            worldV.y - Camera.y);
}

```

Where Vec2 is a class that has a "x" variable and a "y" variable of type float.
> 0 votes

# Answer
Edit: just realised this is pretty old.

Anyways, I did something similar to this in a TD game so hopefully the same would apply here.

In my `TileMap` class I have a method called `getTileCoord(int mouseX, int mouseY)` and for your game it would be translated to something like this:

```
int tileX = (int) (mouseX - camX) / tileWidth;
int tileY = (int) (mouseY - camY) / tileHeight;

...// cap the tile coordinates to 0 and the max width/height if needed
tileX *= tileWidth;
tileY *= tileHeight;
or multiply at at draw of selection
selection.draw(tileX * 64, tileY * 64);

```

Calling `selection.draw` should now be done outside the x and y loop.

If you can scale your camera the the code would become:

```
int tileX = (int) (((x - camX * scale) / tileWidth) * (1 / scale));
int tileY = (int) (((y - camY * scale) / tileHeight) * (1 / scale));

```

Contains some unnecessary code at the moment, I'll update it once I find the recent version.
> 0 votes

# Answer
float mouseY = Math.abs(Mouse.getY() - Gamecontainer.getHeight());
> -1 votes

---
Tags: java, coordinates, mouse, slick
---


# Question
Title: Who use javaFX for commercial quality games?
Are there any companies work with javaFX for building videos games ?

# Answer
I have to say that the current build JavaFX 8 is very well suitable for professional games at least for 2D. The big advantage is that JavaFX has a very professional GUI library which makes it very suitable for UI heavy games.
> 2 votes

# Answer
JavaFX was not built with speed in mind, therefore the JavaFX 2D and 3D libraries are too slow.

I suggest you use JOGL from www.jogamp.org. This library is more than commercially viable.
> 1 votes

---
Tags: java
---