# Question
Title: Libgdx - Jumping, What am i doing wrong?
I really can't work out whats wrong with my code. I have an input listener for gestures, when I Swipe the position goes up on the y axis fine but he doesn't come back down, if with Gravity added. I'll show you any code relevant to the Character.

World.java : updateRuben

```
private void updateRuben (float deltaTime, float accelX) {

        if (Ruben.getState() != Ruben.RUBEN_STATE_IDLE && ruben.position.y <= 0.5f) ruben.hitPlatform();//
        if (Ruben.getState() != Ruben.RUBEN_STATE_IDLE) ruben.velocity.x = -accelX / 10 * Ruben.RUBEN_MOVE_VELOCITY;

                // clamp the velocity to 0 if it's < 1, and set the state to standing
                if (Math.abs(ruben.velocity.y) < 1) {
                    ruben.velocity.y = 0;
                    Ruben.setState(Ruben.RUBEN_STATE_IDLE);
                }

        ruben.update(deltaTime);
        heightSoFar = Math.max(ruben.position.y, heightSoFar);
    }

```

Ruben.java

```
package com.wilson.game.Game;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.input.GestureDetector;
import com.wilson.game.System.DynamicGameObject;
import com.wilson.game.System.World;
import com.wilson.game.System.inputController;

public class Ruben extends DynamicGameObject {
    public static final int RUBEN_STATE_IDLE = 0;
    public static final int RUBEN_STATE_JUMP = 1;
    public static final int RUBEN_STATE_FALL = 2;
    public static final int RUBEN_STATE_HIT = 3;
    public static final int RUBEN_STATE_WALKING = 4;
    public static final int RUBEN_STATE_SPAWN = 5;

    public static final float RUBEN_MAX_VELOCITY = 11;
    public static final float RUBEN_JUMP_VELOCITY = 11;
    public static final float RUBEN_MOVE_VELOCITY = 20;
    public static final float RUBEN_WIDTH = 2f;
    public static final float RUBEN_HEIGHT = 2.5f;
    public static final float RUBEN_SPAWN_TIME = 0.4f;

    public static int state;
    static float stateTime;
    private static boolean grounded;
    public boolean facingRight;

    public Ruben (float x, float y) {
        super(x, y, RUBEN_WIDTH, RUBEN_HEIGHT);
        state = RUBEN_STATE_SPAWN;
        stateTime = 0;
        grounded = true;
        facingRight = true;

        Gdx.input.setInputProcessor(new GestureDetector(new inputController()));
        }

    public void update (float deltaTime) {
        processInput();
        position.add(velocity.x * deltaTime, velocity.y * deltaTime);
        velocity.add(World.gravity.x * deltaTime, World.gravity.y * deltaTime);

        bounds.x = RUBEN_WIDTH;
        bounds.y = RUBEN_HEIGHT;

        if (state == RUBEN_STATE_SPAWN) {
            if (stateTime > RUBEN_SPAWN_TIME) {
                state = RUBEN_STATE_IDLE;
                grounded = true;
            }
        }

        if (position.x * deltaTime < 0) position.x = World.WORLD_WIDTH;
        if (position.x * deltaTime > World.WORLD_WIDTH) position.x = 0;

        stateTime += deltaTime;
}

    private void processInput() {
        if (inputController.fling == true) {
            jump();
            }
        }

    public void hitSquirrel () {
        velocity.set(0, 0);
        state = RUBEN_STATE_HIT;
        stateTime = 0;
    }

    public void jump()
    {
        if (state != RUBEN_STATE_JUMP)
        state = RUBEN_STATE_JUMP;
        velocity.y = velocity.y * RUBEN_JUMP_VELOCITY;
        grounded = false;
        stateTime = 0;
    }

    public void hitPlatform () {
        state = RUBEN_STATE_IDLE;
        stateTime = 0;
        grounded = true;
    }

    public void hitSpring () {
        velocity.y = RUBEN_JUMP_VELOCITY * 1.5f;
        state = RUBEN_STATE_JUMP;
        stateTime = 0;
        grounded = false;
    }

    public static int getState() {
        return state;
    }

    public static float getStateTime() {
        return stateTime;
    }

    public static void setState(int currentstate) {
        currentstate = state;
    }

    public static boolean isGrounded() {
        return grounded;
    }

    public static void setStateTime(float i) {

        i = stateTime;

    }
}

```

How do you apply physics to the actor in order for him to come back down? what am i missing?

# Answer
> 1 votes
```
//At the apex of the jump, Ruben's velocity.y is ~0
if (Math.abs(ruben.velocity.y) < 1) //If Ruben's velocity.y gets close to 0...
{
   ruben.velocity.y = 0; //stop him
   Ruben.setState(Ruben.RUBEN_STATE_IDLE);
}

//velocity.y = +1 //jumping
//velocity.y = 0 //no more jump left; begin falling (except the if activates)
//velocity.y = -1 //falling

```

Edit - Some other, non-related things:

```
void jump()...
//Add braces; no need to do any of this if already jumping
if (state != RUBEN_STATE_JUMP)
{
    state = RUBEN_STATE_JUMP;
    velocity.y = velocity.y * RUBEN_JUMP_VELOCITY;
    grounded = false;
    stateTime = 0;
}

void update()...
//This is more typical (reversed)
velocity.add(World.gravity.x * deltaTime, World.gravity.y * deltaTime);
position.add(velocity.x * deltaTime, velocity.y * deltaTime);

void update()...
if (position.x * deltaTime >...) //What?!? Position * deltaTime??

void update()...
//You are negating part of velocity if the player "wraps"
//This wraps them, but preserves their position delta.
if (position.x > World.WORLD_WIDTH) position.x -= World.WORLD_WIDTH;
if (position.x < 0) position.x += World.WORLD_WIDTH;

```

---
Tags: java, android, libgdx, jumping
---


title: How to keep a shape inside a rectangle?

text:
# Question
Title: How to keep a shape inside a rectangle?
So I'm making a game which is based on randomly generated rooms and I need a way to keep the player inside them and make the player glide when he collides with the room's bounds. I currently have a SAT algorithm in place to detect collisions, but I don't know how to do collision resolution for being inside rooms.

Full code here

```
sf::Vector2f Collision::GetMtv()
{
    return (Mtv(small, smallestPerpendicular[smallestIndex]));
}

```

# Answer
How I would do it:

* Step 1: define rectangles for the bounds of each room and hallway. Now imagine these rectangles as safe areas where the player can be. "Out of bounds" would be declared as any position in which the player is not fully contained in any of the rooms or hallways. Here's a picture as a demonstration:

Now, before we go further, **you must note one important fact**. If the player is between a room and a hallway, it will be declared out of bounds. So to avoid this problem, you must define your hallway rectangles overlapping into both rooms by a little bit more than the maximum size of the player.

* Step 2: every time you move the player on the X axis, keep track of a "last X" variable. If the player steps out of bounds, then restore the player's X value to that variable. Do the same for Y movement.
* Step 3: One final note is that if it is easier to do so, you can instead define rectangles for all of the walls (aka black space). Then, you reverse the collision check per rectangle to "if Rx1 \> Lx2 && Lx1 \< Rx2 && Uy1 \< Dy2 && Dy1 \> Uy2, then there is a collision with that rectangle (the wall)".
* Step 4: Finally, if you want pixel perfect collision detection: well, pixel perfect collision is very expensive. However, in some cases it is worth it. You should really check out Riemer's 2D collision tutorial - it's written in C# instead of C++ but it's really straightforward and easy to understand - you should at least be able to use the concept if not the exact code. http://www.riemers.net/eng/Tutorials/XNA/Csharp/Series2D/Coll\_Detection\_Overview.php
> 1 votes

# Answer
Great work that you are doing here :D.

The thing about advanced collision detection or any technical aspect of programming is getting it done right.

To do so, you must separate the mechanic you want, then make it in a separate environment, then test it then port it into your game.

in this case, you want to make a separate SAT collision demo first then implement that into your game.

Take a look at the interactive demo **HERE**.

However in your case,

since you only have squares why not choose a simpler approach?

You don't need to go for SAT, because if your "squares" are all going to be laid nice and pretty horizontally, then you have no need for diagonal or any other collision test for rotated shapes.

Why don't you try AABB? **Youtube**

If I were you, I would put square walls at the edge of map.

AABB is a very simple and popular technique. You would be able to find abundance of resources to learn it.
> 0 votes

---
Tags: c++, 2d, collision-detection, collision-resolution, sfml
---


title: Drawing a pixel to RenderTexture

text:
# Question
Title: Drawing a pixel to RenderTexture
I would like to know how you would go about drawing a single pixel to a RenderTexture in Unity.

In XNA, it was just a matter of setting the graphic device's active renderTarget, and drawing to it.

In Unity, I am unable to figure out how to do this properly. I attempted to use Graphics.DrawTexture, but that seems to be horribly slow.

I imagine there is something that can be done with GL, but I haven't been able to make it draw in side the RenderTexture properly.

Here was my attempt with DrawTexture:

```
    RenderTexture.active = rt;
    GL.PushMatrix();
    GL.LoadPixelMatrix(0, 128, 128, 0);

    for (int x = 0; x < 128; x++)
    {
        for (int y = 0; y < 128; y++)
        {
            Graphics.DrawTexture(new Rect(x, y, 1, 1), texture, mat);
        }
    }

    GL.PopMatrix();
    RenderTexture.active = null;

```

# Answer
> 14 votes
Original RenderTexture image on the left, edited Texture2D image on the right.

```
public class PixelChange : MonoBehaviour {
public RenderTexture renderTexture; // renderTextuer that you will be rendering stuff on
public Renderer renderer; // renderer in which you will apply changed texture
Texture2D texture;

void Start () {

    texture = new Texture2D (renderTexture.width, renderTexture.height);
    renderer.material.mainTexture =  texture;
    //make texture2D because you want to "edit" it.
    //however this is not a way to apply any post rendering effects because
    //this way, you are reading it through CPU(slow).
}

int at = 0;
// Update is called once per frame
void Update () {
    at++;
    RenderTexture.active = renderTexture;
    //don't forget that you need to specify rendertexture before you call readpixels
    //otherwise it will read screen pixels.
    texture.ReadPixels (new Rect (0, 0, renderTexture.width, renderTexture.height), 0, 0);
    for (int i = 0; i < renderTexture.width*.2f; i++)
    for (int j = 0; j < renderTexture.height;j++){
        texture.SetPixel((at +i),j, new Color(1,0,0) );
    }
    texture.Apply ();
    RenderTexture.active = null; //don't forget to set it back to null once you finished playing with it.
}
}

```

