# Question
Title: Minimal Inform6 code to support <action> syntax
Without using any of the standard Inform libraries, what is the minimal amount of code / infrastructure needed to support the `<action>` syntax?

What I tried is

```
Verb 'foo' * -> Foo;

[ FooSub;
    "Hello from FooSub";
];

[ Main;
  <foo>;
];

```

I expected this to print `Hello from FooSub` when run; however, the output I get is

```
Action <0 0 0>

```

# Answer
By bisecting the standard `parserm.h` file, I've found that the secret sauce is the platform function `R_Process`. By adding the following implementation of it to my code:

```
[ R_Process a;
    indirect(#actions_table-->a);
];

```

I got `<foo>` to work.
> 0 votes

---
Tags: interactive-fiction
---


# Question
Title: How to combine objects in a rendered scene with and without bloom effect?
I'm working on a game and engine as I go under OpenGL.

I've had a bloom effect in place for a while that works as a post-procesing effect on the entire screen. It's been fine up until now.

I have an object that is made up of a few meshes, and one of these meshes is mostly white. The result is it blooms like crazy, but I really don't want it to.

The only way around it I can see is that the objects I *do* want to have bloom would need to be rendered to a bloom-framebuffer from which I can bloom (and store the depths) to then mix back in with the rest of my scene.

Is this the only way to go about it? It seems like a lot of work to simply isolate something from a screen-wide affect.

# Answer
> 2 votes
Usually bloom is done with HDR rendering where you use a floating point (usually 16 bits per channel) texture for rendering to.

* Things that are brighter than 1.0 get bloom applied.
* Things that are 1.0 or less don't get any bloom.

You render everything to the same texture, and remove anything that's not bright enough to bloom when you start processing the bloom post effect. That means you can have a white thing that doesn't bloom by rendering it as RGB(1.0, 1.0, 1.0) and one that does by using say RGB(2.0, 2.0, 2.0).

http://en.wikipedia.org/wiki/Bloom\_%28shader\_effect%29

http://kalogirou.net/2006/05/20/how-to-do-good-bloom-for-hdr-rendering/

# Answer
> 1 votes
I use MRT rendering for this; I render everything into both a diffuse map and a glow map. I then blur the glow map into a bloom-like effect, and add it back on top of the diffuse map as a post-processing effect.

This way I can make objects that glow (by drawing their diffuse color into both the diffuse and the glow map), objects that don't glow (by drawing black into the glow map), translucent objects that partially obscure the glow of any glowing objects which are visible through them (drawing partly transparent black into the glow map), and even objects which glow a different color than their diffuse (by drawing different colors into the two buffers).

It's a pretty simple system that gives a lot of power and flexibility, I find.

---
Tags: graphics, rendering
---


title: svg spaceship game movement 2d

text:
# Question
Title: svg spaceship game movement 2d
I've been searching for a way to make an svg box move to all directions using js. I have seen many tutorials on how to do it grid like, but I want it so have a square that can turn, move forward, backwards and sideways. In terms of movement, I want to be like https://www.chromeexperiments.com/experiment/arena5 except there will be a square instead of a triangle and there will be no enemies.

My problem is that I don't know how to make an svg square move fluidly and without a grid, but the movement will only use keyboard, no mouse. Please be patient I'm new to js gaming.

Here is the most reason version of what I've trying, this is svg, right now I'm trying to make it in canvas.http://codepen.io/julian-a-avar/pen/PqZvxp

# Answer
> 0 votes
I've edited your example, you can now rotate using the keys, it uses CSS3 rotations.

If you want to move more fluid, you can either update the move() faster, or add some easing animations.

You can still make several improvements, but here is one solution:

http://codepen.io/anon/pen/jPraGK

The css rotation code:

```
$("#block_green").css({'-webkit-transform' : 'rotate('+ rotation +'deg)','-moz-transform' : 'rotate('+ rotation +'deg)','-ms-transform' : 'rotate('+ rotation +'deg)','transform' : 'rotate('+ rotation +'deg)'});

```

---
Tags: javascript, movement, html-canvas
---


# Question
Title: Problem, why the mouse cursor position is totally wrong, after resizing the window?
I come here, because i'm trying to add some "menu" interface in my small XNA Game . I found on internet a nice library adviced by many devellopers. Till now everythink is ok, the problem is my C# code logic. I try to allow the player (user) to change the screen resolution . The resolution and screen are both of them change . The problem is about the "cursor" of my computer mouse . It's really weird, i don't why but the cursor of my mouse does not select the right elements .It's look like a gap persisted between the old window.

Here is the code i use, as you can see , very simple. And should be normally work. I hope you have some idea why . I'm lost :'(

```
void btnApply_Click(object sender, Controls.EventArgs e)
{
  Manager.Graphics.IsFullScreen = chkResFull.Checked;

  //Resolution set by default
  int w = 1024;
  int h = 768;

  if (rdbRes1024.Checked)
  {
    w = 1024;
    h = 768;
  }
  else if (rdbRes1280.Checked)
  {
    w = 1280;
    h = 1024;
  }
  else if (rdbRes1680.Checked)
  {
    w = 1680;
    h = 1050;
  }

  Manager.Graphics.PreferredBackBufferWidth = w;
  Manager.Graphics.PreferredBackBufferHeight = h;

  Manager.Graphics.ApplyChanges();
}

```

Here is the screen shot of my original screen ( 800/480 ) Here is the screen shot after change to the screen resolution ( 1280/860 )

# Answer
> 3 votes
When you resize your game resolution you need to update every single `rectangle` in your game (every button, etc) and multiply it by a proper scale, so that the "hitboxes" would work, which would be a lot of work. So, a smarter way of achieving the same result is simply by multiplying your mouse position by a `Vector2 scale = new Vector2(originalWidth / width, originalHeight / height);`.

So, for example, no matter the game resolution, if your mouse is in the middle of the screen, you will see the mousePosition as (400,240);

```
int GameWidth = 800; // the original game's width
int Gameheight = 480; // the original game's height

Matrix ScaleMatrix = Matrix.CreateScale(
    (float)graphics.PreferredBackBufferWidth / GameWidth,
    (float)graphics.PreferredBackBufferHeight / GameHeight,
    1f
    );
Vector2 Scale = new Vector2(ScaleMatrix.M11, ScaleMatrix.M22);

Vector2 mousePosition = ...; // calculate mousePosition as you normally do
mousePosition = mousePosition / Scale;

//Update the input in Game_Reset event
private void Graphics_DeviceReset(object sender, System.EventArgs e)
    {
        if (arcadia.manager.RenderTarget != null)
        {
            //These steps are already done by the manager on Graphics Device Reset.
            //Manager.RenderTarget.Dispose();
            //Manager.RenderTarget = CreateRenderTarget();
            arcadia.manager.Input.InputOffset = new InputOffset(0, 0, arcadia.manager.ScreenWidth / (float)arcadia.manager.TargetWidth, arcadia.manager.ScreenHeight / (float)arcadia.manager.TargetHeight);
        }
        Window mainWindow = arcadia.manager.Controls.First() as Window;
        if (mainWindow != null)
        {
            mainWindow.Height = arcadia.manager.TargetHeight;
            mainWindow.Width = arcadia.manager.TargetWidth;

        }
    }

```

`ScaleMatrix` should be the same matrix you use when using you call: `spriteBatch.Begin(SpriteSortMode.Deferred, null, null, null, null, null, ScaleMatrix);` to scale your sprites.

---
Tags: xna, graphics, mouse, resolution, ui-design
---


# Question
Title: How do I make circles bounce off each other realistically?
I'm trying to create bouncing balls with realistic physics. At the moment, when the balls hit each other, they bounce back in the same direction they came from. How do I make them more realistic?

I don't know much about physics. What things should I be reading about?

Here's an image of how I imagine balls would bounce in real life:

how I think it should work (original source: http://thewombatguru.nl/Bouncing.png):

Is this how it works?

# Answer
> 2 votes
It kinda depends on what you're making.

If you're making a game about physics, you could conceivably write your own physics engine, **however I do not recommend it**. There are many 2D and 3D physics engines already out there that you can use that will save you months of work.

My first time using Box2d was intimidating, and I'll admit it has a fair learning curve. However unless you're a physics genius, the amount of time you spend figuring out Box2d will be significantly less than the amount of time you'd have spent writing your own physics, and I can guarantee the results will be better.

If you insist on writing your own physics... well you've been warned :P There are many articles online about 2D ball to ball collision, you'll just have to do the hard work of converting articles to code. If you aren't worried about spin, it's not too unreasonable of a job... but it will still be a lot of work.

Good luck!

---
Tags: collision-detection, physics
---


title: RPG stats degrading by level

text:
# Question
Title: RPG stats degrading by level
I'm looking for some math to "degrade" stats over level. The idea is that if you have x value for a stat that it's affect will be less when you increase your level, making you have to put more points into that stat to maintain.

For my specific example I have a stat I call Focus. I want the Focus stat combined with the level to create a percentage. I will use this percentage against each abilities damage/heal value to get a value. This value will act as the low end and the abilities value will act as the high end for finding a random number between. So if "Strike" has a value of 10 and my focus % is 50% then then I find a random number between 5 and 10 to get the actual damage to apply.

So at level 1 ideally this % is 100% (so "Strike" will do 10 damage always). At level 2 with no more points in the Focus stat, I want this final % to go down but putting points into the Focus stat could keep it up.

This seems like the kind of thing every RPG game has, but I'm not sure how it's done. I'm picturing all stats being like this. Each level I would increase base damage/heal values for abilities by x% and then degrade other stats. Like strength for example. The idea would be to try and keep the strength state so it results in 100% of the ability damage by putting points into it each level.

Does this make sense or am I way off base in my thinking on how this kind of stuff is done or can be done?

# Answer
> 2 votes
What jhocking said in the comments is what's common in games. I don't think I could name a single game that uses the concept in the question. By that I mean that games commonly have increasingly difficult challenges/enemies such that a protagonist who does not "level" appropriately finds the challenges more and more difficult.

That said, to answer your question as is:

Your obstacle is not in implementing this concept (simply having a stat decrease every level is trivial). Your obstacle is in **explaining this mechanic to the player**. Simply having a "Focus" stat decrease every level with no explanation could be frustrating, confusing, and conflicts with any other RPG they might have ever played.

One reasonable solution to relaying this properly to the player is to wrap the statistic in language explaining it as a skill specifically relative to level. That is, explain that the Focus stat at level 1 is maxed at 1. Upon gaining the second level, the Focus stat remains at 1, thus lowering the effectiveness of all abilities. Couch that statistic in the same numerals used for "levels", always ensuring that "100% Focus" is "Focus = Level". You could explain that each point below Level lowers the effectiveness a fraction, or you could give the percentage to the player ("Each point Focus is lower, all abilities are 10% lower in damage!")

# Answer
> 1 votes
In addition to having a Stat variable, have a StatIncrease variable and decrease StatIncrease with every level. I.e.:

```
float Stat = 0f;
float StatIncrease = 10f;

void LevelUp ()
{
    Stat += StatIncrease;
    StatIncrease *= .9;
}

```

---
Tags: rpg
---


# Question
Title: Does Steam provide persistent data storage to developers?
Does Steam provide persistent data storage (for custom data) to developers? For example, would an online shooter be able to store player statistics (kills, matches, player deaths, etc.) on Steam servers?

# Answer
You could save all the data both locally on your player's computer, and sync it automatically to Steam Cloud, which indeed allows you to store stats/user preferences/progress/etc.. online.

Steam Cloud API :

> header: ISteamRemoteStorage.h
>
> Game settings, savegames, and other user-specific bits can be replicated to the Steam Cloud to provide the player with a continuous and hassle-free experience.

EDIT : You can also write/read everything directly into the servers. If you are worried about users tampering with data.

Steam Cloud documentation :

> The Cloud functions all live in ISteamRemoteStorage.h. It is essentially a very simple filesystem API - your game reads and writes files directly to the API.
>
> Aside from reads and writes, a few functions are provided to provide visibility into the files already in the Cloud "folder", and to query the amount of quota remaining.
> 13 votes

# Answer
For statistics you can use ISteamUserStats, which is a part of the Steamworks offering.

This interface allows you to define (from the Steamworks developer site) a set of tracked statistics with various properties, and can even auto-grant Steam achievements based on the stat values.

The interface supports multiple types of numerical data (integer, floating point, and moving average), access control (only allow trusted game servers to report changes), limits (both absolute and per-update), and automatic global aggregates.

Documentation can be found here: https://partner.steamgames.com/documentation/ugs
(Requires signing up for Steamworks, but doesn't require affiliation to read.)

ISteamUserStats statistics are stored to the Steam backend immediately, rather than requiring synchronization and conflict management, and do not have a fixed quota. Leaderboards can also be automatically built by Steam from the data.

ISteamRemoteStorage is designed for saving user files, such as game saves and configuration information, rather than statistical tracking.
> 5 votes

---
Tags: online, data, steam
---


# Question
Title: What are the key ingredients for a good game-specific community website?
Feel free to use an example. I am thinking things like guides, tools that help a player make certain in-game choices, discussion boards, services that enhance player interaction, mods, blog/news, etc. I am sure sites like this exist for really popular games like WoW. I am wondering what the community here thinks makes for a successful game-specific community website.

# Answer
> 1 votes
Above all, I think it's the community. The community's demeanor is often not in the developer's control but there are things that can be done to promote a friendly culture. For example, rewarding players for helping newbies, a decisive ban every now and then, and giving players the power to reward other players for being helpful.

Next up is giving players the ability to feel proud about their game achievements. This can be something like posting replays for other people to analyze, hosting elite tournaments, talking about strategies, etc.. Mostly the standard forum stuff.

Finally, there's the developers themselves who must communicate with the community and make them feel like their effort and skills contribute to the game's development. Glance over every now and then, respond to some suggestions, and let them know if a suggestion was implemented.

---
Tags: web, marketing, content-generation, community-management
---


title: Simulating beer pong physics in Unity

text:
# Question
Title: Simulating beer pong physics in Unity
I'm trying to create a simple beer pong game in Unity. The basic idea is this - when it's your turn to shoot, you use your mouse to pick a point on the table that you want the ball to hit and bounce off of.

Then you press the left mouse button, and while it's pressed, move it up and down to determine the degree of the arc of the shot (the ball should hit the same previously chosen spot on the table no matter which degree is chosen).

The arc should be visible as well. It would look something like this:

So my questions are:

1. Given a target point and a launch angle, how do I calculate the trajectory?
2. Given the same, how do I calculate the force to apply to the ball?
3. What is the best way to display the trajectory in Unity? My first idea is manually placing a bunch of particles (which is how I did it in the screenshot), but I'm not sure if that's the best choice performance-wise.

# Answer
This is fun! The trajectory is just a bunch of mathfz and a line renderer. Check out this post for more information on that which details how to calculate the trajectory. Line renderers are definitely your best bet for visualization. Even on mobile, 5-10 line renderers would be no problem. The alternative would be to hard-code the visualization with a (code-created) mesh or directly rendering to the screen, both of which are not fun.

As for physics, I bet you can use Unity's PhysX out of the box. You'll have to play with the initial force to apply but the direction should be about the direction the camera is facing. All you have to do is multiply by some factor to get it working well.

```
float X = 10;
PongBall.rigidbody.AddForce(Camera.main.transform.forward * X, ForceMode.VelocityChange);

```
> 2 votes

# Answer
So I started writing some code for you. Then when I tested it, it didn't have the desired result. Here is the code so far. If anyone know what is wrong with it, do tell :-)

```
/// <summary>
/// Adds the velocity to simulate throwing a ball
/// </summary>
/// <param name="angle">The angle of the throw along the z axis</param>
/// <param name="direction">The degrees of the throw to the left or right</param>
/// <param name="power">The power of the throw</param>
private void ThrowBall(float angle, float direction, float power)
{
    angle = Mathf.Max(Mathf.Min(0, angle), 90);  //Make sure angle is between 0 and 90
    direction = Mathf.Max(Mathf.Min(-45, direction), 45);  //Make sure direction is between -45 and 45
    power = Mathf.Max(1, power);  //Make sure there is a power of at least 1
    angle *= Mathf.Deg2Rad;  //Convert angle to radians
    float xForce = Mathf.Cos(angle) * Mathf.Sin(direction);  //Get the force to apply to the x axis to throw the ball to the left or right
    float yForce = Mathf.Sin(angle);  //Get the force to apply to the y axis based on the angle
    float zForce = Mathf.Cos(angle) * Mathf.Cos(direction);  //Get the force to apply to the z axis based on the angle
    Vector3 force = new Vector3(xForce, yForce, zForce).normalized;  //Get the force in a Vector3 and normalize it so that the angle does not affect the power
    GetComponent<Rigidbody>().AddForce(force * power);  //Get the Rigidbody Component and apply the force to it based on the angle and power
}

```

It works if throwing in a straight line, but when adding a left/right directional force, it raises faster than it moves forward. I am very interested in finding an answer to this. I am going to keep looking, and I will update the code as I find out more information.

As for the trail, I would just add particles behind it.
> 0 votes

---
Tags: unity, physics, projectile-physics
---


# Question
Title: How to get the 3D location of a click in unreal engine 4?
I'm trying to do a board game in unreal engine 4. I've set up pawns and a board actors. However, I would like to be able to decide on which case of the board the player clicked. The board is one piece and I'm not sure splitting it up would render it nice.

Is there a way to get back the 3D position of a click in unreal engine ?

Thanks for any help !

# Answer
> 1 votes
Cast a ray in your player controller.

Your PlayerController blueprint that controls your player pawn has special blueprint nodes exactly for this use case. The following outputs the hit location in world coordinates whenever the player clicks on something that blocks traces on the visibility channel:

---
Tags: unreal-4
---


title: Entitiy spawn on Button press

text:
# Question
Title: Entitiy spawn on Button press
I'm trying to create a little 2D-Zombie-Shoot game. I'm pretty much at the beginning of programming. At least, I can create a player that is moving with arrow keys and stuff. My question is: How do I spawn a Zombie on a button-press? I've already tried it, but with no good results. Here's the code:

```
//A variable, for the amount of zombies spawned
public int zombie = 0;

 public void tick() {
 //The rest of the code is irrelevant
 ...........

    if (mouse1.isPressed()) {
        zombie++;
    }

}

public void render() {
    //The rest of the code is irrelevant
    ...........

    //Player
    g.drawImage(playerImage, x, y, null);

    //Check how many zombies should be created
    if (zombie > 0) {
        g.drawImage(zombieImage, zX, zY, null);
    }
    ...........

```

# Answer
You will need a zombie `class`.

```
public class Zombie {
public int x, y;

public Entity(int x, int y) {
    this.x = x;
    this.y = y;
}

public void tick() {
//code to control movement and such
    }

public void render() {
    g.drawImage(zombieImage, x, y, null);
}
}

```

I'm not sure which class you are showing in your code but you will need to make a zombie `ArrayList` for your zombies in it.

```
protected List<Zombie> zombies = new ArrayList<Zombie>();

```

In your tick method you should call all of the zombie's tick methods like this

```
for (int i = 0; i < zombies.size(); i++) {
            zombies.get(i).tick();
        }

```

You also need a similar thing in render

```
for (int i = 0; i < zombies.size(); i++) {
            zombies.get(i).render();
        }

```

This will allow you to have multiple zombies, in order to add new zombies, you call `zombies.add(new Zombie(`your x value you want`,` your y value you want`);`

In order to remove zombies you call `zombies.remove(`the index of the zombie to remove`);`

If you just do this, you will need to know to know the index of the zombie to remove. To get around this you could have a `boolean` called removed inside of the `Zombie` `class`. You can then cycle through the `ArrayList` as earlier and simply remove the zombies that have the `removed` variable equal to `true` like this

```
for (int i = 0; i < zombies.size(); i++) {
            if (zombies.get(i).removed) zombies.remove(i);
        }

```

This will allow you to have multiple zombies and have them all render and update simultaneously.
> 1 votes

---
Tags: java, 2d
---


# Question
Title: Why the AnchorPoint doesn't affect the `CCLayer` Positioning?
I think there is a difference between the CCLayer and CCNode behavior when I change their AnchorPoint.

I will describe what I mean and please somebody explain it.

**Scenario:** I start with `CCNode`

```
CCNode *node = ...;
node.setContentSize(ccp(W,H));
// 1.
node.setAnchorPoint(ccp(0,0));
node.setPosition(ccp(X,Y); // This line will move the node in a way that its (0,0)-point will be placed at (X,Y).
// 2.
node.setAnchorPoint(ccp(1,1));
node.setPosition(ccp(X,Y); // This line will move the node in a way that its (0,0)-point will be placeed at (X-W,Y-H).
//In other word, this line will move the (W,H)-point of the node to (X,Y)

```

In addition to the **Positioning**, all actions (like **Rotating, Scaling**) are based on this anchor point.

This policy is fair enough and you won't get confused when moving a scaled node (`setScale(X)`) to some position because the **node's position** ( and **not node's contents!**) will not change in the screen after any actions.

( **PS:** We knew that rotating/scaling a node will rotate/scale internal node contents)

Let's continue with `CCLayer`:

```
CCLayer *layer= ...;
layer.setContentSize(ccp(W,H));
// 1.
layer.setAnchorPoint(ccp(0,0));
layer.setPosition(ccp(X,Y); // This line will move the layer in a way that its (0,0)-point will be placed at (X,Y)
// 2.
layer.setAnchorPoint(ccp(1,1));
layer.setPosition(ccp(X,Y); // Unfortunately, This line will move the layer in a way that its (0,0)-point will be placeed at (X,Y).

```

Although CCLayer also use the anchor point for scaling, rotating and ... purposes, **It does NOT use its anchor point for positioning!!!**

Question \>\>\>\> **WHY? and How can I have the same CCNode-like `setPosition()` behaviour for `CCLayer`?**

---

PS: I've also tried `->ignoreAnchorPointForPosition(true)` but it didn't help.

(@cocos2d-x version is 2.2.3)

# Answer
You say you have tried setting \`ignoreAnchorPointForPosition(true), but have you tried setting it to false?

CCLayer init method calls `ignoreAnchorPointForPosition(true)`, which basically tells cocos to ignore the anchor point for positioning. You can set it to false and it should respect the anchor point for position.
> 0 votes

---
Tags: cocos2d-iphone, cocos2d, coordinates, cocos2d-x, layers
---


# Question
Title: ECS Reference another Entity's Properties
In an entity component system (implemented where components only contain data and systems operate on groups of data) one can guarantee that the entity in which a system is operating on has the desired data. For example, a MovementSystem only operates on an entity if it has both Transform and RigidBody components. The MovementSystem knows as a matter of fact that the entity has all the data required to perform its logic. The problem I find is if a system needs to operate on *another* entity's properties - we cannot guarantee that this other Entity has the data we want to operate on.

Lets use a contrived example because I like code

DamageComponent:

```
DamageComponent(target, damage) : Component {
    Entity target = target;
    int damage = damage;
}

```

HealthComponent:

```
HealthComponent(health) : Component {
    int currentHealth = health;
}

```

The System:

```
DamageSystem() : System {
    // Operates on all Entities which have a DamageComponent

    DamageComponent dc = this.entity.getComponent(DamageComponent);

    // damage the target every update tick
    void update(dtime) {
        HealthComponent health = dc.target.getComponent(HealthComponent);
        health.currentHealth -= dc.damage;
    }
}

```

You see, a problem arises if the target Entity does not have a HealthComponent. What if the Entity never had a HealthComponent or some other game logic removed the HealthComponent? Is it typical to check every time if the target Entity has the desired Component?

```
if (dc.target.hasComponent(HealthComponent) {
    //...
}

```

I'm looking for a more "elegant" approach, if one exists. Thank you

# Answer
It's probably easier to enforce that an entity has certain components when its reference is assigned to the component property in the first place rather than every time it is used. Depending on the language, there are ways of doing this that are enforced at compile time or run time. Compile time would be ideal for a performance sensitive game. For example, in a language that supports generic programming like C# or templates like C++, you could wrap your entity reference in a type that is generically typed for the components it allows the entity it references to have.
> 1 votes

# Answer
One way to solve this problem is to perform necessary checking while setting the "other" entity of the component. Like so:

```
DamageComponent(target, damage) : Component {
public:
    Entity GetTarget() { return target; }
    void SetTarget(Entity other)
    {
        if (other->contains(healthComponent))
            target = other;
    }
    int damage = damage;
private:
    Entity target = target;
}

```

Something like that. Actual code implementation may depend on the language.
> 1 votes

# Answer
When I implemented something similar I used a messaging system exclusively to handle the necessary communication between different entities in various systems.

That way the messenger can perform the relevant required component checks while marshalling the your messages between the entities. You can think of the Events as mini SubSystems if you like.

It also cleans up your systems quite a bit as well as providing a great deal of de-coupled logic, and hence less dependency chains overall etc.

(contrived and untested psuedo-code disclaimer) example :

```
public class Event_TakeDamage : GameEvent {
    public Entity target;
    public float damage;

    public ComponentMapper<HealthComponent> health;
    public ComponentMapper<EventManagerComponent> eventManager;

    public Event_TakeDamage(Entity target, float damage) {
        this.target = target;
        this.damage = damage;

        health.init(world);
        eventManager.init(world);

        if(health.Get(target) != null && eventManager.Get(target) != null) {
            eventManager.AddListener<Event_TakeDamage>(health.TakeDamage);
        }
    }
}

public class HealthComponent : EntityComponent {
    public float health;

    public void TakeDamage(float damage) {
        health -= damage;
        // TODO check for death etc
        // possibly do a RemoveListener for this Entity's EventManager etc.
    }
}

public class ColliderComponent : EntityComponent {
    public Bounds bounds;
}

public class CollisionSystem : EntitySystem {
    ComponentMapper<ColliderComponent> collider;

    void Start() {
        collider = AddComponentType<ColliderComponent>();
    }

    void Init() {
        collider.init(world);
    }

    void Process(Entity entity) {
        foreach(Entity collidee in SpacialManager.Instance.QueryCollisions(collider.Get(entity).bounds)) {
            EventManager.Instance.QueueEvent(new Event_TakeDamage(collidee, 5f));
        }
    }
}

```
> 0 votes

---
Tags: entity-system
---


# Question
Title: Algorithm for dividing a 2D grid into organic looking plates
the title pretty much says it all: **How could one go about segmenting a 2D grid into smaller parts?** My goal here is to create tectonic plates for further procedural world generation

**Details to consider:**

* The amount of parts should be controllable the resulting parts should
* look "organic", meaning somewhat irregular, but still clumpy
* the parts should wrap on the x and y axes

**For now, I am using a random flood fill** with as many starting points as I want plates.

Pseudocode would look a bit like this:

```
For 0 to plateAmount
   create a random seeding point and store point in each plates list of points.

While empty points exist in the grid,
   loop over each plate and add an adjacent, empty point to it.

```

This gives acceptable results, but takes very long! With 6 plates, a map of 100x100 tiles/points/cells takes 3 seconds, 200x200 takes 50 seconds, 500x500 takes forever. The more plates, the quicker it is.

Is there a quicker way to get a good result? Maybe something with Voronoi?

*My result with 60x60 cells, 10 plates, each cell is 10x10 pixels. Ignore the "height" text, it displays not-yet-visualized data from the cell the mousecursor hovers over*

# Answer
> 2 votes
You're on the right track. However...

**Try**

`O(n*m)` runtime is typical with something like this. Your implementation is a bit excessive, however. The real question is, **What is making your `O(n*m)` algorithm take so long?**

Why bother to run through *every map cell* for each influence? It would be faster to have each starting influence also specify some random maximum radius within which it could affect map cells. At the start, store the position of the influence AND it's radius. Then, for each "plate" (influence), attempt to write cell color *only within that radius*.

Cell-based Voronoi will similarly be `O(n*m)` if using a similarly naive approach, since you must run through *all* Voronoi centres for *all* map cells.

**Catch**

For the approach described above:

1. Radius-based distance checks use a square root which can be relatively costly; use either a radius look-up table to avoid square root calculations, or use rectangular `[x,y]` bounds range-check for early termination, only checking radius / `sqrt` once you fall within those `[x,y]` bounds.
2. Optimal average radius is going to be based on your average influence point spacing... this is something I leave for you to figure out, as it depends on how you have distributed your initial points.
3. Some empty cells will remain since radii will not cover all map cells. You can fill these out relatively cheaply in a final step, by taking the colour of a random, populated neighbour.

**Finally...**

(1) profile your code and (2) optimise:

* remove conditionals, the more deeply-nested they are the more impact this will have;
* pack your data tightly and in a cache-friendly fashion (anything from using simple sub-grids to a Hilbert curve or Z-curve).

Unfortunately, to get to closer to `O(n)`, you would need a continuous function that creates distinct regions of adjacent, uniquely-coloured cells. If anyone knows of such an approach, I would love to hear about it, but I know of no such algorithm. There may be a way to adapt Perlin noise (continuous function) to do this, but not without a significant amount more effort and complexity. Usually, simplicity is best, so I suggest sticking with and optimising your current nested approach.

Vectorised (SIMD) and parallelised (multi-core) processing are also options if your language is sufficiently low-level or does these transparently. The only other thing I could suggest if you are using a higher-level langauge (e.g. HTML5 JS or Unity) is to write generation functions in a lower level language and tie them in as e.g. shared libraries to maximise performance in those critical sections.

# Answer
> 1 votes
Instead of iterating over all plates, consider only those empty cells that could possibly be filled: namely those that are adjacent to at least one already filled cell.

Your algorithm could then become something like this:

```
1) Keep track of all unfilled cells that have at least one adjacent filled cell.
2) Select one of these unfilled cells.
3) Select one plate from all plates adjacent to the cell.
4) Make the cell part of the plate.
5) Check the cells surrounding the newly filled cell: add those that don't belong
   to a plate yet to your data structure (if they haven't been added before).

```

This way, your runtime is `O(w*h)` but the operations inside the loop are quite cheap. In practice, the following Java implementation has no trouble generating a 500 by 500 grid:

```
import java.util.Random;

// for displaying
import java.awt.Color;
import java.awt.image.BufferedImage;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JOptionPane;

public class OrganicFill {
    private int width;
    private int height;
    private int[][] grid;
    private int numPlates;

    private Random random = new Random();

    public OrganicFill(int width, int height, int numPlates) {
        this.width = width;
        this.height = height;
        this.grid = new int[width][height];
        this.numPlates = numPlates;
    }

    public void fill() {
        // auxiliary data structures for potential occupants of a cell
        boolean[][] claimed = new boolean[width][height];
        int[] cells = new int[width * height - numPlates]; // fixme: too much
        int numEmptyCells = 0;

        // select random starting points for all plates
        for (int plate = 1; plate <= numPlates; plate++) {
            int x = random.nextInt(width);
            int y = random.nextInt(height);

            // make sure this cell is unoccupied
            while (grid[x][y] != 0) {
                x = random.nextInt(width);
                y = random.nextInt(height);
            }

            numEmptyCells = setCell(x, y, plate, cells, numEmptyCells, claimed);
            claimed[x][y] = true;
        }

        // fill the rest of the grid
        while (numEmptyCells > 0) {
            int index = random.nextInt(numEmptyCells);

            // remove the selected cell from the list
            int cell = cells[index];
            cells[index] = cells[--numEmptyCells];

            int x = cell % width;
            int y = cell / width;
            int plate = selectPlate(cells, x, y);

            numEmptyCells = setCell(x, y, plate, cells, numEmptyCells, claimed);
        }
    }

    private int setCell(int x, int y, int plate, int[] cells, int cellsIndex, boolean[][] claimed) {
        assert plate > 0 && plate <= numPlates;

        grid[x][y] = plate;

        int left = (x == 0 ? width - 1 : x - 1);
        int right = (x == width - 1 ? 0 : x + 1);
        int up = (y == 0 ? height - 1 : y - 1);
        int down = (y == height - 1 ? 0 : y + 1);

        if (!claimed[left][y]) {
            cells[cellsIndex++] = left + y * width;
            claimed[left][y] = true;
        }

        if (!claimed[right][y]) {
            cells[cellsIndex++] = right + y * width;
            claimed[right][y] = true;
        }

        if (!claimed[x][up]) {
            cells[cellsIndex++] = x + up * width;
            claimed[x][up] = true;
        }

        if (!claimed[x][down]) {
            cells[cellsIndex++] = x + down * width;
            claimed[x][down] = true;
        }

        return cellsIndex;
    }

    private int selectPlate(int[] cells, int x, int y) {
        // find all adjacent plates
        int left = (x == 0 ? width - 1: x - 1);
        int right = (x == width - 1 ? 0 : x + 1);
        int up = (y == 0 ? height - 1 : y - 1);
        int down = (y == height - 1 ? 0 : y + 1);

        final int plates[] = new int[4];
        int count = 0;

        if (grid[left][y] != 0) plates[count++] = grid[left][y];
        if (grid[right][y] != 0) plates[count++] = grid[right][y];
        if (grid[x][up] != 0) plates[count++] = grid[x][up];
        if (grid[x][down] != 0) plates[count++] = grid[x][down];

        // select on of the adjacent plates at random
        return plates[random.nextInt(count)];
    }

    public static void main(String[] args) throws Exception {
        if (args.length != 3) {
            System.err.println("USAGE: java ..OrganicFill <width> <height> <number-of-plates>");
            System.exit(1);
        }

        int width = Integer.parseInt(args[0]);
        int height = Integer.parseInt(args[1]);
        int numPlates = Integer.parseInt(args[2]);

        OrganicFill main = new OrganicFill(width, height, numPlates);
        main.fill();

        Random random = new Random(0);
        int[] colors = new int[numPlates];
        for (int i = 0; i < numPlates; i++) {
            colors[i] = random.nextInt(0xFFFFFF);
        }

        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        for (int y = 0; y < height; y++) {
            for (int x = 0; x < width; x++) {
                int color = main.grid[x][y] > 0 ? colors[main.grid[x][y] - 1] : 0;
                image.setRGB(x, y, color);
            }
        }

        JLabel map = new JLabel(new ImageIcon(image.getScaledInstance(500, 500, image.SCALE_FAST)));
        JOptionPane.showMessageDialog(null, map);
    }
}

```

Here, I'm using a second grid (`claimed`) and an array (`cells`) in which I keep track of all cells that have at least one adjacent plate. The `cells` array basically functions as a list for all such cells from which the next cell to assign is selected at random. The `claimed` array allows for fast checking of whether a cell has already been added to `cells` or not.

The main loop is in `fill`: first, some random starting points are determined for each plate. Then a loop fills all remaining cells of the grid.

The real smarts is in `setCell`: this method does not only update the grid itself, but also the "claims" array for the cells immediately above, below, left of and right of the given cell.

A third method `selectCell` randomly selects for a given cell one of the plates that made a claim for that cell.

---

EDIT: 500x500 with 10 plates in 33ms

EDIT2: 500x500 with 10 plates in 19ms with updated code

# Answer
> 0 votes
Since you mention voronoi, i'll give my c# voronoi implementation

```
private void Voronoi(int[,] points, int minDelta)
{
    for (int i = 0; i < wid; i++)
    {
        for (int j = 0; j < hei; j++)
        {
            float minDist = 999999999f;
            float minDist2 = 999999999f;
            float minV = 0f;
            for (int p = 0; p < points.GetLength(0); p++)
            {
                int pX = points[p, 0];
                int pY = points[p, 1];
                float pV = (float)(points[p, 2])/255f; //0..1
                Double Dist1X = Math.Abs((i - pX));
                Double Dist1Y = Math.Abs((j - pY));
                Double Dist2X = wid - Dist1X;
                Double Dist2Y = hei - Dist1Y;
                /*to grant seamless I take the min between distX and wid-distX
                 |                       |
                 |                       |     ----------- = Dist1X
                 |...i-----------X.......|     ..........  = Dist2X
                 |                       |
                 */
                Dist1X = Math.Min(Dist1X, Dist2X);
                /*to grant seamless I take the min between distY and hei-distY*/
                Dist1Y = Math.Min(Dist1Y, Dist2Y);
             //euclidian metric
                float dist = (float)Math.Sqrt(Dist1X * Dist1X + Dist1Y * Dist1Y);

                // add pseudorandom perturbation to plates/cells
                float a = (float)PerlinNoise2d(pX, pY, wid, hei, wid/4, hei/4, 0.5f, 1, 0.5f);
                dist = dist * (a - 0.5f)*2;
                if (dist <= minDist)
                {
                    minDist2 = minDist;
                    minDist = dist;
                    minV = pV;
                }
                else
                {
                    if (dist <= minDist2)
                        minDist2 = dist;
                }
            }

//store the i,j pixel value
            setV(i, j, minV);
        }
    }
}

```

Where `wid` and `hei` are the map dimensions , `setV()` is the sets the pixel i,j at value minV, `PerlinNoise2d` is autoexplicative, but you can use any pseudo random generator (same coord same value)

Here a 256X256 example in 1.7 seconds

---
Tags: 2d, algorithm, procedural-generation, random
---


# Question
Title: Which is the best method implementing a background scrolling for game in libgdx?
My question is very simple I am new to libgdx development, which is the best approach implementing a background that is to make the background move in y direction

1)My First approach is drawing the background image 10 times towards positive y direction using camera.translate(x,y) function to move camera from bottom to top 2)second approach is to make the camera still while making the background scroll ie drawing the background frame by frame updating the position each time

Can you please suggest which is the best approach?

# Answer
In my game i have 3 background textures (maximum amount that can fit on screen). I initialize them so they are placed in a row. And this is how i update them:

```
    protected void updateBackground(Background background) {
        if (background.position.x < camera.position.x
                - (background.width + camera.viewportWidth / 2))
            background.position.x += 3 * background.width;
    }

```

This code just checks if background texture is out of screen and if so places it in front of other background textures.
> 0 votes

# Answer
I would have one background sprite. Then offset the uv of that sprite for when the camera moves. The sprite's texture will have to be set to repeating. The background sprite will need to be locked to camera position.

Very similar to this Repeat texture in a scrolling game
> 0 votes

# Answer
I have done something like this and it works great! Thank you all for your valuable suggesitions!

```
initiate()
{
  bg1 = new Sprite( backgroundImage );
  bg2 = new Sprite( backgroundImage );
}

update()
{
  position1 = position1 - 3;
  position2 = position2 - 3;

  if( position2 <= -height )
    position2 = height;

  if( position1 <= -height )
    position1 = height;
}

render()
{
  bg1.setPosition( positionX, position2 );
  bg2.setPosition( positionX, position1 );
  bg2.draw( batch );
  bg1.draw( batch );
}

```
> 0 votes

---
Tags: libgdx, scrolling
---


# Question
Title: Should I cull off-screen objects in SDL2
My game will have a large number of objects moving offscreen at any given time, can i just render them all with `SDL_RenderCopy` even though they are off screen or should I only render them if they are on-screen? I will probably have many hundreds or throusands of objects loaded at a time. My dev machine is quite overpowered for what I'm trying to do but I am conserned that I just won't notice a preformance drop that may affect players with less powerful computers.

So, will checking if each object is on screen before drawing increase performance/lower CPU load, or can I safely let SDL handle this with clipping?

# Answer
> 6 votes
As SDL2 is but a wrapper over the graphics API (OpenGL or DirectX), out-of-view triangles will be culled by the GPU before reaching the rasterizer. As GPU's have hardwired or heavily optimized triangle culling, my guess is that the GPU will be faster than the CPU to do it.

But !

The CPU/GPU bandwidth comes into play. The GPU may well be a triangle munching champion, but you need to send it those triangles. When the numbers increase, it's possible that you'll encounter bandwidth saturation well before the GPU starts grinding. In which case you'd need to, again, cut down the number of triangles you try to squeeze through.

In the end, the answer is as always with graphics programming : profile, and test. Results will vary wildly between hardware configurations, drivers versions, and your particular code.

---
Tags: sdl, sdl2
---


# Question
Title: Load new Java classes from a folder automatically at startup
I want to make my game-coding very flexible; so I wanted to make the game **automatically** load new Mobs from a folder named "mobs".

This must be **only at startup**; not while it's already running.

I just want to **put a file** with a name like "mouse.jar" (or others -\> dynamic) into this folder, and the game should **load** it at startup.

I already saw this in "Robocode" (Robots) and "MCForge" (whole Mods), so it must be possible.

**Can anyone tell me, how is it possible to load classes as resources in game at startup, regardless of the quantity?**

# Answer
> 2 votes
You require three things to load code from files and do things with the types and functions defined in those modules.

* A way to load a module from disk or memory.
* A way to, given a module, enumerate and use the functionality present in the module.
* A bunch of types and signatures designed to be shared between the modules, so the code has something to speak in terms of.

In C++ on Windows, you've got LoadLibrary, GetProcAddress, and function pointers/classes.

In C++ on POSIXy platforms, you've got dlopen, dlsym, and the same.

In Java you have ClassLoader, reflection, and common interfaces. The key in Java is that ClassLoader doesn't only know how to load a class by a given package name from your classpath, but can also load arbitrary .class files from file or memory.

---
Tags: java
---


title: Trying to implement gun cooldowns in C#

text:
# Question
Title: Trying to implement gun cooldowns in C#
My aim is to allow my player to shoot 3 bullets at a time. Between shooting these 3 bullets the player should wait a very small interval (so that they don't all get fired at the same time) - call this `gunLocalCooldown`. After shooting these 3 bullets, the player should wait a much longer interval - call this `gunGlobalCooldown`. I also have a boolean `canShoot` that must be true for a bullet to fire (i.e. when the gun is off cooldown).

Here is the code responsible for this in `Update()`:

```
// If space is pressed, the gun is off local cooldown and the player can shoot
if (Input.GetKey (KeyCode.Space) && Time.time >= gunLocalCooldown && canShoot) {
    // Bullet prefab
    Rigidbody bPrefab = Instantiate (bulletPrefab, transform.Find ("Bullet").position, Quaternion.identity) as Rigidbody;
    bPrefab.AddForce (transform.up * bulletForce);
    gunLocalCooldown = Time.time + 0.12f;
    bulletCounter++;
    // If 3 bullets are shot, wait for gunGlobalCooldown then reset counter to 0 and allow him to shoot
    if(bulletCounter == 3) {
        gunGlobalCooldown = gunLocalCooldown + 0.8f;
        if(Time.time >= gunGlobalCooldown) {
            gunGlobalCooldown = Time.time + 0.8f;
            canShoot = true;
        } else {
            canShoot = false;
        }
    bulletCounter = 0;
    }
}

```

What happens right now: after player shoots 3 bullets he can no longer shoot. The problem is that after canShoot is set to false, it is never set to true again (it should be set to true if the player is able to fire 3 bullets again) - and after playing around with this code for a while I still can't figure out how to do this.

As well as this, I want the player to be able to fire 3 bullets again if he shoots even 1 or 2 bullets as long as the global cooldown is complete.

Any ideas?

# Answer
> 4 votes
Your code is very scrambled. You have all your time relative variables inside the shooting loop. and the instantiation code too. Why? Why not simply make it like this :

```
void ShootBullet() {

        Rigidbody bPrefab = Instantiate (bulletPrefab, transform.Find ("Bullet").position, Quaternion.identity) as Rigidbody;
        bPrefab.AddForce (transform.up * bulletForce);

    }

```

There, this is the ShootBullet() method, great. So if he presses Space, he shoots, and adds to the shooting counter. If he shot once, then he needs to wait for 0.12f, if he shot 3 times, then he needs to wait for 0.8f . You don't need to have two variables for this, nor do you need to have both of them inside the Space button loop. Just get both of these variables into one variable, that will control the `canShoot` variable, that will be the only one deciding if he can shoot or not.

```
void Update() {

if (Input.GetKey(Keycode.Space) && canShoot) { //if He can shoot, and he pressed space
  ShootBullet(); // then shoot
  bulletCounter++; //add to the counter
  gunCooldown = Time.time + 0.12f; // set the guncooldown to the small wait value
  canShoot = false;  //he can't shoot anymore
}

if (!canShoot && Time.time > gunCooldown) // once he can't shoot, and enough time passed
   canShoot = true; //he can now shoot

if (bulletCounter == 3) { //once he shot 3 times
gunCooldown = Time.time + 0.8f; // set the guncooldown to the longer wait value
bulletCounter = 0; //reset the bulletcount
}

}

```

And tadaa, there you have it! Clean and tidy! :)

# Answer
> 2 votes
In the frame that bulletCounter become 3, Time.time will be less than gunGlobalCooldown because this line of code:

```
gunLocalCooldown = Time.time + 0.12f;
gunGlobalCooldown = gunLocalCooldown + 0.8f;

```

so the boolean canShoot will be set to false, and this if

```
if (Input.GetKey (KeyCode.Space) && Time.time >= gunLocalCooldown && canShoot)

```

will never be triggered again.

Try simply put the increment of the Cooldown variable under the inner if, something like this:

```
if (Input.GetKey (KeyCode.Space) && Time.time >= gunLocalCooldown && canShoot) {
// Bullet prefab
Rigidbody bPrefab = Instantiate (bulletPrefab, transform.Find ("Bullet").position, Quaternion.identity) as Rigidbody;
bPrefab.AddForce (transform.up * bulletForce);
bulletCounter++;
// If 3 bullets are shot, wait for gunGlobalCooldown then reset counter to 0 and allow him to shoot
if(bulletCounter == 3) {
    if(Time.time >= gunGlobalCooldown) {
        gunGlobalCooldown = Time.time + 0.8f;
        canShoot = true;
    } else {
        canShoot = false;
    }`
gunGlobalCooldown = gunLocalCooldown + 0.8f;
bulletCounter = 0;
}
gunLocalCooldown = Time.time + 0.12f;

```

# Answer
> 1 votes
So this doesn't produce exactly the behavior you asked for but I think it might be what you're looking for anyway.

This code (syntax not exact as I don't use c#) would allow someone to sustain a fire rate of one bullet per 0.5 seconds indefinitely, but fire bursts of up to 3 bullets at a rate of one bullet per 0.12 seconds.

```
gunBurst=0.12f
gunSustained=0.5f
gunBurstCount=3
gunSustainedDelay=(gunBurstCount-0.9f)*(gunSustained-gunBurst)

// If space is pressed and the gun is cool
if (Input.GetKey (KeyCode.Space) && Time.time >= gunBurstCooldown && Time.time >= gunSustainedCooldown ) {
    // Bullet prefab
    Rigidbody bPrefab = Instantiate (bulletPrefab, transform.Find ("Bullet").position, Quaternion.identity) as Rigidbody;
    bPrefab.AddForce (transform.up * bulletForce);

    //update cooldowns
    gunBurstCooldown = Time.time + gunBurst;
    gunSustainedCooldown = Math.Max(gunSustainedCooldown + gunSustainedDelay,Time.time-gunSustainedDelay);
}

```

This simply prevents firing if the gun is too hot to sustain more fire. If you'd like some of punishment period for trying to fire faster than the sustained fire rate. See below:

```
//consts
gunBurst=0.12f
gunSustained=0.5f
gunBurstCount=3
gunReset=1.8f
gunSustainedDelay=(gunBurstCount-0.9f)*(gunSustained-gunBurst)

// If space is pressed and the gun is cool
if (Input.GetKey (KeyCode.Space) && Time.time >= gunBurstCooldown &&  Time.time >= gunResetCooldown) {
    if(Time.time >= gunSustainedCooldown){
        // Bullet prefab
        Rigidbody bPrefab = Instantiate (bulletPrefab, transform.Find ("Bullet").position, Quaternion.identity) as Rigidbody;
        bPrefab.AddForce (transform.up * bulletForce);

        //update cooldowns
        gunBurstCooldown = Time.time + gunBurst;
        gunSustainedCooldown = Math.Max(gunSustainedCooldown + gunSustainedDelay,Time.time-gunSustainedDelay);
    }else{
        gunResetCooldown= Time.time + gunReset;
    }
}

```

# Answer
> 1 votes
Coroutines are the best performance-wise. I.e.

```
void Start ()
{
    //Starting the coroutine
    StartCoroutine (Shooter());
}

IEnumerator Shooter ()
{
    if (Input.GetMouseButton(0))
    {
        //Shoots the bullet
        Rigidbody bullet = Instantiate (Bullet).GetComponent<Rigidbody>;
        bullet.AddForce (Camera.main.transform.forward * 10, ForceMode.VelocityChange);
    }

    //Waits half a second before ticking again
    yield return new WaitForSeconds (.5f);
    StartCoroutine(Shooter());
}

```

Note that this, like Update() is dependent on framerate. For a smoothly running game, it should be no problem.

# Answer
> 0 votes
The last time I faced something like this I came at it from a very different direction:

I didn't use a global cooldown at all. After a shot was fired I set a reloading timer on that barrel. Every tick the reloading timers were decremented. (Watch out for roundoff errors if you're using floating point--I simply used a certain number of game ticks.) When the user tried to fire I would look for a barrel that wasn't reloading. If I found one I fired the shot and set the timer for that barrel.

This does mean checking counters for every barrel for every cycle but it was a trivial amount of the CPU power back then and now we have probably 10,000x the CPU that I did when I did this.

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


# Question
Title: Are the prefabs stored in RAM or in the Hard disk? (Unity3D)
I have many prefabs objects (65 MB) in an Unity3D project.

My game use 100 different levels with combinations of the prefab objects.

What is better create 100 scenes or create only one scene where the prefab objects are placed with data from a XML?.

Each Scene load your own prefab objects?

Are the prefab objects loaded in the RAM when the scene is loaded or are stored in the hard disk and then loaded in the RAM when come in the scene?

# Answer
> -1 votes
The only things "stored" on the HDD, are the Assets. Everything the game needs throughout every runtime will be stored once and for all; prefabs, scripts, sounds, etc..

But indeed it's very tricky to optimize loading prefabs that you won't ultimately need all at once, but will still be loaded into the scene and take lots of RAM space, I recommend watching this.

---
Tags: unity, performance
---


title: What does cache mean?

text:
# Question
Title: What does cache mean?
I'm kinda new to the programming scene. I'm still a high school student but I want to be a game designer so I'm studying independently before I graduate to get an edge. The issue with this is that although I have learned some programming, I can't follow all of the technical terms that get thrown around on the game dev forums. One of the terms that gets used a lot is cache, and I'm wondering what that means. Outside of programming it means a secret stash of something you don't want others to know about, which could be referring to things like AI, login info or, something like that. I would like a more specific answer if anyone would be willing to give the time.

# Answer
> 6 votes
Generically in software, "Caching" means keeping a local copy of some data that either:

* Is stored elsewhere in a harder-to-reach place (like on the hard drive rather than in RAM, or hosted on a server somewhere on the web)

or

* Is time-consuming to compute from scratch

This way we can save the time of re-fetching/re-computing the data when we need it repeatedly.

.

One common place this comes up is the **CPU cache**. It turns out that accessing data in memory, though much faster than reading from the hard drive, is still painfully slow in CPU terms. To hide this delay, your processor has a tiny amount of extremely fast memory built into the chip. This is the CPU cache. Whenever your game wants to access data from main memory, the chip first checks if it the data is in the cache. If not, then it requests it from main RAM, and then stores the result in the cache so that the next time it looks for that data, it will be lightning fast.

If you access the same data a lot, the average cost of each access goes down, since you're only paying the big time hit on the first attempt to access it from RAM. That makes it seem like the memory is keeping up with the CPU better than the hardware really is. ;)

Of course, the CPU cache is limited in size, so if you're accessing data from all over memory, eventually old data will be flushed out to make room for something else. This leads to the principle of **data locality**: your program runs fastest if you do a lot of work with clusters of adjacent memory (so most of your accesses are served by the cache), rather than jumping all over the place (which "thrashes" the cache by continuously flushing & re-requesting data, so it's not as effective at hiding memory latency)

Game Programming Patterns has a great write-up on CPU caching and data locality if you'd like more information. It's a huge field and I've only described a shallow version of it above.

.

Another common place you'll see caching is in **web development**. Your browser typically doesn't re-download a website from scratch on every visit. Instead, it keeps a cache of "temporary internet files" on your hard drive, and only re-downloads files which might have changed (according to the caching information provided when they were last downloaded). This saves on bandwidth and makes loading faster.

In turn, the server you're requesting the files from is probably caching them too, so it doesn't have to look them up from disc (or another server) if the same file is requested by multiple users.

.

In game development, an engine that streams assets like textures on demand might maintain a cache of recently-used textures, on the hunch that they might be needed again soon. For instance, as you walk away from a village, the engine removes the objects inside the buildings, knowing they won't be visible. But it's likely to keep (the small mips of) their textures in its asset cache, so that if you turn around and run back to the village, it can display them again quickly without needing to load the textures off the hard drive (or worse, off of the game disc).

A game script that does target selection might keep a cache of recent target candidates that it uses for its most frequent updates, and only query for a new set of candidates every n frames, to reduce how often it performs what might be an expensive search through all the possible targets in the scene.

---
Tags: software-engineering
---


# Question
Title: Is Physics2D.BoxCast a safe alternative to a row of raycasting?
Raycasting in rows is a common practice.

1. Is using the Physics 2D BoxCast function a good alternative to using multiple raycasts spread out (an example use being collision detection in a custom character controller script)?
2. There is limited documentation on boxcasting. Would boxcasting be too intensive or more friendly to call each frame?

# Answer
> 2 votes
Box cast would probably be more performant since it's only checking 4 vertices but it'll definitely be more accurate, at least depending on what you want. Good idea!

Example use:

```
RaycastHit2D raycast = Physics2D.BoxCast (

    //Starting point of box
    Vector2.zero,

    //Size of the box
    new Vector2 (2,2),

    //Angle of box,
    0f,

    //Direction to cast
    Vector2.right,

    //Distance to cast
    5f

);

```

This BoxCasts starting from Vector2d.zero with a square of length 2 in the direction of (0,1), for a distance of 5. Conceptually, this is like dragging a 2x2 square from (0,0) to (0,5) and detecting any collisions along the way.

---
Tags: unity, unityscript, raycasting
---


title: Vertex ordering with THREEjs's exporter

text:
# Question
Title: Vertex ordering with THREEjs's exporter
I'm using THREEjs's exporter to export a 2D polygon plane. The resulting JSON gives me the vertices. I'm trying to properly order these vertices as to make the actual polygon shape, without luck.

Right: Default vertex order

Left: Actual order

I manually put the needed order together and found it to be this. `0,1,2,3,4,5,6,7,8,9,11,13,17,16,15,19,21,22,23,25,27,29,39,38,37,36,35,34,33,32,31,30,28,26,24,20,18,14,12,10` (element represents index in default order).

Is there a pattern to this ordering? Does the JSON file reveal more information on how to properly order it? Seems the only other information in there is the `faces` array. I do not understand how to read it or what it represents.

# Answer
> 2 votes
As you guessed, you can know the vertices order by checking the faces. To know how faces could be read, check this link.

Next follows an example (C#) on how it could be done (no errors checking).

```
public class Face
{
    static int TYPE_BITMASK_TRIANGLE_QUAD = 0;
    static int TYPE_BITMASK_FACE_MATERIAL = 1;
    static int TYPE_BITMASK_FACE_UV = 2;
    static int TYPE_BITMASK_FACE_VERTEX_UV = 3;
    static int TYPE_BITMASK_FACE_NORMAL = 4;
    static int TYPE_BITMASK_FACE_VERTEX_NORMAL = 5;
    static int TYPE_BITMASK_FACE_COLOR = 6;
    static int TYPE_BITMASK_FACE_VERTEX_COLOR = 7;

    private static string[] DATA_BLOCK_SEPARATOR = { ", " };
    private static char[] DATA_SEPARATOR = { ',' };

    private byte _typeBitmask;
    public bool HasMaterial = false;
    public bool HasFaceUv = false;
    public bool HasFaceVertexUv = false;
    public bool HasFaceNormal = false;
    public bool HasFaceVertexNormal = false;
    public bool HasFaceColor = false;
    public bool HasFaceVertexColor = false;

    public int VerticesAmount { get; private set; }
    public int[] VertexIndex;
    public int MaterialIndex;
    public int FaceUv;
    public int[] FaceVertexUv;
    public int FaceNormal;
    public int[] FaceVertexNormal;
    public int FaceColor;
    public int[] FaceVertexColor;

    private Face() : this(3) { }

    private Face(int verticesAmount)
    {
        this.VerticesAmount = verticesAmount;
        this._typeBitmask = (byte)(verticesAmount == 3 ? 0 : 1);
        this.VertexIndex = new int[verticesAmount];
        this.FaceVertexUv = new int[verticesAmount];
        this.FaceVertexNormal = new int[verticesAmount];
        this.FaceVertexColor = new int[verticesAmount];
    }

    public static Face Triangle()
    {
        return new Face(3);
    }

    public static Face Quad()
    {
        return new Face(4);
    }

    public Edge[] GetEdges()
    {
        return GetEdges(this);
    }

    public static Edge[] GetEdges(Face face)
    {
        Edge[] edges = new Edge[face.VerticesAmount];
        for (int i = 0; i < face.VerticesAmount - 1; i++)
        {
            edges[i] = new Edge(face.VertexIndex[i], face.VertexIndex[i + 1]);
        }
        edges[face.VerticesAmount - 1] = new Edge(face.VertexIndex[face.VerticesAmount - 1], face.VertexIndex[0]);
        return edges;
    }

    public static List<Face> Deserialize(string json)
    {
        // Split json string into data blocks
        string[] dataBlocks = json.Split(DATA_BLOCK_SEPARATOR, StringSplitOptions.None);

        // Set amount of vertices and types of data to read
        int verticesAmount;
        bool hasMaterial, hasFaceUv, hasFaceVertexUv, hasFaceNormal, hasFaceVertexNormal, hasFaceColor, hasFaceVertexColor;
        byte typeBitmask = byte.Parse(dataBlocks[0]);
        verticesAmount = IsBitSet(typeBitmask, TYPE_BITMASK_TRIANGLE_QUAD) ? 4 : 3;
        hasMaterial = IsBitSet(typeBitmask, TYPE_BITMASK_FACE_MATERIAL);
        hasFaceUv = IsBitSet(typeBitmask, TYPE_BITMASK_FACE_UV);
        hasFaceVertexUv = IsBitSet(typeBitmask, TYPE_BITMASK_FACE_VERTEX_UV);
        hasFaceNormal = IsBitSet(typeBitmask, TYPE_BITMASK_FACE_NORMAL);
        hasFaceVertexNormal = IsBitSet(typeBitmask, TYPE_BITMASK_FACE_VERTEX_NORMAL);
        hasFaceColor = IsBitSet(typeBitmask, TYPE_BITMASK_FACE_COLOR);
        hasFaceVertexColor = IsBitSet(typeBitmask, TYPE_BITMASK_FACE_VERTEX_COLOR);

        List<Face> faces = new List<Face>();
        Face face;
        int dataBlockIndex = 1;

        // Build Face instances until all data blocks parsed
        while (dataBlockIndex < dataBlocks.Length)
        {
            face = new Face(verticesAmount);
            face._typeBitmask = typeBitmask;
            face.HasMaterial = hasMaterial;
            face.HasFaceUv = hasFaceUv;
            face.HasFaceVertexUv = hasFaceVertexUv;
            face.HasFaceNormal = hasFaceNormal;
            face.HasFaceVertexNormal = hasFaceVertexNormal;
            face.HasFaceColor = hasFaceColor;
            face.HasFaceVertexColor = hasFaceVertexColor;

            // Parse vertices
            face.VertexIndex = ParseBlock(dataBlocks[dataBlockIndex]);
            dataBlockIndex++;

            // Parse other data, as needed
            if (hasMaterial)
            {
                face.MaterialIndex = int.Parse(dataBlocks[dataBlockIndex]);
                dataBlockIndex++;
            }
            if (hasFaceUv)
            {
                face.FaceUv = int.Parse(dataBlocks[dataBlockIndex]);
                dataBlockIndex++;
            }
            if (hasFaceVertexUv)
            {
                face.FaceVertexUv = ParseBlock(dataBlocks[dataBlockIndex]);
                dataBlockIndex++;
            }
            if (hasFaceNormal)
            {
                face.FaceNormal = int.Parse(dataBlocks[dataBlockIndex]);
                dataBlockIndex++;
            }
            if (hasFaceVertexNormal)
            {
                face.FaceVertexNormal = ParseBlock(dataBlocks[dataBlockIndex]);
                dataBlockIndex++;
            }
            if (hasFaceColor)
            {
                face.FaceColor = int.Parse(dataBlocks[dataBlockIndex]);
                dataBlockIndex++;
            }
            if (hasFaceVertexColor)
            {
                face.FaceVertexColor = ParseBlock(dataBlocks[dataBlockIndex]);
                dataBlockIndex++;
            }

            // Add the face to the resulting list
            faces.Add(face);
        }

        // Return the list
        return faces;
    }

    private static bool IsBitSet(int value, int position)
    {
        return (value & ( 1 << position )) == 0 ? false : true;
    }

    private static int[] ParseBlock(string dataBlock)
    {
        string[] data = dataBlock.Split(DATA_SEPARATOR);
        int[] result = new int[data.Length];
        for (int i = 0; i < data.Length; i++)
        {
            result[i] = int.Parse(data[i]);
        }
        return result;
    }

    public static List<int> GetOutline(List<Face> faces)
    {
        List<int> sortedVertices = new List<int>();
        Dictionary<long, Edge> edges = new Dictionary<long, Edge>();

        // Get the edges in the outline
        foreach (Face face in faces)
        {
            foreach (Edge edge in face.GetEdges())
            {
                if (edges.ContainsKey(edge.Id))
                {
                    // Remove any edge shared by 2 faces
                    edges.Remove(edge.Id);
                }
                else
                {
                    // Add new edges
                    edges.Add(edge.Id, edge);
                }
            }
        }

        // Assuming that at least 1 triangle will have 1 edge starting at vertex 0
        long firstEdgeId = edges.First(ed => (ed.Key & 0x7FFFFFFF00000000) == 0).Key;

        // Add the first edge's vertices to the resulting list
        Edge nextEdge = edges[firstEdgeId];
        sortedVertices.Add(nextEdge.A);
        int nextVertex = nextEdge.B;
        sortedVertices.Add(nextVertex);
        // Remove the edge from
        edges.Remove(nextEdge.Id);

        // For all remaining edges
        while (edges.Count > 0)
        {
            // Search the next edge, sharing a vertex with last edge
            nextEdge = edges.First(ed => (ed.Key & 0x7FFFFFFF00000000) >> 32 == nextVertex).Value;
            // Add the new vertex to the resulting list
            sortedVertices.Add(nextVertex);
            // Remove the edge from remaining edges
            edges.Remove(nextEdge.Id);
            // Set the vertex to use in next search
            nextVertex = nextEdge.B;
        }

        // return the resulting list of vertices (sorted and ready for your use)
        return sortedVertices;
    }
}

public class Edge
{
    public int A;
    public int B;
    public long Id;

    public Edge(int a, int b)
    {
        this.A = a;
        this.B = b;
        this.Id = a << 32 + b;
    }
}

```

---
Tags: vertex, three.js, export
---


title: Scrolling background loop

text:
# Question
Title: Scrolling background loop
I'm trying to scroll my background forever and so I'm using the background image twice. When the first one goes off screen, it should relocate to the end of the second one. However, there seems to be a black bar inbetween the two images and so it seems that the image is not being moved into place quick enough. What would be the algorithm to do such a thing to give the illusion of a continuous background? I've got this at the moment (which loops, but with a black bar in between the background image)

```
 GeneralTransform gt = bg1Canvas.TransformToVisual(Application.Current.RootVisual as UIElement);
        Point bg1Offset = gt.Transform(new Point(0, 0));

 GeneralTransform gt2 = bg2Canvas.TransformToVisual(Application.Current.RootVisual as UIElement);
        Point bg2Offset = gt2.Transform(new Point(0, 0));

 bg1.TranslateX -=  playerVel.X; //bg1 and bg2 are the composite transforms for the canvas
 bg2.TranslateX -=  playerVel.X;

 if (bg1Offset.X < -bg_width)
     bg1.TranslateX -= bg1Offset.X - bg_width;
 if (bg2Offset.X < -bg_width)
     bg2.TranslateX -= bg2Offset.X - bg_width;

```

Any ideas?

Edit - Updated code Edit 2: New code with three images (all same width). Works for the first few scrolls, then suddenly stops working and no background is displayed.

```
if (bg1Offset.X < -bg_width )
                bg1.TranslateX = bg3Offset.X+bg_width;

            if (bg2Offset.X < -bg_width )
                bg2.TranslateX = bg1Offset.X + bg_width;

            if (bg3Offset.X < -bg_width)
                bg3.TranslateX = bg2Offset.X + bg_width;

```

# Answer
> 4 votes
Try making you background image bigger than your screen.

This can be done by duplicating the image in paint or something.

Start at the beginning of the image and scroll along and when you get near the end of the image jump back to displaying the beginning of the image.

Try to jump before you reach the end of the image.

This will save memory and run faster.

Sorry I cant give an example but I don't recognise the language your using.

# Answer
> 3 votes
I've written an article about a general purpose solution that lets you scroll an image infinitely in every direction even if your camera is transformed. But it's done in XNA with HLSL and relies on the texture addressing mode being set to wrap, so I'm not sure if it could be translated to Silverlight. Here's the link:

http://www.david-gouveia.com/scrolling-textures-with-zoom-and-rotation/

For a less general purpose solution, that doesn't use a vertex shader you could try the following link where I describe two other ways to solve it (the first should work anywhere since you only need the ability to choose a source rectangle when drawing):

http://www.david-gouveia.com/scrolling-textures-in-xna/

**EDIT:**

*To give a general description of the techniques linked above...*

Basically, your way of scrolling the background by drawing it twice and moving these two pieces around when the player moves outside a certain range, is the way I first implemented texture scrolling.

But soon I figured there were several limitations to that approach, and throughout the years found about a few other ways to do this that are much more flexible and general.

For instance, first I wanted to have the background scroll diagonally instead of horizontally, and so the original technique broke. Later on I found a way to achieve the same thing in a much easier way so I changed to that. Eventually I wanted to be able to scale and rotate the camera as well so had to go even further.

Here's a summary of all three that I described on my blog (code samples are XNA/HLSL). If possible, I really recommend the first one, but of course it depends on your platform's limitations.

---

# Technique 1

1. Create a fullscreen textured quad (a SpriteBatch.Draw with *destination rectangle* set to the entire screen will do just fine) and map the texture you want to scroll to it.
2. Set the texture addressing mode to wrap so that it automatically wraps whenever the texture coordinates leave the normalized \[0,1\] range.
3. Use a vertex shader to generate new texture coordinates for your quad's vertices based on your camera's transform. This transform is pretty much the inverse of your view matrix, but with translations being done in texture space (i.e. dividing the translation amount by the texture size).

I use this vertex shader (where 99% of it is boilerplate needed for SpriteBatch to work - only the last line is new):

```
sampler TextureSampler : register(s0);
float2   ViewportSize;
float4x4 ScrollMatrix;

void SpriteVertexShader(inout float4 color : COLOR0, inout float2 texCoord : TEXCOORD0, inout float4 position : POSITION0)
{
  // Half pixel offset for correct texel centering.
   position.xy -= 0.5;

   // Viewport adjustment.
   position.xy = position.xy / ViewportSize;
   position.xy *= float2(2, -2);
   position.xy -= float2(1, -1);

    // Transform our texture coordinates to account for camera
    texCoord = mul(float4(texCoord.xy, 0, 1), ScrollMatrix).xy;
}

```

And pass it this matrix, which is calculated using the properties of my camera:

```
public Matrix GetScrollMatrix(Vector2 textureSize)
{
    return Matrix.CreateTranslation(new Vector3(-Origin / textureSize, 0.0f)) *
             Matrix.CreateScale(1f / Zoom) *
             Matrix.CreateRotationZ(Rotation) *
             Matrix.CreateTranslation(new Vector3(Origin / textureSize, 0.0f)) *
             Matrix.CreateTranslation(new Vector3(Position / textureSize, 0.0f));
}

```
* Pros: Single quad being drawn to cover the entire screen. Works perfectly with a zoomed and rotated camera too.
* Cons: Needs vertex shader and texture address set to wrap.

---

# Technique 2

1. Same as Technique 1 Step 1
2. Same as Technique 1 Step 2
3. Play around with SpriteBatch.Draw *source rectangle* by setting the rectangle's X/Y to be the camera's position and the rectangle's Width/Height to be the screen's size.

Example:

```
spriteBatch.Begin(SpriteSortMode.Deferred, null, SamplerState.LinearWrap, null, null);
spriteBatch.Draw(texture, position, new Rectangle(-scrollX, -scrollY, texture.Width, texture.Height), Color.White);
spriteBatch.End();

```
* Pros: Simplest method. Doable in 2/3 lines of code. No need for vertex shader either.
* Cons: Still needs texture wrap addressing mode. You can still move the camera around in every direction but you can't rotate it. You can however zoom the camera with just a little trick: just scale the source rectangle's size along inversely to the camera's zoom (i.e. the larger the camera zoom, the smaller the rectangle - just divide the original rectangle size by the zoom factor).

---

# Technique 3

This method doesn't need anything other than being able to specify a source rectangle on drawing.

1. It's a variation of your idea of drawing the background twice depending on the player's position, but enlarged to all four directions (so that it also repeats up down), and instead of moving the pieces around, you move their source rectangles (so the pieces stay still but the content you see changes).
2. Basically draw the texture four times like in the image below, and depending on the camera's position you draw more, or less of each of them to give the impression that the camera is moving.

Something like:

```
Rectangle source1 = new Rectangle(0, 0, texture.Width - scrollX, texture.Height - scrollY);
Rectangle source2 = new Rectangle(texture.Width - scrollX, 0, scrollX, texture.Height - scrollY);
Rectangle source3 = new Rectangle(0, texture.Height - scrollY, texture.Width - scrollX, scrollY);
Rectangle source4 = new Rectangle(texture.Width - scrollX, texture.Height - scrollY, scrollX, scrollY);

Vector2 position1 = new Vector2(position.X + scrollX, position.Y + scrollY);
Vector2 position2 = new Vector2(position.X, position.Y + scrollY);
Vector2 position3 = new Vector2(position.X + scrollX, position.Y);
Vector2 position4 = new Vector2(position.X, position.Y);

spriteBatch.Begin();
spriteBatch.Draw(texture, position1, source1, Color.White);
spriteBatch.Draw(texture, position2, source2, Color.White);
spriteBatch.Draw(texture, position3, source3, Color.White);
spriteBatch.Draw(texture, position4, source4, Color.White);
spriteBatch.End();

```

And you also need to be careful and wrap the scrollX and scrollY values around so that they don't leave the texture.

* Pros: Doesn't need many features to implement.
* Cons: Can only move camera around, no other transformations.

---

# Answer
> 1 votes
This may be for XNA not silverlight (still C# though), but this is a good tutorial to achieve what you want.

# Answer
> 1 votes
I think you need to draw the image three times: Imagine your background is `\/`

```
1.      [ /\ ] \/ \/
2.    \ [ /\ ] / \/
3.    \/[ \/ ] \/
4. \/ \ [ /\ ] /
5.      [ /\ ] \/ \/

```

(assuming Right ==\> Left scrolling)

If you're seeing a black bar (I presuem you are clearing to `Color.Black`) you probably have an error in your positioning code.

# Answer
> 0 votes
I have done something like this and works great.. background scrolls from top to bottom. To make black bar disappear add an offset to size of second background

```
initiate() {
  offset=2 ;
  bg1=new Sprite(backgroundImage);
  bg2=new Sprite(backgroundImage);
  bg1.setSize(width, height);
  bg2.setSize(width, height+offset);
  //ADD AN OFFSET HERE YOU CAN SEE THE BLACK BAR DISAPPEAR
}

update() {
  position1=position1-3;
  position2=position2-3;
  if(position2<=-height) position2= height;
  if(position1<=-height) position1=height;
}

render() {
  bg1.setPosition(positionX, position2);
  bg2.setPosition(positionX, position1);
  bg2.draw(batch);
  bg1.draw(batch);
}

```

---
Tags: c#, 2d, side-scroller, silverlight
---


# Question
Title: useful way for coloring 3ds object in opengl
I have been working in making plane in blender and it has many materials over than 90 , and now I need it in an opengl project with c++ , but as you know if I but the 3ds file the plane color is totally white so I have to color back all the parts of the plane and it's getting really hard with all the materials I have , any useful thing I can make ? .

# Answer
> 1 votes
There are a number of ways to color objects in OpenGL. You can specify colors as vertex attributes. You can apply textures to objects by supplying texture coordinates and the actual textures. You can write fragment shaders to determine the color programatically. Or you can use a combination of those 3 things (and possibly others).

Does your "3ds" file contain textures or at least the paths of the textures on disk? If so, you can probably load them and use them directly.

If you want a more detailed answer, you'll need to supply more information, such as how you're loading the file, what the file contains, etc. Also, let us know which version of OpenGL you're using, as the answer will depend greatly on that.

---
Tags: opengl, c++, blender
---


# Question
Title: How do we make online games deterministic?
I am trying to understand how networking in games work as I am trying to make an online game myself. I can't grasp how it is possible to synchronize the players, in order to make the game deterministic. I found an article saying this:

> in order to ensure that the game plays out identically on all machines it is necessary to wait until all player’s commands for that turn are received before simulating that turn. This means that each player in the game has latency equal to the most lagged player.

This makes sense and I also came to the same conclusion after hours of drawing graphs with various scenarios. However, there are some games where one player can have 500ms delay, and another player could have 40ms delay. In this case, how is the game deterministic ?

Lets name players with `40ms`, `500ms` delay: **Player40**, **Player500**

Lets say that Player40, shoots Player500 with an instant laser shot at *T1 = 0ms*. Exactly 40ms after the Player40 actually clicked with his mouse to shoot (so *T2 = 40ms*), The "laser shooting event" registered on the server and returned "ok, you can execute laser shoot" to Player40. So, the shot is being applied on Player40's machine and on his screen he sees that he killed Player500, and the corpse is lying on (x1,y1,z1).

Meanwhile, what happened on Player500's machine, was that Player500 was running straight. A few moments later he sees a laser a few feet behind him, he dies even though the laser didn't hit him, and his corpse is lying on (x2,y2,z2).

Since this scenario never happens in some games, does this mean that those games are deterministic ? How is something like this possible, without forcing all players to get a delay equal to the delay of the most lagging player ?

# Answer
It's actually the other way around. Games are made deterministic to be online.

The basic idea is to send commands rather than game state. If you have a function F(X) = Y and you need everyone's Y to be the same, you can send X instead of Y. The reason why this happens in the first place is because sometimes commands are more efficient than game states bandwidth-wise. In an RTS game, there can be 200+ units at one time so sending a command is better than replicating 50 positions, rotations, healths, etc.. There are several other benefits like 100% game state cheat proof and small replay sizes.

Unfortunately, deterministic games require deterministic simulations which floating-point numbers cannot do for you. This means Box2D, PhysX, and Bullet are all out of the window without clever floating-point tricks, but even with those low-level modifications, they can't be cross-platform deterministic.

Fortunately, you don't have to code your own physics engine or lockstep logic if you're using Unity. I'm working on a deterministic physics engine with lockstep multiplayer, all integrated with Unity3D. If you'd like to sign up for the Beta and give it a shot, here's the link: http://forum.unity3d.com/threads/dphysics-beta-cross-platform-deterministic-physics-engine.318827/.

Sorry for the shameless plug :). Anyways, if you're not using Unity, I'll give you a few details about a lockstep framework that'll be good to know anyways.

Lockstep games think in frames, basically an integer that goes up every time the game is simulated. On frame 100, everyone's simulation should be the exact same but everyone doesn't have to be on frame 100 at the same time which is how latency is handled but I'll get into that more soon.

Everyone receives the same data for every frame as well, and can't advance to the next frame if they haven't received the data for the frame. A client has to have a packet designated for frame 100 to run frame 100. Inside this packet are player commands.

i.e.: Units {1,2,3,30,127} -\> Attack -\> Unit 10 **or** Player 5 -\> Mouse Input Rotate -\> (30,20) then Player 5 -\> Shoot.

From there, you can adjust the simulation rate to be faster or slower depending on how many packets in advance you have to simulate. While others' response times don't really matter to a player, his own does. If a player has 500ms latency, he'll simply get packets 500ms later than everyone else thus his game state will be 500ms behind. The main problem is that when this player sends a command, he won't be getting it back until 500ms later which means his actions won't be responded to for a noticeably long time. This is true for authoritative server setups as well. Lag masking methods can be used like pre-played animations, instant sounds, slow acceleration, or "fake" movement.

This is the core of DPhysics Lockstep. If you're not using Unity, you could take a peek at the code anyways to see an example implementation. The DPhysics implementation uses a server instead of P2P which means no desyncs or funky code and latency is determined by a single source instead of by the slowest players.
> 8 votes

---
Tags: networking
---


title: Scaling images in Unity

text:
# Question
Title: Scaling images in Unity
I have a question about how scales work in Unity (using 5.0).

I've made a .gif image that is 100x100 pixels in size.

I put it in Resources folder under Assets.

When i drag it onto the scene it looks very tiny. Scale of it is x:1, y:1, z:1

I've added a 14 size font onto the scene as well for comparison.

You can see the little blue square underneath it.

I don't understand why the square is so small when it came from 100x100 pixel image and the text is only 14 px big.

Am i missing something really simple here?

# Answer
When importing sprites into Unity, you don't work with pixels anymore, you work with units.

By default, all sprites have : 100pixel per unit. 100px = 1 unit.

You can change this, go to your sprite in the assets, click it, and on the editor you'll see the "Pixels per Unit", which should indeed be 100. If you change it to 1, then every 1 pixel will equal 1 unit. Using units is much easier to keep track of everything, since both gameObjects and sprites have the same unit.
> 3 votes

---
Tags: unity, scale
---


# Question
Title: How to get this type of movement in LibGDX?
I want objects in my game to move randomly but always from right side of the screen to the left side. The movement must be as smooth and natural as possible, like they are following a path. Can i obtain this with the wander steering behavior without having objects going in every direction randomly? (that's what i have right now)

# Answer
Do you want the objects to move along the X axis (right to left) at the same speed or should this vary?

If it should be the same speed, simply apply some sort of random modification to their Y velocity every X frames while keeping the X velocity at a constant.

If they should slightly vary in speed from left to right, do the same as above making sure to keep the X velocity above some minimum value.

Here is a code example for objects having the same X speed:

```
public class MovingCircle(){

    // vectors for position and velocity
    Vector2 position = new Vector2();
    Vector2 velocity = new Vector2();

    // the circles will modify their direction every 3 seconds
    // changing this to an instance variable (remove static) would allow different circles to
    // change directions at different frequencies, making some more erratic than others
    private static float directionChangeFrequency = 3f;

    // these determine how much of a direction change can occur per directionChangeFrequency
    private static float minDirectionChangeAmount = 0.1f;
    private static float maxDirectionChangeAmount = 0.5f;

    private static Random randomNumberGen = new Random();

    // timer to keep track of when this moving circle should change direction
    float directionChangetimer = 0;

    public void update(float delta){
        position.x += velocity.x * delta;
        position.y += velocity.y * delta;

        directionChangetimer  += delta;

        if(directionChangetimer >= directionChangeFrequency){
            directionChangetimer -= directionChangeFrequency;
            float directionChangeRange = maxDirectionChangeAmount - minDirectionChangeAmount;
            // calculate a random change amount between the minimum and max
            float directionChangeAmount = randomNumberGen.nextFloat() * directionChangeRange + minDirectionChangeAmount;
            // flip the sign half the time so that the velocity increases and decreases
            if(random.nextBoolean()){
                directionChangeAmount  = -directionChangeAmount;
            }
            // apply the change amount to the velocity;
            velocity.y += directionChangeAmount;
        }
    }
}

```
> 1 votes

# Answer
Here is a pseudo theory on how to write it. Base on the lines drawn the max value for the Y-axis when generating random values is based off of the most extreme points from the object's center. You will also need a timer to set check distance. a more advanced version would be to apply random time to the below pseudo code to trigger more random variations based also on distance:

Start from current position of object Move object to the left and calculate object's new position from old position. If object's new position moves 'n' amount of distance from the old position in 'N' amount of milliseconds, randomly move object in the y-direction between nY and -nY. Store new position as old position. Repeat process.
> 0 votes

---
Tags: libgdx, movement, random, path
---


# Question
Title: Understanding some variable names in the quake engine
I am doing a bit of research for a project about air acceleration in the quake engine. I have a question about the names of the variables and their definitions. The code that I am looking at is

https://github.com/id-Software/Quake-III-Arena/blob/dbe4ddb10315479fc00086f08e25d968b4b43c49/code/game/bg\_pmove.c starting on line 235, PM\_Accelerate and flafla2's writeup http://flafla2.github.io/2015/02/14/bunnyhop.html , specifically the part where he shows his code. Section "Putting it All Together"

What I currently (think I) understand is this.

wishdir is the direction that the player will move, this is found by a combination of the movement keys and player's mouse movement.

I am not sure what wishspeed is

accel is the user defined acceleration value

addspeed is the difference between the untruncuated future velocity value and the current speed

accelspeed is the acceleration that will be added to the current velocity

currentspeed is obviously the player's current speed at the time of the check.

Is quake engine's wishdir flafla2's acceldir? The max velocity value limits the projection of velocity unto acceleration plus acceleration?

EDIT:

I'm beginning to understand the engine more and more after more concentrated studying of the engine. But I have two major problems/questions, that if answered, will make me extremely happy.

How exactly is wishdir calculated, and what is wishspeed/wishvel (and how is it calculated as well). I've looked around but haven't had much succesess with finding any useful information. Thanks in advance.

# Answer
> 0 votes
It appears that I have finally found wishdir, it was under my nose the whole time.

wishdir is created when you do the function `VectorCopy (wishvel, wishdir);`

```
FORCEINLINE void VectorCopy( const Vector& src, Vector& dst )

{
    CHECK_VALID(src);
    dst.x = src.x;
    dst.y = src.y;
    dst.z = src.z;
}

```

---
Tags: source-engine, quake3
---


# Question
Title: Unity: How to get a GameObject programmatically?
I have created a prefab. In Unity Scene editor, I dragged the prefab into the scene and named it PrefabA (this is a GameObject instance of the Prefab).

Now, I need to update the PrefabA position.
How can I access the GameObject "PrefabA" during runtime via script?

```
GameObject prefab =  GameObject.Find("Canvas/PrefabA").GetComponent<GameObject>();

```

The code above throws `Object reference not set to an instance of an object.`

# Answer
> 2 votes
Now that I see your problem, this has absolutely nothing in relation to Prefabs, your error resides in addressing the object you're looking for:

```
 GameObject.Find("Canvas/PrefabA").GetComponent<GameObject>();

```

Try doing this :

```
GameObject prefab =  GameObject.Find("Canvas").transform.Find("PrefabA").gameObject;

```

or this :

```
 GameObject prefab =  GameObject.Find("Canvas/PrefabA").gameObject;

```

Tip : You don't need to use `GetComponent<GameObject>();`, using `gameObject` is just as correct. Cheers!

---
Tags: unity, unityscript
---


title: Unity: Prefab image is scaled

text:
# Question
Title: Unity: Prefab image is scaled
I have a question regarding to the size of images in the prefab versus UI/Image.
When I drag prefab(SlotWheel) into the Scene editor, my images get scale larger.
The original image that composed become the prefab is on the right (UI/Image) with 100 width and 100 height.
In this case, how do I recalculate the height on each UI/Image in the prefabs - even though I multiply the height with scale y still doesn't add up with the height of the canvas?
I have preset Canvas Scaler's reference resolution to x:1136 and y:640. And canvas render mode is set to Screen space overlay.

# Answer
As you can clearly see right there in the transform of "SlotWheel", that your SlotWheel object, has a scale of "3.901" on (x,y,z).

So all your little child objects that belong to SlotWheel, will all have a scale of :

The child's scale * parent's scale.

Just set the parent "SlotWheel" to 1, and all the children to 1, and you'll have the usual scale of the UI/Image you showed.
> 0 votes

---
Tags: unity
---


# Question
Title: Make platform's visibility distinct from background
I have a 2d infinite runner type game which background is changing its colors constantly. Meanwhile the color of the platforms stays the same. This way the platforms at some point(when their color is the same as the background's) become "invisible" for the player.

How can I creatively, shortly and conviniently avoid this problem with unity?

P.S. I've tried adding glossy material to it but it didn't work.

# Answer
Old trick - new look:

Add a layer of color to your platforms that helps keep that defined line.

Your solution of either line or other graphics can vary but the principle is the same - the color you choose can be as subtle or as stark as you need it to be.
> 20 votes

# Answer
Since this is an infinite runner, I assume your background colors are procedurally generated. I'm not sure on your algorithm, but take that color output and limit its range.

1. You could simply exclude your platform color(s) as a possible background color option (but the background could be a tiny bit different and hard to differentiate). For example: IF backColor = platformColor THEN GetNextBackgroundColor(). You could create a 'IsColorSimilar(color1, color2)' function for this also, but more difficult.
2. Use a list of known valid background colors, and cycle through them.
3. Have different color 'styles' for both. Your platform could be bright and cheerful, and limit your background colors to desaturated colors. You need to move away from the traditional RBG way of representing colors, and move to a model such as HSL.

A great Unity add-on for working with colors is ColorTools. It costs $10, but is worth it. https://www.assetstore.unity3d.com/en/#!/content/21966

It has methods for generating colors for what you are looking for, such as Desaturate() for desaturating your generated background color, and IsSimilar() to check if the two colors are too close of a match to each other.

You can find other similar functionality for free in other libraries on the net with a bit of searching.
> 1 votes

---
Tags: unity
---


title: Lasers in 3D space game

text:
# Question
Title: Lasers in 3D space game
I am creating this little 3d space shooter and am somewhat unsure on how to implement the laser beams.

I'm thinking about something along Star Wars and the like where mostly you shoot rather short laser beams but very many of those.

Should I create a "tube" for each of the beams, render them via instancing and give them a better look just with the shader?

How would you go on about this? I was rather perplexed that there was no good tutorial on this matter out there.

# Answer
> 3 votes
You can also assume that "laser beam" is cylinder, and create a billboard for that:

http://www.opengl-tutorial.org/intermediate-tutorials/billboards-particles/billboards/

# Answer
> 5 votes
I would do this by rendering textured quads. A single laser beam would be two rectangles intersecting each other at the center by a perpendicular angle, each sharing the same texture of the laser beam.

Not very much to it, you can use instancing for them, with a very simple pixel shader which just samples the texture, oh and additive blending.

---
Tags: opengl, 3d
---