Reminder, reading onto texture2D then editing it is slow because Apply call sends chunk of information back go gpu for changed pixels to be applied.

The "correct way" would be writing shader or have "pixel size" object to be drawn onto the final screen, renderTexture.

---
Tags: c#, opengl, unity, rendertexture
---


# Question
Title: Best way to deal with a large variety of items?
I am currently working on my first java game and I am having trouble figuring out how I should implement my classes that will have heavy variety. For example, I am considering having an abstract item class that every item in the game will inherit from, but I don't really know how specific I should get with the sub classes. Is an armor class enough? Should I break it down into where the armor will be equipped(head, chest, etc)? Should I go so far as to give every single item it's own class and use a factory?

I apologize in advance for the noobie question, I have been searching around for a couple of hours but haven't been able to find a solid best practices guide that really goes in depth with this kind of stuff.

# Answer
Well honestly, in a personal project, whatever works for your needs is good enough. In a professional game, if you were working with a team of other programmers and designers you'd want it to be data driven so designers could tweak numbers and such. There's no clear cut answer though, it really is kind of a personal preference of the people involved, and to some extent doesn't matter so long as it fits the needs of your project. You could always start out with a best guess and change course if needed along the way, but chances are this isn't going to be a major issue in your game whatever you choose (:
> 1 votes

# Answer
The way I am doing it with my game is as follows:

I have a very generic abstract Item class that is the basis for all types of items. This is what it looks like:

```
public abstract class Item {
    public enum Type {
        weapon;
    }

    public abstract Type getItemType();

    public abstract String getName();

    public abstract String getDescription();

    @Override
    public String toString() {
        return getName() + ": " + getDescription();
    }
}

```

*Note that I only have weapons now because I am still building my game, but the way I am doing it should make it very easy to add new types of items.*

I then have a more specific class depending the type of item (of course I only have weapons now):

```
public class Weapon extends Item {
    private Weapons type;
    private int uses;

    public Weapon(Weapons type) {
        this.type = type;
    }

    public int getUses() {
        return uses;
    }

    public int getMaxUses() {
        return type.uses;
    }

    public boolean use() {
        if(getMaxUses() < 0)
            return false;
        uses--;
        return uses <= 0;
    }

    public int getBaseExp() {
        return type.baseExp;
    }

    public int getDamage() {
        return type.damage;
    }

    @Override
    public Type getItemType() {
        return Type.weapon;
    }

    @Override
    public String getName() {
        return Stats.ucFirst(type.toString()); //this isn't important, only makes the first letter upper case
    }

    @Override
    public String getDescription() {
        return type.description;
    }
}

```

Now you may be confused as to what `Weapons type` is. This is how I am enabling my game to have easily added items, classes, etc. This is what `Weapons.java` looks like (it only contains one item for now):

```
public enum Weapons {
    claws(-1, 9, 40); //-1 uses, i.e. infinite

    int uses, damage, baseExp;
    String description;

    Weapons(int uses, int damage, int baseExp) {
        this.uses = uses;
        this.damage = damage;
        this.baseExp = baseExp;
        this.description = ReverseBlade.ioHandler.getDescription(this);
    }
}

```

Because it is an enum I do not need to create new classes for each individual weapon, instead I just add 1 easy line to this code. And I can easily give a character any type of weapon with `new Weapon(Weapons.claw)` for example.

Using a system like this you can easily keep all of your items in order while still being able to create new ones. Of course, if you want a certain weapon to be very special with completely unorthodox effects you will have to create a new class (just have it extend Weapon for example). Although you should be able to add an infinite amount of parameters and just make defaults for each one if certain items won't use them. Just experiment with it :)
> 0 votes

---
Tags: java, architecture
---


# Question
Title: Why does adding LIBGDX "fadeIn" action to a table in a group make the whole stage fade in?
I'm trying to "*fadeIn*" a store "screen" which is really just an invisible group. I set the group to visible=true, set the alpha to 0 and then do a "*fadeIn*" on the group. The problem is that the whole stage goes black (my clear screen color) and then fades back in.

```
storeGroup.addAction(Actions.sequence(Actions.alpha(0), Actions.fadeIn(1)));

```

I even went as far as to make the Table within my StoreGroup accessible and adding the action to that, but the result is the same.

```
storeGroup.getTable().addAction(Actions.sequence(Actions.alpha(0), Actions.fadeIn(1)));

```

Essentially I just want my store group to fade in over whatever is currently displaying, but the fade in seems to apply to every other actor in my Stage, not JUST the one I'm adding it to.

Any help would be greatly appreciated, I've been working on this all morning and can't figure out why the "*fadeIn*" is applying to everything.

# Answer
The most likely problem is that in one of your actor's draw calls you are forgetting to reset the batch's color. This would cause alpha transparency to carry throughout your entire stage.

Make sure you always reset the batch's color at the end of a draw call where you manipulate it. Here is an example:

```
public void draw (Batch batch, float parentAlpha) {
    batch.setColor(this.getColor());
    // always make sure to only multiply by the parent alpha
    batch.getColor().a *= parentAlpha;

    // do your drawing

    batch.setColor(Color.WHITE); // reset the color
}

```
> 4 votes

# Answer
Same issue. It seems to be due to when the batch is flushed? Anyways basically every Actor sibling seems to also fade with it. Also will happen with any setColor as you might expect. Workaround I have done is just wrap it with a group.

Update: Actually last item in group seems to always have issue, even if wrapped. Need a flush? Or whatever resets the alpha, etc.

Update: StrongJoshua answered it. Due to having actor outside the group and needing to reset the batch color before using it.
> 0 votes

---
Tags: libgdx, scene2d
---


# Question
Title: moving object in unity from a point A to point B no matter what the original position of the object is
I'm moving a Game Object in unity from point A to point B no matter what the original position of the Game Object is.

Let us suppose that I have a Game Object at (0, 0, 0).

But I want to move that Game Object from (1, 1, 1) to (2, 2, 2).

How can I do this in C# ?

# Answer
Simply set the object's `Transform.position` to Vector3.Lerp(Vector3 A, Vector3 B, percent completion
> 2 votes

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


title: Incorrect Normal Matrix

text:
# Question
Title: Incorrect Normal Matrix
In my game engine I'm passing a normal matrix to my shaders like so:

```
Matrix3f normalMatrix = modelMatrix.invert().transpose();

```

However this is causing lighting to rotate with my object, producing a weird effect.

As I'm not performing any non-uniform scaling, I tried substituting `normalMatrix` for `mat3(modelMatrix)`, and that worked fine.

Also doing the transpose inverse on the GPU using `transpose(inverse(modelMatrix))` worked fine.

This has lead me to believe there is a bug in my `invert()` and `transpose()` functions.

According to some math websites, when the `modelMatrix` lacks any non-uniform scaling, calling `inverse().transpose()` on it will produce the exact same matrix.

However in my code the output is far from the same:

```
modelMatrix

0.25    0      0      2353.3474
0       0.25   0      0
0       0      0.25   51.86973
0       0      0      1

normalMatrix = new Matrix3f(modelMatrix).invert().transpose()

4.0 0.0 0.0
0.0 4.0 0.0
0.0 0.0 4.0

```

Would anyone be able to shed some light on this issue... (I don't want to just stick with `modelMatrix` because I do want to support non-uniform scaling in the future)

Here are some screenshots describing the issue:

These are two frames of my planet as it rotates. The light source appears to be rotating with it (it shouldn't be). Using the `modelMatrix` instead of `normalMatrix` solves the issue.

# Answer
> 1 votes
> According to some math websites, when the modelMatrix lacks any non-uniform scaling, calling `inverse().transpose()` on it will produce the exact same matrix.

This is slightly incorrect. Let's define *N* as *M.inverse().transpose()*. Then *N = M* is true only if *M* is a rotation matrix. If *M* has uniform scaling, the resulting matrix *N* will be different. However when transforming vertices with matrix *N*, the resulting vectors will have the same direction as with *M* but different magnitude. If you normalize the vectors after the transformation, the results will indeed be the same. With non-uniform scaling this is no longer enough. As a summary:

* If all you have is rotation, you don't need a separate normal matrix.
* If you have rotation and uniform scaling, you don't need the normal matrix either, but you need to normalize the transformed normals.
* If you have non-uniform scaling / shearing, you need to calculate normal matrix with the transpose of the inverse.

The output from your normal matrix calculation looks correct.

> Also doing the transpose inverse on the GPU using `transpose(inverse(normalMatrix))` worked fine.

Is this a typo? You are using the normal matrix calculation for the normalMatrix, which results in the original matrix.

Based on the given information it's hard to guess what is wrong. Note that normal matrix is 3x3 whereas your model matrix is 4x4. Try to reduce the model matrix to 3x3 as the first thing by discarding the *w* components. It's also possible that you are passing the normal matrix incorrectly to the GPU. You might need to add more information / screenshots to the question.

---
Tags: opengl, lighting
---


title: How many resources are too many?

text:
# Question
Title: How many resources are too many?
I don't know if this question is too broad but I am finally working on a game I want to release and I find that questions like: *"can I really add another 10 frames?", "Do I really need that animation?", "Can I add more background effects?"* etc. are always on my mind and limit my creativity.

I am trying to find an answer online without success, and as a hobby developer with no real training it is hard to know what is considered "too many" resources.

I suppose it differs depending on what you plan to release it for etc, but is there a general rule of thumb? I want to release for Android and ios.

For example I have a main character, and right now he has these animations:

```
 atlas = Assets.manager.get(Assets.runner, TextureAtlas.class);
        tallAnim = new Animation(1/10f, atlas.findRegion("runner1"), atlas.findRegion("runner2"), atlas.findRegion("runner3"), atlas.findRegion("runner4"));
        shortAnim = new Animation(1/10f, atlas.findRegion("short_runner1"), atlas.findRegion("short_runner2"), atlas.findRegion("short_runner3"), atlas.findRegion("short_runner4"));
        hitAnim = new Animation(1/10f, atlas.findRegion("runner_hit1"), atlas.findRegion("runner_hit2"));
        flyAnim = new Animation(1/10f, atlas.findRegion("runner_fly1"), atlas.findRegion("runner_fly2"));
        animation = tallAnim;

```

I want to add more but I am stopping my self because I don't know if this is too much. Right now he has 12 frames, and I am rendering a scrolling background and 2 different enemies (each with 3 frames) and a few other objects. **Do I need to start limiting my game or is it hard to reach a point of "too much"?**

# Answer
> 0 votes
No, it is not too hard to reach the point of too much. The problem here is that you never know what devices your users will have.

But, don't start limiting your game just to start limiting it. You should know what and why you are doing and what goal you want to achieve.

---

At first, you should care about the amounts of RAM and VRAM on a target device. All your resources that should reside in the RAM/VRAM simultaneously should fit into that amounts. And don't forget that:

* The images could be decompressed on a device unless you use special hardware compression.
* Your program itself uses some memory.
* Other programs running in background use some memory.
* OS uses some memory too.

Of course, old devices mostly don't have enough memory to handle modern games, so you should choose a minimal device for your game. Next step is to find out the amounts of RAM/VRAM available on that device and how much memory is used by the OS. The rest is *mostly* yours.

The best idea is to buy such device and test the game on it.

---

Another thing you should care about is the size of the game bundle. Two problems may appear here:

* Stores may have some restrictions for large bundles.
* It is wise to save the user traffic and disk space.

This is less important than fitting into RAM/VRAM, of course.

---

Finally, there is the CPU usage. It is really difficult to predict how fast a game would run on a particular device, so, again, you need to choose a minimal device(s) (with the worstest CPU and GPU) and test the game on it.

---
Tags: game-design, assets, resource-management
---


title: Proper use of texture units

text:
# Question
Title: Proper use of texture units
I'm a beginner using OpenGL v3.3 on C# with SharpGL. I have a simple scene with a Skybox and some OBJ Models. Both the skybox and models have multiple textures. Currently what I do is that I load all the textures used in the scene into different texture units at once program launch and then while rendering each element in the scene I just change a uniform variable to reflect the correct texture unit and render the vertices. Doing this could get me into trouble if there are more textures in my scene than texture units on the GPU, so I'm not sure if this is the right approach.

I would like to know what the standard practice for such a scenario. Do you just (re)load the texture for each element into say fixed texture unit 0 on every draw call or what?

# Answer
I'll post the answer as the question is related to my previous misunderstanding of how textures and texture units work.

1. You can load as many Textures as you want into the OpenGL memory, all assigned to Texture Unit #0. OpenGL always returns a new handle for each of these textures.
2. When applying the texture, you just have to bind to the appropriate handle via `glBindTexture()` and set the sampler to 0
3. For most cases you don't need to use the other texture units, it's only really required when you want to blend more than one texture on the fly.
> 3 votes

# Answer
are you drawing your texture in the back buffer for updates but still storing the texture?

if the texture was destroyed from memory thin it will have to be reloaded in to the back buffer

are you changing the texture to a new texture?

draw the texture in to the back buffer so on next update there texture will update thin remove old texture from memory
> 0 votes

---
Tags: textures
---


# Question
Title: How to implement "bullet time" in a multiplayer game?
I have never seen such a feature before, but it should provide an interesting gameplay opportunity.

So yes, in a multiplayer/real-time environment (imagine FPS), how could I implement a slow motion/bullet time effect?

Something like an illusion for the player that's currently slo-mo'ed. So everybody sees him "real-time", but he sees everything slowed down.

### Update

A sidenote: keep in mind that a FPS game has to be balanced in order for it to be fun. So yes, this bullet time feature has to be solid, giving a small advantage to the "player", while not taking away from other players.

Plus, there is a possibility that two players could activate their bullet time at the same time.

### Furthermore:

I'm going to implement this in the future no matter what it takes. And, the idea is to build a whole new game engine for all this. If that gives new options, I'm more then interested in hearing the ideas.

Meanwhile, here with my team we're thinking about this too, when our theory will be crafted, I'm going to share it here.

~~Is this even possible?~~ So, the question on "is this even possible" has been answered, now it's time to find the best solution.

I'm keeping the "answer" until something exceptionally good comes up, like a prototype theory with something close to working pseudo code.

### What the physicists and philosophers say:

The links are for you interest, because topics are closed.

https://physics.stackexchange.com/questions/17118/time-traveling-and-time-dilation-within-a-multiplayer-videogame

https://philosophy.stackexchange.com/questions/1704/seeing-everything-in-slow-motion-but-being-real-time

### The conditions I thought about when writing the question on physics site (copied):

1. The player under the effects of slow motion has an advantage to make more precise actions (shooting, movement etc.), due to seeing everything in a much slower pace.
2. His actions should affect the other players in real-time.
3. The players looking upon our affected player, do not see any difference, except they can experience the actions he have done (like, player gets shot/affected dodges a rocket).
4. When the player comes out of this effect, he simply continues in the same pace as usual. (If this is not possible, then I guess he'll have to suffer until the time gets synced back)

### References on bullet time (slow motion):

Sadly, most of implementations are single-player only

http://www.gamesradar.com/a-videogame-history-of-bullet-time/

# Answer
> 23 votes
It has been done before. :) Check out the specialists, a half life mod that has two different bullet time powerups.

**EDIT to include zzzzbov's info below**

The way bullet time worked in "The Specialists" from a gameplay perspective was that the player could get powerups that would give limited amounts of "bullet time". When used, a bubble around the player would have its physics slowed down.

Players far away would move at normal speed, but anything in the bubble (bullets, players, explosions) would slow down. The player that used the power-up would move slightly faster, allowing them to run away or use stunts to dodge bullets.

Anyone else caught in the "bullet-time" bubble still has the advantage of being able to see what's about to happen, but the relative speed difference between a caught player and bullets remains the same, so that the ability to react is practically nonexistent.

# Answer
> 12 votes
I can't think of any game that has bullet time in single player that transitioned it successfully to multiplayer in any meaningful way. There might be a few of them that solved it by speeding up the player using it, but that kind of defeats the point.

Bullet time exists because you want to make the player feel like a badass. You're giving the player a seemingly unfair advantage through simulating higher level perception. The end result of this is that players can aim while doing cool things like jumping out from cover and so forth. If you just sped up the player while they have bullet time enabled then you give them less time to react, which is the opposite of what you want.

In a synchronous multiplayer environment, there really isn't any solution for user-activated "time slows down" that simulates the feeling that comes from using it in a single player environment. If time itself were slowed, then everybody's perception goes up. Especially in a PC game where mouse aiming is generally instantly, everybody would get the benefit of slower moving targets.

Now if you were dead set on this, my suggestion would be to, instead of making it a player-activated feature, make it sort of an encounter "state". Think like a John Woo movie where it's the good guy vs the bad guy and everything seems to slow down as they're shooting at each other. So when an "encounter" starts, turn on slo-mo and you can get some interesting effects. Guys jumping around and stuff ricocheting from missed bullet hits floating in mid air, and all that stuff. Of course, this would only really work for a 1 on 1 game. You wouldn't get the one-sided benefit of the bullet time like in a single player game, but it might be an interesting play experience.

# Answer
> 8 votes
# General Thoughts

This is a problem that is best described using general relativity - take for instance the fact that you can see the effects of bullet time by just looking through your telescope at a satellite (the cause of the infamous neutrino travelling faster than light problem) - equations that are solvable exist under these conditions; meaning it's completely possible.

Your game will need to be able to handle separate frames of reference - as far as I know the net effect of this would be ('player' being the person with bullet time active):

* The people seeing the player would see them move extremely quickly.
* The player would see people move extremely slowly.
* The player would be moving into the past/future in reference to everyone else.

Luckily for you this means that a player in bullet time does have an advantage over everyone else; they can't possibly aim at him - however it wouldn't be convincing because the average person would expect to see no discernible difference when observing time dilation.

I strongly recommend you post this on physics (indicate it is a game, but you need real theoretical knowledge) and ask for ideas how you would approximate the effect in a concurrent simulation.

One possible solution I would look at is having the world catch up with the player (as he has moved into the future) by having everyone experience a progressive amount (far less than the actual bullet time) of bullet time depending on far behind (in time) they are. This way you could approximate time differences without actually having to deal with storing past state etc. *You would need some way to explain this effect, 'time rebound' or something, because it's not physically correct.*

Another idea is to abuse the most basic physics equations (`s = d/t`), when a player goes into bullet time everything becomes smaller - if you halve the size of everything from his perspective but keep his speed the same according to his original frame of reference, (effectively double it) the equation will still balance. Warp drive sequences in space films use this space dilation to portray the effect - so people are used to seeing it.

# Actual Solution

I have given this even further thought. If you look at how the Steamworks network system works (*does someone have a link?*) the server is constantly ahead in time by a certain amount; and each client knows about the 'next' frame that it needs to interpolate to.

Let's say for instance that the server is 20ms ahead of all the players. When a player enters bullet time change his update interval to 40ms (his simulation will run at 40ms time-steps and the server will queue his actions 40ms into the future) - which will basically push into the future in reference to other players: in addition to making him move faster from their reference and making them move slower from his. Once he leaves bullet time give everyone else a 5ms advantage over him so that they can play 'catch up' (this is your `time rebound`, coincidentally smart players will bullet time during these catch-up periods). It might look a little better if you map a parabola to his time step - this will make things slow down, stop and then gradually speed up again.

*Disclaimer: I am no physicist, but I do have a workable knowledge of relativity.*

# Answer
> 5 votes
I wanted to add my $0.02, as I implemented a prototype bullet-time mode that worked in multiplayer games for Heroes Over Europe.

In single-player, a button press at the right moment would slow down time, and zoom in on your intended target. I didn't want to slow time down globally in multiplayer to replicate the feature (as the game was to support 16 simultaneous players!), so I used a "bubble" method.

Specifically, when bullet-time mode was triggered, a sphere was created around the target airplane. The rate of passage of time changed depending the distance to the sphere's centre; time degraded linearly from its surface to a minimum value somewhere near the centre. The rate also changed as a function of how long the sphere had existed, and how long the sphere had left before it "evaporated".

This was synchronised across machines by sending a packet which defined a *future* start time for the bubble; this allowed the effect to stay in sync in spite of latency. (Similarly, when the effect was to end early, a packet would declare the future time at which it was to end.)

The rate of passage of time was always functionally defined: given a sphere's definition, the current time and a position, it was possible to determine how fast time was flowing.

To make the effect work, several game systems had to be adapted to this "functional" definition of time. Airplanes, bullets, missiles and other effects each used an individual `dt` that was worked out by calling the appropriate function. Most of the work in getting the prototype working was spent here.

The result worked reasonably well: a player targeted by bullet-time would noticeably slow down, and have a (small) chance to manoeuvre their way out of their aggressor's cross-hairs and away from a hail of slow-motion bullets. Nearby players could see planes and bullets dodging one another in slow motion, but were otherwise unaffected.

Note that the triggering player was also slowed, but wasn't strictly disadvantaged by it: they had a zoomed-in view of their target and could affect one-shot kills on their prey. Another player could attempt to kill you (or kill steal!) in this state, but their plane (and their bullets) would be affected when entering the bubble, giving you time to escape.

Unfortunately, while it worked, we never had time to complete and polish the feature for multiplayer, so it was dropped. (Single player still kept the feature, as "Ace Kill".)

# Answer
> 2 votes
Not really bullet time, but could be fun:

What about something similar to the way Braid does the time-slowing down thing? I.e. the closer to the person who is experiencing the bullet time, the slower things go... and if you're outside of the sphere of influence, time flows normally.

... for example, if Player A goes bullet time, it puts up a gradated sphere of "slow time" around him so he can aim properly, but not necessarily move around any faster - then Player B firing bullets at him would have to over-predict where the bullet will hit, as it will slow down the closer it gets to him.

Although, the more I think about this, the less I think it would work, because it could just make Player A an easy target (as his head would slow down?) - but it would be interesting to see it in 3D anyway.

# Answer
> 2 votes
*I know this is an old question but I had a hard time not mentioning the issue with most of the answers dealing with relativity*

Implemented with the effects as described in the question, bullet time in multiplayer is not possible.

The reason for with is how relativity works; some of you here have mentioned it and obviously understand relativity, but the issue is that your models are set up incorrectly.

Many people have used "Player A's reference vs Player B's" in your answers but sadly neither of those things really exist. Yes you have players, maybe even many of them, and yes they can control and interact with their world and have their own perspective of the game, but perspective is not a point of reference in time: it's just an X Y Z space projected into the X Y plane.

There is only a single point of reference of time and that is the server (or host). There is only one view of the physical state of the world and therefore only one reference point. What players see on their screen are different graphical views of the same physical simulation.

To have one player view a simulation run at one speed and another view the same simulation at another speed and not have a desync just isn't possible. Somewhere, something has to give.

Any effort to have multiple simulations or have the server run ahead of the clients just doesn't make sense. The effect as described in the post just can't be done without either forcing the single reference point or letting thinks become desynced and telling players that their actions didn't really happen after the fact.

I think the best solution is similar to one already given which is to have a braid like effect where your speed is changed in a bubble around the player. That being said, the player would not slow down and the bubble would always be positioned and moved with him at the centre. This makes it so that the player moves at full speed while those closest to him feel slowed down. He gets his power up advantage and people far from that area don't feel effect. Those who are close are slowed down but it would be obvious that somebody is using the power up (I would suggest highlighting the player somehow who is using it so that opposing players fully understand what is happening and why).

# Answer
> 1 votes
It would be very awkward. Without even looking at the problem of time dilation, imagine that you're the player who just spent 4 seconds in bullet time, whereas everyone else in the game spent 2 seconds in real time. Since the same time passed for everyone in reality, you'd have to "gain back" those two seconds in-game somehow. So at some point you'd need to "skip" 2 seconds of game time, or spend a bit of time running *faster* than normal, or something else that would probably make the bullet time kind of a waste.

Plus, there's the whole bit about having to send what you do at at 2 seconds in your time back in time 1 second to everyone else.

# Answer
> 1 votes
Throw mini quick time-like events at the player to dodge bullets or auto-track enemy targets, while making your player's movements look blurry or "phased" to the other players (so they don't scratch their heads as to why their bullets aren't hitting). That seems like the simplest, most practical translation you could make for multiplayer.

Any other solution involves some physical element of the game being changed for one or more players that doesn't apply parallel for the others, I would imagine.

# Answer
> 0 votes
Just slow everyone else down execpt the player experiancing bullet time. You could do this by just decreasing their mouse sensitivty.

# Answer
> 0 votes
Let's say we have player A in bullet time and player B in real time. And they do the following from player B's point of view:

* Time 0s - Player A activated bullet time
* Time 2s - Player A shoots at player B
* Time 3s - Player B shoots at player A

Now from player A's point of view this will take twice as long - since the world is moving slower for him:

* Time 0s - Player A activated bullet time
* Time 4s - Player A shoots at player B
* Time 6s - Player B shoots at player A

Finally the server has the following events coming into it:

* Time 0s - Player A activates bullet time
* Time 3s - Player B shoots at player A (B initiates this action so it follows his timeline)
* Time 4s - Player A shoots at player B (A initiates this action)

So, we have two initial problems. The first is that A is now 3 seconds of game time behind everyone else. This could be an interesting game mechanic if you had a concept that meant he had to pay this debt back. Imagine a cover based shooter where you can activate bullet time to break across open ground, but once you are safely under cover you have to stand still until the rest of the world catches up with you (the three seconds of time that you missed is replayed)

The second problem is much larger. The server needs to reorganise the events chronologically for each player and figure out the outcome. Firstly B shoots at A - this happens three seconds into the game, and A sees it at 6 seconds - no problem so far. At 4 seconds player A shoots at B. In B's timeline this happened two seconds ago. So what do we do with the two seconds of gameplay that has already passed for him including his shot at A?

We could nullify it - basically say "I know player B *thinks* he shot that guy, but it turns out he was already dead so let's pretend that never happened" This would be a crappy experience, very similar to lag, but would solve the problem.

We could make both timelines gospel - use the servers point of view as the whole truth and worry about each persons timeline independently. At 3 seconds B shots at A and kills him. At 4 seconds A shoots at B and kills him. Both players die from shots that they didn't see. Doesn't sound good, but maybe there is a good way of doing this after giving all the players a brief course in the crazy world of relativity.

We could have a pseudo-realtime system - a turn based game where you plan your moves first and then trigger a simultaneous calculation of events. A good solution that fixes all the problems other than it not being the type of game that you want to write.

Long story short I don't think there is a good way to implement bullet time treating it in the classical sense the effect being on the person using it - *they* move faster, *they* see the world as slower, everyone else carries on as normal. If we reverse it and everyone else gets thrust into the bullet-timer's point of view and see themselves as moving slower and their controls become sluggish then it all happens in sync and there are no problems. But is that really bullet time? While it might look like it to an outside observer (and in match replays) neither of the participants would get the effect they expect.

# Answer
> -1 votes
F.E.A.R. had bullet time in multiplayer, but it applied to the whole team and it slowed down everyone on the other team.

Bullet time in real-time multiplayer without actually slowing down the others would desynchronize the clients, the slow-motion player would be reacting to events the other players did long ago while they would be reacting to current events.

# Answer
> -1 votes
No it is not possible. Imagine one player flips to slow motion, what would the other players see? You'd want them to see the bullet time player moving normally but having lightning reflexes, right? But unfortunately everyone playing the game will be playing the game in the same real-time. Therefore the only way of doing it would be to slow the whole game down, getting rid of any advantage it brings as everyone would be in bullet time. Also it would be fairly annoying to have the game slow down all the time when anyone pushed that button.

There are work arounds which would result in players having a similar advantage (one of being able to move faster etc) by for example slowing everyone ELSE down and letting you move normally (then in a replay you could speed them to normal and you'd be reacting fast) but I don't think that's really what you want.

# Answer
> -2 votes
Perhaps you should arrange the equipment necessary to shoot the player at the PC who triggered bullet-time into space at near light-speed velocities.

This would solve all of your problems but may generate higher ping/latency.

# Answer
> -3 votes
well it wouldn't be a problem if they all move slower than usual but not too slow and the one who activates it gets to move faster like submerging the whole game underwater or taking it to outerspace with the one activating moving as peacefully as ever

---
Tags: game-design, multiplayer, first-person-shooter
---


# Question
Title: How can I calculate the orthographic projection needed to encompass an object with arbitrary rotation?
So I need to set up the dimensions of a orthographic projection that will encompass the entirety of a bounding box when viewed from any arbitrary position.

That's an eye (programmer art); and the vertical line next to it is my view. How can I work out what the size of this view should be so that it encompasses the furthest corners of my rotated rectangle (from the viewports perspective)?

I want to do this in 3D obviously, I thought 2D would explain it better.

So far, I've considered that if I have:

1. The coordinates of each corner of my bounding box from it's model matrix perspective
2. With this, I could easily work out what the furthest ones are IF I was able to multiply it with my view matrix. However, it's the view matrix I'm trying to calculate...

# Answer
> 1 votes
You can solve this by looking at the typical procedure followed when rendering a game world. When you render a 3D object, you typically apply three transformations:

---

# 1. Model Transformation (*Model coordinates* to *World coordinates*)

This tranformation is applied to the model itself, disregarding anything else in the scene. It is used to scale, rotate (around its own center axis) and finally translate the object to its desired location. The resulting transformation will move the model to its desired location in the world. Therefore the coordinates are called world coordinates.

---

# 2. View Transformation (*World coordinates* to *Camera coordinates*)

You typically want to view your world from a specific position, at a specific angle. The metaphor of a camera is often used for this. Therefore, a view transform is performed, to transform all objects in your game world as they would appear when viewed through the lens of a specific camera. It is interesting to note, that you are actually **moving your objects** with respect to a camera looking at the origin (0, 0, 0). You are **not moving a camera** through the world. Looking through a camera which is at position (5, 0, 0) is the equivalent of looking through a camera at position (0, 0, 0), after displacing all objects in your world by (-5, 0, 0). In the same way, you don't rotate your camera, but you rotate the entire world around your camera.

---

# 3. Projection Transformation (*Camera coordinates* to *Screen coordinates*)

The final step is to apply a projection. The projection specifies **how** (*parallel* or *converging projectors*) and **what volume** (*bounds of the view* and/or *field of view*). Using parallel projectors means that no foreshortening is applied. This means that objects far away from the camera will appear equal in size as compared to nearby objects. An orthographic projection is an example of this. Converging projectors will cause distant objects to appear smaller than nearby ones, creating the illusion of perspective. The first approach is useful in applications where accuracy is key, whereas the latter is useful when realism is desired.

The viewing volume is also specified in this transformation. For example in an orthographic projection along the positive x-axis (after camera rotations have been applied via the view transformation), you would specify this is terms of *left (z-min)*, *right (z-max)*, *bottom (y-min)*, *top (y-max)*, *near (x-min)* and *far (x-max)*. For a perspective projection, this is specified as a horizontal and vertical field of view along with near and far clipping planes.

---

# How to find the bounds of your ortho view

From the above, you can see that deciding what volume is viewed, happens in the projection transformation. Depending on how you specified your camera, you can retrieve the bounds by looking at the *Camera coordinates*. Assuming your camera looks along the positive x-axis, simply use the minimum and maximum y and z values of the bounding box in camera coordinates.

To construct your view matrix, note that it is a concatenation of rotation and translation transforms. You are trying to calculate the transform that would place your camera in the origin, looking along the positive x-axis (can be another axis if you desire so).

1. First find the **translation** that would place your camera in the origin. For example, if your camera is located at (5, 10, 15), this transformation would be (-5, -10, -15).
2. Then find the **rotation** that would make your camera look at the positive x-axis. For example if the camera is looking 15 degrees to the left, and 25 degrees downward, your transformation would be 15 degrees to the right and 25 degrees upward. Be careful with the order of the rotations here. It depends on how you defined the angles your camera (typically you want to rotate around the z-axis first (= looking up/down) and around the y-axis (up-vector) next (= looking around left and right). To transform your camera to the origin, you need to apply these in reverse.

---

I may have made some mistakes concerning the terminology of the transformations and the coordinate systems, but this should give you the general idea.

# Answer
> 0 votes
If you consider all possible orientations of a bounding box, the corners are on the surface of a bounding sphere. If you fit your view to the extents of that bounding sphere, you're guaranteed that your box will always fit.

---
Tags: matrix, vector, viewport
---


# Question
Title: XNA - Darkening background and drawing something on top
In a game a group of friends and I are working on using XNA, we wanted to create an effect where we could darken the screen and draw something else on top of the darkened portion. For example, we have a title screen that is drawn as a background sprite, a logo, a few buttons, and a lot of particle effects (all separate Texture2D's), but when you select the "Exit" button, the entire title screen darkens, and two (undarkened) buttons are drawn over-top ("exit" and "cancel" buttons).

Initially, we were going to do this by having two separate render targets, one for the title screen, and one for the yes and no buttons. Then, when we wanted to display the topmost render target, we darkened the render target that the title screen was drawn to, and then draw the new render target on top. The problem with this is that the second render target is filled with black pixels that simply get drawn over the background, blocking it out completely.

We have two ideas to fix this. The first idea is to draw the second render target on top of the first using `BlendState.Additive`, so that the black pixels are simply added to the background instead of drawn over-top. The problem with this is that it makes the other buttons look weird, since they're being drawn over top other things on the title screen. The second idea was to manually set every black pixel in the second render target to `Color.Transparent`, but we're not sure how efficient that is.

Any ideas on how we could achieve this effect?

# Answer
> 1 votes
Why not draw a semi-transparent black sprite in between the background and the yes and no buttons? For example something like this:

If you had a scene that looked like this:

Then you could simply draw the semitransparent mask on top and have it look like this:

Then all you'd have to do is draw the buttons *on top of the mask* while the rest of the scene is drawn *below the mask*.

Hope this helps!

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


# Question
Title: What causes this graphics quality difference between WebGL Build and Unity 5 Editor?
The Editor version and WebGL version of my Minesweeper clone have some graphics quality differences. I chose 'Fast' option when building this deployment.

Is this the difference between 'Fast' and 'Fastest' options of Optimization Level in Build Settings, meaning that if I choose the 'Fastest' option, the WebGL deployment will be the same as Editor version, unlike below? If not, why this happens?

# Answer
Because the default settings on the web player are low and on the unity editor are good.

You can go to Edit \> Project Settings \> Quality, the default settings checkbox is in green light, you can change it in row Default and pressing the dropdown arrow.
> 3 votes

---
Tags: unity, graphics, lighting, deployment
---


# Question
Title: Why does my character stop a little before landing on the ground?
I made a little game with side-scrolling and a box (the player) jumping across the level. The simple physics are almost done, but I have two problem with the way things behave:

* On landing, the box takes a little time to reach the floor
* When the box hit a roof, there is always a little space between it and the object.

Here is my collision code (in the player's Step Event):

```
myGravity = 0.5;
if (vspeed > 10)  vspeed = 10;

speedAir = abs(vspeed+1);

//ON_FLOOR = !(place_free(x, y + speedAir));
ON_AIR = place_free(x, y + speedAir);

FREE_RIGHT = place_free(x + speedScreen, y);
FREE_UP = place_free(x, y - speedAir);

KEY_UP = keyboard_check(vk_up);
KEY_LEFT = keyboard_check(vk_left);
KEY_RIGHT = keyboard_check(vk_right);
KEY_FIRE = keyboard_check(vk_space);

/* JUMP */
if ON_AIR
{
    gravity = myGravity;
    gravity_direction = 270;

    if !(FREE_UP)
    {
        vspeed = 0;
    }
}

else // if ON_FLOOR
{
    gravity = 0;
    gravity_direction = 270;
    vspeed = 0;

    // JUMP
    if KEY_UP & FREE_UP
    {
        vspeed = -10;
    }
}

/* LATERAL */
if (FREE_RIGHT)
{
    x += speedScreen; // screen side-scrolling
}

```

How can I do this correctly?

# Answer
> 3 votes
## The problem

I think the main flaw is that you're checking *if the object is in the air* using the code `place_free(x, y + speedAir)`. That's effectively like this:

Imagine your object is shaped like that blue J-tetromino and the ghost version of it represents its position + its speed; where it will be next frame. The yellow is a floor.

At the first two speeds, it's correctly determined as being in the air. In the third, the `place_free` check fails because the ghost intersects something, and so `ON_AIR == false` even though the object is nowhere near the ground!

## The fix

It might be worth reading up on collision detection (Metanet's tutorial on separating axis theorem is pretty great), but here's one simple-ish method: To make sure the character stops exactly on the ground, you could first of all check only for `place_free(x, y)`, and use the object's position relative to the ground object to calculate how much they intersect by. Then just move the object out by that amount.

---
Tags: collision-detection, physics, platformer, game-maker
---


# Question
Title: In Box2D, how do I create an infinitely oscillating spring?
How do I create an ideal spring that can oscillate indefinitely using Box2D?

A `b2DistanceJoint` works almost perfectly, but it eventually slows to a stop, even with damping set to 0. I think it is because `b2DistanceJoint` is not meant for creating springs, but for preserving the distance between two bodies by correction the violated distance with a spring like behaviour. Hence, it should have a damping to eventually bring back the bodies to initial state and stop at some point.

# Answer
> 1 votes
If you want well defined behavior, you should consider perpetuating the oscillations yourself. I will assume, for simplicity, that we are working with a simple spring-mass-damper system where the spring and damper behavior is encapsulated in a `b2DistanceJoint`.

The basic idea is to evaluate the total energy (kinetic + potential) of the system and apply a force if this is below a certain threshold. The total energy of the system at any instant is given by:

where `m` is the mass of the body at the end of the spring, `k` is the spring coefficient, and `x` is the displacement from the rest length. `k` can be related to the frequency of the distance joint through the equation:

Plugging this in and simplifying gives:

All of the variables on the right hand side can be evaluated (with the help of box2d). Once you have calculated the energy, compare it with a reasonable threshold value. If it exceeds that threshold, then your spring is under significant tension or compression and/or the mass has a high velocity; in this case we don't need to do anything. If the energy falls below the threshold, then apply some small force `dF` along the spring axis, in the direction that the mass is currently moving.

Here's how I might implement it (in c++)

```
/* ... */

b2Body springBody;
b2DistanceJoint spring;
double restLength;
double Ethresh;          //Threshold energy. Set to reasonable value.
double dFM;              //Small force. Set to reasonable value.

// in time loop

/* ... */

/* Assign spring body and distance joint */

double m = springBody.GetMass();
b2Vec2 vel = springBody.GetLinearVelocity();
double vmag = vel.Length();            //Assuming the body is traveling along the spring axis
double w = spring.GetFrequency();
double x = spring.GetLength() - restLength;
double E = 0.5*m*(vmag*vmag + w*w*x*x);

if(E < Ethresh){
    b2Vec2 dF = (vel/vmag)*dFM;
    springBody.applyForce(dF);
}

/* ... */

```

If you have a more complicated system (e.g. distance joints attached to bodies which are joined to tertiary bodies, etc...) this will of course invalidate the theory, but I believe this approach will produce visually believable results for many different setups.

---
Tags: box2d, physics, spring
---


# Question
Title: Unity forward vector flips when upside down. Mario Galaxy style gravity, bad rotation?
This is a question that I think is best to explain visually, so I will do my best to be succinct here.

**What I am trying to do:**

Allow the player to run about a world that is spherical, not a flat object. The intended result is going to be much like navigating a planet in super mario galaxy.

**My attempt at solving this problem:**

Conceptually it is simple. I create a vector from the player to the origin of the planet/world, and use it as the gravity vector. This works great, I know the direction I need to fall towards.

**The problem:**

When trying to use unity's transform.forward vector, everything is fine until I move slightly off to the side and attempt to circle the planet. At about the south pole, the forward vector points to random places. I believe this is because of how unity calculates the forward vector, but I don't know how it is done so I can't say.

Should I attempt to calculate it myself? Or should I just store a matrix for my object and do everything manually?

Below are images that hopefully shed some light.

In this image, the forward vector (red ray) points correctly in front. This is at the starting position of the object. The blue ray is the vector toward the planet center

After circling to the bottom of the planet, I just need to move slightly to the side, and the forward vector begins to circle about the blue vector

EDIT for code:

BaseObject class for objects that will react to planet gravity

```
public class BaseObject : MonoBehaviour {

    public GameObject planet;
    private float gravityConstant;

    public Vector3 TowardOrigin { get; set; }

    void Awake () {
        /// Store the gravity constant
        gravityConstant = Physics.gravity.magnitude;
    }

    void FixedUpdate()
    {
        /// Manually set the force of gravity to point towards the center of the planet
        TowardOrigin = transform.position - planet.transform.position;
        TowardOrigin.Normalize();
        Physics.gravity = -gravityConstant * TowardOrigin;
        transform.up = TowardOrigin;

        ChildFixedUpdate();
    }

    /// <summary>
    /// To be inherited and overriden by child objects
    /// </summary>
    public virtual void ChildFixedUpdate() { }
}

```

PlayerController class:

```
public class PlayerController : BaseObject {
    public float speed;
    Rigidbody body;

    void Start()
    {
        body = GetComponent<Rigidbody>();
    }

    public override void ChildFixedUpdate()
    {
        if (Input.GetAxis("Vertical") != 0 || Input.GetAxis("Horizontal") != 0)
        {
            Vector3 forwardMomentum = (transform.forward) * (Input.GetAxis("Vertical") * speed);
            Vector3 sideMomentum = (transform.right) * (Input.GetAxis("Horizontal") * speed);

            body.AddForce(forwardMomentum);
            body.AddForce(sideMomentum);
        }
        else
        {
            body.velocity = Vector3.zero;
        }

    }
}

```

# Answer
> 2 votes
Your problem is `transform.up = TowardOrigin;`. I didn't know you could actually *set* transform.up until now, since it's actually a summary of a more complex state of the object -- its rotation. Setting it tells Unity to orient your object along that axis, but doesn't tell Unity to keep transform.forward as close as possible to what it used to be.

You're probably better off using Transform.LookAt, which doesn't sound intuitive at first, but hear me out. It has an optional **up** parameter. So in BaseObject.FixedUpdate, in order to do this without having to worry about tricky maths myself, I would first figure out a point in front of the character using its current transform.forward. Then I'd use transform.LookAt to look towards that position, passing it TowardOrigin as the up vector.

So it'd be something like:

```
var frontPos = transform.position + transform.forward;
transform.LookAt(frontPos, TowardOrigin);

```

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


title: Libgdx distorted texture size

text:
# Question
Title: Libgdx distorted texture size
I'm just starting to learn LibGDX and have been having some troubles getting my world size to match with my texture size and box2d bodies. I have a texture 64x64 that I am trying to display but it takes up half of the window, both on desktop and android. I've tried scaling the texture down also. I am wondering if this has anything to do with my two variables FRUSTUM\_WIDTH and FRUSTUM\_HEIGHT being used in the creation of my camera.

```
  int FRUSTUM_WIDTH = 8;
int FRUSTUM_HEIGHT = 15;
World world;
Box2DDebugRenderer debugRenderer;

@Override
public void create () {
    batch = new SpriteBatch();
    img = new Texture("player.png");

    player = new Sprite(img);
    player.setPosition(5, 5);
    //player.scale(.8f);

    camera = new OrthographicCamera(FRUSTUM_WIDTH, FRUSTUM_HEIGHT);
    camera.position.set(FRUSTUM_WIDTH / 2, FRUSTUM_HEIGHT / 2, 0);

    world = new World(new Vector2(0, -50), true);
    debugRenderer = new Box2DDebugRenderer();

    setUpBox2D();

}

private void setUpBox2D()
{
    BodyDef bodyDef = new BodyDef();
    bodyDef.type = BodyDef.BodyType.DynamicBody;

    bodyDef.position.set(4, 10);

    Body body = world.createBody(bodyDef);

    CircleShape circle = new CircleShape();
    circle.setRadius(1);

    FixtureDef fixtureDef = new FixtureDef();
    fixtureDef.shape = circle;
    fixtureDef.density = 0.1f;
    fixtureDef.friction = 0.1f;
    fixtureDef.restitution = 0.5f;

    Fixture fixture = body.createFixture(fixtureDef);

    BodyDef groundBodyDef = new BodyDef();

    groundBodyDef.position.set(new Vector2(0, 1));

    Body groundBody = world.createBody(groundBodyDef);

    PolygonShape groundBox = new PolygonShape();

    groundBox.setAsBox(camera.viewportWidth, 1.0f);
    groundBody.createFixture(groundBox, 0);
}
@Override
public void render () {
    Gdx.gl.glClearColor(0, 0, 0, 1);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
    drawScene();
    updateScene();
}

private void drawScene()
{
    debugRenderer.render(world, camera.combined);
    camera.update();
    batch.setProjectionMatrix(camera.combined);
    batch.begin();
    player.draw(batch);
    batch.end();
    world.step(1/60f, 6, 2);
}
private  void updateScene()
{

}

```

I do have a resize method but it is currently empty.

The window size is 480 by 800. I looked at a game called Super Jump on Github which helped fix my camera issue, but I am still having issues with the giant textures

# Answer
What you are currently referring to as `FRUSTUM_WIDTH, FRUSTUM_HEIGHT` is actually the world width and height for the camera. This means that, across your application window, `8` world units in width and `12` world units in height will be displayed.

Since you are not changing the size of your Sprite, it will have the texture's width and height, so it will be drawn at a size of 64x64 world units. This means you need to set the Sprite's size to fit into the world. If you want it to be drawn at 64x64px then you need to do some math (`spriteWidth / (windowWidth / worldWidth)`) to convert the Sprite's pixel size to world unit size.

Also, after you manipulate any of the camera's attributes (like its position) you need to call `camera.update()`.

Read the OrthographicCamera wiki page for more information.
> 0 votes

---
Tags: java, libgdx
---


title: Programmer career roadmap

text:
# Question
Title: Programmer career roadmap
this is my first post on this SE, and I have noticed the large numbers of closed/downvoted career-related questions, so I will try to ask in a fashion most gingerly.

What would the career roadmap for a video game programmer be like? There seems to be a consensus that the video game industry is not so structured, and a roadmap would not be useful at all.

To be more specific, I understand the difference between role and title, IE there may be one person with the title "Engine Programmer", but he may do other things, and other people may do his role as well.

How would I chart out my career road map? Would it be simply moving from a junior programmer in a certain field, to a more senior position on that field, or are there certain fields which are inherently more senior than others?

Notes:

* I am currently studying for a degree in video game programming
* This is for an assignment, and I am told to consult real developers to be able to better perform.

# Answer
I recommend you not getting a degree in video game development, but in Computer Science or Software Engineering instead (The name sounds a bit more sophisticated to me) . Programming video games is more of a hobby because it's *fun*. Having to develop things with timelines may dull out how interesting it can be. If you believe you can handle full time game programming (If that's what your doing), then go ahead.

As for a "road map", make sure you read a *lot*. Sometimes, answers can become perplexing online and a good old fashioned book can get the job done. Here's a list (in order) of what I personally see the game developer road:

**ROAD MAP**

* Learn to program neatly and efficiently - Doing Eulers and Katas should help
* Understand how a game loop works
* Practice rendering/velocity and choose a development tool - Something Low Leveled like OpenGL or higher leveled like Unity (You should understand how low level things work later on)
* Learn game development techniques and how math applies to game dev(A lof of good books that teach it)
* Between all of this, practice *little* DEMOS (don't think to big. You almost always end up confused when attempting big projects too early)
* Join a community - Places like here let's you learn from others as well as contribute to help others
* Enjoy what you're doing - Again, starting too big can cause frustration from how fun game development is :D
> 4 votes

# Answer
As time goes on and game Dev gets more complex, specialized roles are getting deeper and the barrier for entry gets higher. In older days a person might work on both rendering and network code, but these days you likely have a specialist for each if not a team of specialists. However I've heard from many employers that what they are often looking for is someone who is a specialist in everything, that can change hats and do good work in many different areas as the needs of the team change. All this said, I think its important to become familiar with everything you can, never stop learning, and try to get experience being a specialist in every area that you can, and every area that you have any interest in. I think entering as a gameplay generalist (or other entry level positions) is a good way in, and then as time goes on you will have to start carving your own path based on your personal goals.
> 2 votes

# Answer
@Positive x Squared pretty much said it, I just wanted to add my 2c of personal experience. If you're in school right now, we are probably not too far apart in age (I'm 26 now)

I graduated in Computer Engineering (basically CS with some EE), and since I got into the degree I wanted to make games. I have not been programming all my life like some people out there, but I enjoy it a lot, and that's a big requirement IMO if you plan on ever making a game.

When I was finished with school, I applied to dozens of game companies and interviewed with several. Overall it was a good experience in terms of facing the madness of interviews, but after a couple months I realized the following:

1. I have big ideas of my own. These would be squashed by any big company I was talking to, and they would never see the light of day.
2. Many programmers at these companies are highly overworked and live a stressful life because of deadlines.
3. It is EXTREMELY difficult to get an entry level job in the game industry because it is highly competitive, interview questions are very difficult, and often requires some serious networking (people-wise) before you can get anywhere
4. I watched Indie Game - The Movie and felt that the indie game scene was a big enough inspiration

So, I took a year off after school and ended up publishing 3 games on iOS/Android. It was an amazing experience. ..I did not become a millionaire. In fact, it was barely enough to get by, so I ended up getting a regular job at a data company.

**Moral of the story:** One of the offers I received from a game company in San Diego was 45k base salary. WHAT?? I could have used it to gain experience and get my foot in the door, but instead I declined and followed my own route.

My first job after my period of unemployment was almost double that offer. And I have zero job stress because deadlines are not nearly as strict. What's best, I get to continue working on my games on the side.

So if your passion is game development, I say build your own team, find some interesting people who share your enthusiasm, get a job that will earn you a real living, and do it little by little. Maybe you will be the next Phil Phish.

Good luck mate
> 2 votes

---
Tags: software-engineering, education, career
---


title: XNA game structure question

text:
# Question
Title: XNA game structure question
I see to be running into a problem here. I know it's easier to show code samples so here you go.

This is my main game class

```
namespace WindowsGame4
{
    public enum MoveDirection { Left, Right, Up, Down, None}
    public enum GameState { MainMenu, LevelOne, PauseScreen }

    public class Game1 : Microsoft.Xna.Framework.Game
    {
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;

        GameState gameState = GameState.LevelOne;

        LevelOne levelOne = new LevelOne();
        MainMenu mainMenu = new MainMenu();

        public Game1()
        {
            graphics = new GraphicsDeviceManager(this);

            Content.RootDirectory = "Content";
        }

        protected override void Initialize()
        {
            if(gameState == GameState.MainMenu)
            {
                this.IsMouseVisible = true;
                mainMenu.Initialize(gameState);
            }

            if(gameState == GameState.LevelOne)
            {
                levelOne.Initialize();
            }

            base.Initialize();
        }

        protected override void LoadContent()
        {
            float viewportWidth = GraphicsDevice.Viewport.TitleSafeArea.Width;
            float viewportHeight = GraphicsDevice.Viewport.TitleSafeArea.Height;

            //pass in content manager, so we can load our textures and content from the class instead of from the main game code
            if(gameState == GameState.MainMenu)
            {
                mainMenu.LoadContent(Content, viewportWidth, viewportHeight);
            }

            if(gameState == GameState.LevelOne)
            {
                levelOne.LoadContent(Content, viewportWidth, viewportHeight);
            }

            spriteBatch = new SpriteBatch(GraphicsDevice);
        }

        protected override void UnloadContent()
        {

        }

        protected override void Update(GameTime gameTime)
        {
            if (gameState == GameState.MainMenu)
            {
                mainMenu.Update(gameTime);
                gameState = mainMenu.ReturnGameState();
            }

            if (gameState == GameState.LevelOne)
            {
                levelOne.Update(gameTime);
            }

            base.Update(gameTime);
        }

        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.CornflowerBlue);

            spriteBatch.Begin();

            if (gameState == GameState.MainMenu)
            {
                mainMenu.Draw(spriteBatch);
            }

            if (gameState == GameState.LevelOne)
            {
                levelOne.Draw(spriteBatch);
            }

            spriteBatch.End();

            base.Draw(gameTime);
        }
    }
}

```

My idea is, I can use the gamestate enum to switch between what I load for the player, like a menu or the main gameplay part. However I'm not sure if that is the right way to go about building a game in XNA. I'm VERY new to this, both xna and programming and structuring a program.

The problem I'm running in to so far is when I try this, it sas "object reference not set to an instance of an object." I'm not sure what that mean, as it is referring to right before I attempt to draw the stuff happening in my levelone class.

EDIT for Shiro, Here is the level one class

namespace WindowsGame4 { class LevelOne { GameState gameState;

```
    Rizerd rizerd = new Rizerd();
    Player player = new Player();

    public void Initialize()
    {

    }

    public void LoadContent(ContentManager Content, float viewportWidth, float viewportHeight)
    {
        Vector2 position = new Vector2(viewportWidth / 2, viewportHeight / 2);
        Vector2 rizardPosition = new Vector2(viewportWidth / 3, viewportHeight / 3);
        player.Initialize(Content.Load<Texture2D>("warriorspritesheet"), Content.Load<Texture2D>("hitbox"), Content.Load<Texture2D>("horizontalSwordHitbox"), Content.Load<Texture2D>("VerticalSwordHitbox"), position, 4, 4);
        rizerd.Initialize(Content.Load<Texture2D>("rizerd"), Content.Load<Texture2D>("rizardBounding"), rizardPosition, 2, 2);
    }

    public void Update(GameTime gameTime)
    {
        rizerd.Update(gameTime);
        player.Update(gameTime);
    }

    public void Draw(SpriteBatch spriteBatch)
    {

        player.Draw(spriteBatch);
        rizerd.Draw(spriteBatch);

    }
}

```

}

As well as the player class and the sprite class that is the base class for player

PLAYER CLASS namespace WindowsGame4 { class Player : Sprites { string name; int health; int mana; int score; int damage = 34;

```
    MouseState mouseState;
    MouseState previousMouseState;

    bool IsAttacking = false;
    int attackFrameTime = 250;

    int mouseDelay = 350;
    public bool mouseUsed = false;
    int elapsedMouseTime;

    Texture2D horizontalSword;
    Texture2D verticalSword;

    Vector2 swordHitBoxLocationDown;
    Vector2 swordHitBoxLocationUp;
    Vector2 swordHitBoxLocationRight;
    Vector2 swordHitBoxLocationLeft;

    public Rectangle swordDown;
    public Rectangle swordUp;
    public Rectangle swordRight;
    public Rectangle swordLeft;

    KeyboardState debugPress;
    bool debug;

    public bool playerCollide;

    //using initialize to pull the texture and frame count info into the GetFrames animation interfaces
    public void Initialize(Texture2D sprite, Texture2D boundingSprite, Texture2D horizontalSword, Texture2D verticalSword, Vector2 position, int frameRows, int frameColumns)
    {
        this.position = position;
        frameTime = 170;
        direction = MoveDirection.Down;
        speed = 3.0f;
        this.horizontalSword = horizontalSword;
        this.verticalSword = verticalSword;
        GetFrames(sprite, frameRows, frameColumns);
        SetBoundingBox(boundingSprite, position, sprite);
        SetSwordCollision();
    }
    public void Update(GameTime gameTime)
    {
        UpdateSwordCollision(gameTime);
        MovementAnimation(gameTime);

        //debug boolean switch
        debugPress = Keyboard.GetState();
        if(debugPress.IsKeyDown(Keys.F))
        {
            debug = true;
        }
        if(debugPress.IsKeyDown(Keys.G))
        {
            debug = false;
        }
    }

    public void Draw(SpriteBatch spriteBatch)
    {
        DrawFrame(spriteBatch, position);

        //debug, for checking hitbox location and activation
        if(playerCollide == true)
        {
            spriteBatch.Draw(playerBoundingSprite, playerBoundingPosition, Color.White);
        }
        else
        {

        }

    }

    //calculates the swords hitboxes based on the texture passed in for them, as well of the original sprites bounding position
    public void SetSwordCollision()
    {
        swordHitBoxLocationDown.Y = playerBoundingPosition.Y + playerBoundingSprite.Height - 2;
        swordHitBoxLocationDown.X = playerBoundingPosition.X + ((playerBoundingSprite.Width / 2 - verticalSword.Width / 2) + 4);
        swordDown = new Rectangle((int)swordHitBoxLocationDown.X, (int)swordHitBoxLocationDown.Y, verticalSword.Width, verticalSword.Height);

        swordHitBoxLocationLeft.Y = playerBoundingPosition.Y + ((playerBoundingSprite.Height / 2) - 3);
        swordHitBoxLocationLeft.X = playerBoundingPosition.X - horizontalSword.Width - 1;
        swordLeft = new Rectangle((int)swordHitBoxLocationLeft.X, (int)swordHitBoxLocationLeft.Y, horizontalSword.Width, horizontalSword.Height);

        swordHitBoxLocationUp.Y = playerBoundingPosition.Y - verticalSword.Height;
        swordHitBoxLocationUp.X = playerBoundingPosition.X + (playerBoundingSprite.Width / 2 - verticalSword.Width / 2);
        swordUp = new Rectangle((int)swordHitBoxLocationUp.X, (int)swordHitBoxLocationUp.Y, verticalSword.Width, verticalSword.Height);

        swordHitBoxLocationRight.Y = playerBoundingPosition.Y + (playerBoundingSprite.Height / 2) - 3;
        swordHitBoxLocationRight.X = playerBoundingPosition.X + playerBoundingSprite.Width;
        swordRight = new Rectangle((int)swordHitBoxLocationRight.X, (int)swordHitBoxLocationRight.Y, horizontalSword.Width, horizontalSword.Height);
    }

    //updates the sword hitbox's position, the textures position as well, when the sprite moves
    public void UpdateSwordCollision(GameTime gameTime)
    {
        if (direction == MoveDirection.Up && Idle == false)
        {
            swordHitBoxLocationDown.Y -= speed;
            swordDown.Y -= (int)speed;

            swordHitBoxLocationLeft.Y -= speed;
            swordLeft.Y -= (int)speed;

            swordHitBoxLocationRight.Y -= speed;
            swordRight.Y -= (int)speed;

            swordHitBoxLocationUp.Y -= speed;
            swordUp.Y -= (int)speed;
        }
        if (direction == MoveDirection.Left && Idle == false)
        {
            swordHitBoxLocationDown.X -= speed;
            swordDown.X -= (int)speed;

            swordHitBoxLocationLeft.X -= speed;
            swordLeft.X -= (int)speed;

            swordHitBoxLocationRight.X -= speed;
            swordRight.X -= (int)speed;

            swordHitBoxLocationUp.X -= speed;
            swordUp.X -= (int)speed;
        }
        if (direction == MoveDirection.Down && Idle == false)
        {
            swordHitBoxLocationDown.Y += speed;
            swordDown.Y += (int)speed;

            swordHitBoxLocationLeft.Y += speed;
            swordLeft.Y += (int)speed;

            swordHitBoxLocationRight.Y += speed;
            swordRight.Y += (int)speed;

            swordHitBoxLocationUp.Y += speed;
            swordUp.Y += (int)speed;
        }
        if (direction == MoveDirection.Right && Idle == false)
        {
            swordHitBoxLocationDown.X += speed;
            swordDown.X += (int)speed;

            swordHitBoxLocationLeft.X += speed;
            swordLeft.X += (int)speed;

            swordHitBoxLocationRight.X += speed;
            swordRight.X += (int)speed;

            swordHitBoxLocationUp.X += speed;
            swordUp.X += (int)speed;
        }
    }

    public void MouseInput(GameTime gameTime)
    {
        previousMouseState = mouseState;
        mouseState = Mouse.GetState();
        //elapsed mout time and mousedelay allow us to use gametime to limit button mashing of the attack button
        elapsedMouseTime += (int)gameTime.ElapsedGameTime.Milliseconds;
        //using a previous mouse state to register buttonstate release and current mousestate to register buttonstate pressed at the same time
        //prevents the system from registering the button being held down
        if (mouseUsed == false)
        {
            if (mouseState.LeftButton == ButtonState.Pressed && previousMouseState.LeftButton == ButtonState.Released)
            {
                //elapsed time here is used to time out the attack frame, when we press the mouse button, the frame is timed out, when it is timed out, our speed and frame goes back to normal--
                //--using previous frame.  also our isattacking goes to false at the end of the time.
                elapsedTime = 0;
                elapsedMouseTime = 0;
                IsAttacking = true;
                speed = 0;
                mouseUsed = true;
            }
        }

        if(mouseUsed == true)
        {
            Idle = true;
        }

        //only call moveobject if the mouse cooldown completes
        else if(mouseUsed == false)
        {
            MoveObject();
        }

        if(elapsedMouseTime > mouseDelay)
        {
            mouseUsed = false;
        }

        //if the attack frame is done, then set the speed to normal and go back to the frame you were at before the attack frame.
        //also set isattacking to false
        if (elapsedTime > attackFrameTime)
        {
            currentFrame = previousFrame;
            speed = 3.0f;
            IsAttacking = false;
        }
        //idle frames, these will be defaulted to based on MoveDirection enum and if the player is idle via no keyboard input
        if (direction == MoveDirection.Left && Idle == true)
        {
            if (IsAttacking == true)
            {
                currentFrame = 8;
            }
            else if (IsAttacking == false)
            {
                currentFrame = 0;
                previousFrame = currentFrame;
            }
        }
    }
    public void MovementAnimation(GameTime gameTime)
    {
        MouseInput(gameTime);
        //using elapsed time to measure how long a frame has been on screen
        elapsedTime += (int)gameTime.ElapsedGameTime.TotalMilliseconds;

        if (direction == MoveDirection.Right && Idle == true)
        {
            if(IsAttacking == true)
            {
                currentFrame = 9;
            }
            else if(IsAttacking == false)
            {
                currentFrame = 3;
                previousFrame = currentFrame;
            }
        }
        if (direction == MoveDirection.Up && Idle == true)
        {
            if(IsAttacking == true)
            {
                currentFrame = 11;
            }
            else if (IsAttacking == false)
            {
                currentFrame = 7;
                previousFrame = currentFrame;
            }
        }
        if (direction == MoveDirection.Down && Idle == true)
        {
            if(IsAttacking == true)
            {
                currentFrame = 10;
            }
            else if (IsAttacking == false)
            {
                currentFrame = 5;
                previousFrame = currentFrame;
            }
        }

        //movement frames paired with our MoveDirection enum
        //first we check if the player is not idle
        if (direction == MoveDirection.Down && Idle == false)
        {
            //then we set the frame based on what our direction is
            if (IsAttacking == true)
            {
                currentFrame = 10;
            }
            else if (IsAttacking == false)
            {
                currentFrame = 5;
                previousFrame = currentFrame;
            }

            //as long as the proper time has passed, we will go to the next frame
            if (elapsedTime > frameTime)
            {
                currentFrame = 4;
                previousFrame = currentFrame;
                //we wait for the proper amount of time to pass again, then we set the elapsed time to zero
                //then as long as we are receiving false for idle, the frame will go back to 5, and repeat
                if (elapsedTime > frameTime * 2)
                {
                    elapsedTime = 0;
                }
            }
        }
        if (direction == MoveDirection.Left && Idle == false)
        {
            if (IsAttacking == true)
            {
                currentFrame = 8;
            }
            else if (IsAttacking == false)
            {
                currentFrame = 0;
                previousFrame = currentFrame;
            }
            if (elapsedTime > frameTime)
            {
                currentFrame = 1;
                previousFrame = currentFrame;
                if (elapsedTime > frameTime * 2)
                {
                    elapsedTime = 0;
                }
            }
        }
        if (direction == MoveDirection.Right && Idle == false)
        {
            if (IsAttacking == true)
            {
                currentFrame = 9;
            }
            else if (IsAttacking == false)
            {
                currentFrame = 3;
                previousFrame = currentFrame;
            }
            if (elapsedTime > frameTime)
            {
                currentFrame = 2;
                previousFrame = currentFrame;
                if (elapsedTime > frameTime * 2)
                {
                    elapsedTime = 0;
                }
            }
        }
        if (direction == MoveDirection.Up && Idle == false)
        {
            if (IsAttacking == true)
            {
                currentFrame = 11;
            }
            else if (IsAttacking == false)
            {
                currentFrame = 7;
                previousFrame = currentFrame;
            }
            if (elapsedTime > frameTime)
            {
                currentFrame = 6;
                previousFrame = currentFrame;
                if (elapsedTime > frameTime * 2)
                {
                    elapsedTime = 0;
                }
            }
        }
    }
}

```

}

SPRITE CLASS

```
class Sprites : IMovement, IAnimation
{
    protected Texture2D sprite;
    protected bool Idle = true;
    protected Vector2 position;
    protected float speed;
    protected MoveDirection direction;

    protected KeyboardState currentButtonPress;
    protected KeyboardState previousButtonPress;

    protected int rows;
    protected int columns;
    protected int currentFrame;
    protected int previousFrame;
    protected int totalFrames;
    protected int elapsedTime;
    protected int frameTime;

    protected Texture2D playerBoundingSprite;
    public Rectangle playerBoundingRectangle;
    protected Vector2 playerBoundingPosition;

    //calculates sprites bounding position and size based on the texture atlas passed in and the position of the sprite itself
    public void SetBoundingBox(Texture2D boundingSprite, Vector2 position, Texture2D atlas)
    {
        playerBoundingSprite = boundingSprite;
        playerBoundingPosition.Y = position.Y + ((atlas.Height / (columns * 2)) - (boundingSprite.Height / 2));
        playerBoundingPosition.X = position.X + ((atlas.Width / (rows * 2)) - (boundingSprite.Width / 2));
        playerBoundingRectangle = new Rectangle((int)playerBoundingPosition.X, (int)playerBoundingPosition.Y, boundingSprite.Width, boundingSprite.Height);
    }

    //updates the sprites position and the direction of our movedirection enum
    public void MoveObject()
    {
        previousButtonPress = currentButtonPress;
        currentButtonPress = Keyboard.GetState();

        if(currentButtonPress.IsKeyDown(Keys.W))
        {
            Idle = false;
            direction = MoveDirection.Up;
            position.Y -= speed;
            playerBoundingPosition.Y -= speed;
            playerBoundingRectangle.Y -= (int)speed;
        }
        else if(currentButtonPress.IsKeyDown(Keys.A))
        {
            Idle = false;
            direction = MoveDirection.Left;
            position.X -= speed;
            playerBoundingPosition.X -= speed;
            playerBoundingRectangle.X -= (int)speed;
        }
        else if(currentButtonPress.IsKeyDown(Keys.S))
        {
            Idle = false;
            direction = MoveDirection.Down;
            position.Y += speed;
            playerBoundingPosition.Y += speed;
            playerBoundingRectangle.Y += (int)speed;
        }
        else if(currentButtonPress.IsKeyDown(Keys.D))
        {
            Idle = false;
            direction = MoveDirection.Right;
            position.X += speed;
            playerBoundingPosition.X += speed;
            playerBoundingRectangle.X += (int)speed;
        }
        else
        {
            Idle = true;
        }
    }

    public void GetFrames(Texture2D spriteSheet, int rows, int columns)
    {
        //when i load content for this player, Ill use the constructor parameters from the player class and pass them into the parameters for this method.
        sprite = spriteSheet;
        this.rows = rows;
        this.columns = columns;
        currentFrame = 0;
        totalFrames = this.rows * this.columns;
    }

    public void DrawFrame(SpriteBatch spriteBatch, Vector2 position)
    {

        //get the width and height of the current frame
        int width = sprite.Width / columns;
        int height = sprite.Height / rows;

        //calculates the current row we are on based on what frame we are on
        //calculates the current column we are on based on what frame we are on
        //for currentRow, the float it return will determine what row we are on
        //for current column, the remainder will determine which column we are on
        int currentRow = (int)((float)currentFrame / (float)columns);
        int currentColumn = currentFrame % columns;

        Rectangle sourceRectangle;
        Rectangle destinationRectangle;

        sourceRectangle = new Rectangle(width * currentColumn, height * currentRow, width, height);
        destinationRectangle = new Rectangle((int)position.X, (int)position.Y, width, height);

        spriteBatch.Draw(sprite, destinationRectangle, sourceRectangle, Color.White);
    }
}

```

}

# Answer
> 2 votes
> Ah, then I may be confused on game structure with XNA... If loadcontent and initilize in the main game class can only be called once,

They are called once *per device creation* not per game start. If you re-size the underlying Windows window, the device is, and all content should be, explicitly destroyed.

> then do I call my other classes loadcontent and initialize in the update method?

When the device is created, game.Initialize() is called. Anything already added to game.Components is Initialize()'d at this point. Objects that are created *during* game.Initialize() need to be explicitly Initialize()'d at the same time.

After game.Initialize() is finished, game.LoadContent() is called. Do not use the Device and/or Content before game.LoadContent() is called. Anything already added to game.Components is LoadContent()'d at this point. Objects that are created *during* game.LoadContent() need to be Initialize()'d and LoadContent()'d at the same time, since game.Initialize() will not be called again until the device is destroyed.

After game.LoadContent() is finished, any object you create needs to be Initialize()'d and LoadContent()'d at the same time. You can do this anywhere, at any time.

**Static/singleton:**
Don't get fooled into making **everything** a sub-sub-sub-sub-sub-class of GameObject that **must** get added to game.Components. Make a generic GameObjectContainer\<\> class and inherit from it when you need to make "buckets" of similar things. A GameObjectContainer will be nothing but a List and overrides of Initialize(), LoadContent(), Update() and Render() that all contain nearly-identical Foreach(...)'s.

The following basic shape applies to all kinds of content. An example Manager class for textures:

```
class TextureManager
{
   private static Dictionary<string, Texture2D> allTextures;
   public static Texture2D GetTexture(string name)
   {
      if (allTextures.containsKey(name))
      {
         return allTextures[name];
      }
      else
      {
         Texture2D newTexture;
         switch (name)
         {
            case "ShipHull":
              newTexture = new Texture2D(...);
              break;
            default:
              throw new Exception("Unknown texture name");
              break;
         }
         allTextures.add(name, newTexture);
      }
   }
   public static void StaticInit(Game game)
   {
       //Call whenever the backbuffer needs to be created
       //Load backbuffer and other essentials
   }
   public static void StaticDeinit()
   {
       //Call whenever the device is destroyed
       //Unload all children
   }
}

```

From anywhere:

```
draw(..., TextureManager.GetTexture("ShipHull")); //Created/loaded when first accessed
//You can access it early so it's ready before you actually need it,
//but you don't **have** to load everything at game start.

```

**Edit:** another handy singleton

```
public class Game1 : Microsoft.Xna.Framework.Game
{
   public static readonly Game TheGame;
   public Game1()
   {
      TheGame = this;
      ...
   }
   ...
}

```

From anywhere:

```
Game1.TheGame.GraphicsDevice.PresentationParameters.BackBufferHeight
Game1.TheGame.Content
//Instead of passing as arguments

```

It is entirely valid to have only two GameObjects added to game.Components. One for 2D/interface stuff and one for 3D/world stuff. If they are both GameObjectContainers and you have implemented content managers, there is no need to pass Game to every component constructor. This may also remove the need for the distinction between Initialize() and LoadContent(); if your objects don't inherit from GameObject and will be created after game.LoadContent() is called, you can just completely initialize them within the parameter-less constructor. All content is, or will be, available through the appropriate Manager. Just make sure to StaticInitialize() all of the Managers absolutely first.

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