# Question
Title: Delay for seconds when key is held down?
Hello I am very new to Unity and am trying to make a shooting game in which when the space key is pressed down the gun charges then shoots. I want it to wait for 0.3 seconds before the gun fires off because I want an effect to happen with a particle system(I confused animation with effect in the first post). Also the problem the script has is that the bullet would not fire at all when the space is pressed. Here is the scripts I wrote:

```
 void Start()
 {
     StartCoroutine("Shoot",0.3f);
 }

 IEnumerator Shoot()
 {
     yield return new WaitForSeconds (0.3f);
     Bam ();
 }

 void Bam()
 {
     transform.Translate (0, 0, 12);
 }

 void Update ()
 {
     if (Input.GetKey (KeyCode.Space))
         Shoot();
 }

```

# Answer
It's been a while since I used Unity, but I don't think you need the Coroutine. I'd just use a private variable instead.

```
private const float timeToCharge = 0.3f;
private float chargeTimer = 0.0f;

private void Update()
{
    if (Input.GetKey(KeyCode.Space))
    {
        chargeTimer += Time.deltaTime;
        if (chargeTimer >= timeToCharge)
        {
            chargeTimer -= timeToCharge;
            Bam();
        }
    }
    else if (Input.GetKeyUp(KeyCode.Space))
    {
        chargeTimer = 0.0f;
    }
}

```

Note that if you want the player to only be able to fire once when having charged the weapon you'll need to add a boolean to keep track of that and then check the condition of that boolean in both the if-statements inside Update().

```
private bool weaponFired = false;
...
if (!weaponFired && Input.GetKey(KeyCode.Space))
{
    chargeTimer += timeToCharge;
    if (chargeTimer >= timeToCharge)
    {
        Bam();
        weaponFired = true;
    }
}
else if (weaponFired && Input.GetKeyUp(KeyCode.Space))
{
    chargeTimer = 0.0f;
    weaponFired = false;
}

```

Note that you don't need to subtract timeToCharge from the chargeTimer if the player only is allowed to fire once per click.
> 0 votes

# Answer
You can do something different.

You could use Unity's animation events system. You can find it in the Animation tab (the bookmark with plus sign on it). Actually you can just check this Unity manual page.

In your update method (better cache your animator link in start/awake):

```
void Update ()
{
    if (Input.GetKey (KeyCode.Space)) {
        Animator animator = GetComponent<Animator>();
        animator.Play("ShootStateName");
    }
}

```

Then you create new method and there you put projectile's spawn and move code. This new method you link in the animator's events system as shown in the manual.

The good thing of this approach is that, if you later decide to modify your charge/shoot animation, you wouldn't need to modify your code.
> 0 votes

# Answer
it is better to run your animation on button press something like this

```
void Update ()
 {
     if (Input.GetKey (KeyCode.Space))
         //Play your animation
 }

```

and then check on update that if your animation have finished then shoot

```
bool animationClipPlaying = false;

    void Update()
    {
     if (GetComponent<Animation>().IsPlaying(clipNameCompare))
     {
         //as animation start to play true the bool
         animationClipPlaying = true; //true this for comparsion
     }
     //if animation is not playing and the bool is true then, animation finished
     else if (!GetComponent<Animation>().IsPlaying(clipNameCompare) && animationClipPlaying)
     {
         //shoot the fire- your function of fire
          Bam ();
         //False so that this condition run only once
         aanimationClipPlaying = false;
     }
}

```
> 0 votes

---
Tags: unity, input
---


# Question
Title: Organizing movement, collision detection, and collision resolution
There's many articles on the internet focusing on how to implement movement, collision detection, or collision resolution. What I'm wondering is how to put them together, specifically in what order to perform them.

Should one iterate through all physics objects and do movement, collision detection and resolution for each (approach A), or perform movement for all objects, then detect all collisions, and finally resolve all collisions (approach B), or some combination thereof? Is there an approach that is universally superior? If not, what are the pros and cons for each approach (including ones I haven't listed)?

**Approach A:**

```
for (all objects)
    object.move
    object.detect_collisions
    object.resolve_collisions

```

**Approach B:**

```
for (all objects)
    object.move

for (all objects)
    object.detect_collisions

for (all objects)
    object.resolve_collisions

```

# Answer
Approach B is what you want.

With Approach A here's a possible problem:

```
//You have two balls
//Ball A moves
//Ball A is now colliding with Ball B
//Ball A and B get forces applied

```

When in reality Balls A and B are very close but have the exact same velocity!

What should happen (and what you would get with Approach B) is:

```
//Ball A Moves
//Ball B Moves
//No collisions detected
//No forces applied
//Both balls continue moving as they did

```
> 5 votes

# Answer
In general, approach B is actually faster since it can be cached and vectoried more efficiently using Structs of Arrays (SoA) / Arrays of Structs of Arrays (AoSoA), which you probably should be using anyway.
> 1 votes

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


# Question
Title: Unity 5.3.5 - How to setup a lobby with general game settings?
I am currently working on the lobby for my game. I have followed these tutorials (https://www.youtube.com/watch?v=jklWlm5v21k), which were very helpful, and was able to setup my lobby like this.

The tutorial explains all about player specific settings using lobby player prefabs, but it does not explain general level settings. I want to be able to select a game type (sudden death, flag match etc), and maybe also a map type.

What would be a good way to do this, and sync it back into the game?

One solution I thought of was adding this to the lobby player prefab, and then only make it editable for the host, and only display the hosts settings for this. Then make the hook change the map/gametype accordingly.

This doesn't quite feel like the right way to do this, so I would be happy to get some pointers on this.

I am using Unity 5.3.5 with c#

# Answer
In the lobby manager, add a new panel (or change an existing panel, whichever is easier to you) which contains all the general game settings that you need. When a player hosts a new game, then display this new panel and get all the information, and then start a new game accordingly. Hope this helps
> 0 votes

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


# Question
Title: SceneManager.GetActiveScene(); return -1 when Debugging active scene in editor
I'm trying to use the new SceneManagement since Application.LoadLevel is obscelete and I've read that we need to put it like this.

```
using UnityEngine;
using System.Collections;
using UnityEngine.SceneManagement;

public class UI : MonoBehaviour {

    private Scene activeScene = SceneManager.GetActiveScene();

    // Use this for initialization
    void Start () {
        Debug.Log (activeScene.name);
    }

    // Update is called once per frame
    void Update () {

    }

    public void restartLevel(){
        SceneManager.LoadScene (activeScene.buildIndex);
    }
}

```

The Debug.Log show "-1" and it should be "0" and throw this error in console

```
Scene '' (-1) couldn't be loaded because it has not been added to the build settings or the AssetBundle has not been loaded.

```

The Scene is added in the build setting too by the way.

Seems that it can't return me the good index and even with the activeScene.name, still returns NULL. I miss how Application.LoadLevel was easier and more robust that this new way...

# Answer
Ahh.. You are assigning `activeScene` outside the main thread. Just assign it in any method such as `Start` or `Awake`.

Like,

```
...
private Scene activeScene;
...

void Start () {
        activeScene = SceneManager.GetActiveScene();
        Debug.Log (activeScene.name);
    }
...

```
> 2 votes

# Answer
Did you add the Scene in Building Settings?

sceneNumber = SceneManager.GetActiveScene().buildIndex;

by this code you will get scene number.
> -2 votes

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


# Question
Title: How to orient a hexagonal tile on a geodesic sphere (Goldberg polyhedron)?
I've recently ported the hexasphere implementation by Rob Scanlon at https://github.com/arscan/hexasphere.js to objective-c for use in a project I'm exploring.

As a port, it works very well, and I can render the hexasphere using SceneKit on iOS however it's terribly inefficient. Because I want to dynamically animate individual facets of the hexasphere, I originally implemented each facet as a single SCNNode with it's own SCNGeometry object.

This produces a very slow rendering, with frame rates well below 30fps because of the high draw count.

Here is an image of the output after the original port:

With some advice from another developer, I've improved the rendering by creating a single SCNGeometry object that represents a single hexagon, and then using that single geometry multiple times, once for every hexagon in the hexasphere.

Whilst this brought down the draw count to an amazing 8 draws, it introduced a new problem.

By taking the multiple geometries generated by the original hexasphere code, each hexasphere was oriented in 3D so that they fit into the hexasphere appropriately.

Moving to the new design where I am positioning each SCNNode on the centrepoint of each hexagon, left me with a single geometry, correctly position in 3D, but incorrectly oriented, as this image shows:

After some experimentation I worked out that if I use the latitude and longitude of each hexagon, these would appear to give the correct orientation in the X and Y axes.

Applying this, I got a much better result:

But there is still a problem. The hexagons, whilst correctly positioned, are not oriented correctly on the face of the hexasphere.

So, finally, my question.

I'm trying to work out how to rotate those hexagons on the surface of the hexasphere, but I can't see how to. I had thought it was about rotating it on the Z axis, but that doesn't appear to work. I think I somehow need to calculate a set of 3 angles, 2 of which much be close to the latitude and longitude.

My current thought is that given that I have the boundary points of the original hexagon generated by the original code, I should be able to calculate (somehow) a 3D vector that represents the slope/orientation of the plane formed by those points, and use that to get the hexagons looking the way they are supposed to look.

Can someone help me get this right. Now I know I'm working with SceneKit and Objective-C, but I'm open to solutions in other languages. What I'm hoping is that I don't just get told to read a site with arcane maths because believe me, I've tried, and I just don't get it.

\[UPDATE\] I've completed my project now, and have made my Objective-C implementation of the hexasphere public on git at: https://github.com/pkclsoft/HexasphereDemo

# Answer
> 3 votes
As I mentioned above, there won't be a perfect solution here, because the hexagons that make up a Goldberg polyhedron tend to be irregular and non-congruent with each other. From one part of the sphere to another they distort in different ways. In general there's no rotation that will align a regular source hexagon with a given tile perfectly.

But, there are lots of ways to get a *close* match, particularly in areas where the distortion is low. I'll present one below, but I make no guarantees it's optimal. ;)

Here's an outline of the method:

First we want to identify the longest corner-to-corner axis of the hexagon - on the grounds that it likely dominates the perceived orientation of the tile.

Next we want to find the midpoint of this line. That's the position in space where we'll position our hex tile (which might be different from the coordinates of the geodesic vertex it came from), so from here on I'm going to call it the "center."

Now we need to form a basis for our orientation. We'll take the vector from the center to one of the corners on our long axis and call it "up." (The top blue arrow in the diagram above)

Next, we'll take the normal of the face (the green arrow sticking out of the hexagon in an attempt to show 3D above). I expect you can get this from the hexasphere code, but you can also normalize the offset from the center of the sphere to the face position to get something similar (depending on how hexasphere builds its polyhedra).

Take the cross product of the up and normal vectors to get a "right" vector perpendicular to both.

Now we can construct a transformation matrix something like this:

```
┌                            ┐
| right  up   normal  center | (Treating each named vector as a 3x1 column
|   0     0     0        1   |  so the matrix is actually 4x4)
└                            ┘

```

Depending on your matrix multiplication conventions, you may want the transpose of this, and you may need to negate one of the axes to get the handedness right for your coordinate system / winding. I haven't used SceneKit so I'm not familiar with its particular conventions.

If you scale all three vectors to the length of the "up" vector, you'll match the furthest corners but usually overshoot the rest, but you could use some fraction of this length to get a slightly inset hexagon face, which may help hide the inaccuracies.

If your setup supports non-uniform scale and skew, we can get a little closer:

Here we calculate the right vector a bit differently.

We take the offset from the center to the midpoint of each edge across from it. Subtract the left offset from the right and divide by two to get an "average" right vector.

To make this a drop-in replacement, we change our source hexagon so it's as wide as it is tall, so the side edges end up where we expect without a compensating magic number. ;)

Now we construct the transformation matrix the same way, but we don't normalize or rescale the lengths of the up or right vectors - their relative lengths describe how broad or skinny the hexagon should be.(You can still multiply them by a fraction if you want to inset the whole face proportionately though)

This still won't be perfect, but it may be close enough for the eye in many cases.

# Answer
> 2 votes
**Updated**: to show my final result.

This answer is actually my implementation of the answer provided by @DMGregory above.

For the most part, I found that answer worked very well, so I thought it worthwhile to post some SceneKit code.

Before I do, here is an image showing what the answer provides as a result. It's definitely not perfect, and as @DMGregory states, it's not expected to be.

The (accepted) answer provided by @DMGregory above has two main components to it.

* The first component deals with forming a transformation matrix that will position and orient each of the faces on the polyhedron as desired.
* The second component deals with an attempt to scale each face of the polyhedron so that it closely resembles the original image in the question.

What I have, is a working first component, and now, a working second component.

**First Component - position and orientation**

The polyhedron in question involves 12 pentagons, and a computed number of hexagons. The answer above only really discusses hexagonal faces, however I found that I could apply the same rules to the 12 pentagons with one key point.

For each face I needed to determine the centroid, and the coordinate of the "top" vertice. I called this "top" vertice, the `keyPoint` of the face.

Four SCNVector3 objects are defined, `center`, `up`, `normal` and `right`. Given the above, I calculated these as follows:

```
SCNVector3 center = tile.centrePoint;
SCNVector3 up = SCNVector3FromGLKVector3(
                   GLKVector3Subtract(
                      SCNVector3ToGLKVector3(center),
                      SCNVector3ToGLKVector3(tile.keyPoint)));
SCNVector3 normal = SCNVector3FromGLKVector3(
                       SCNVector3ToGLKVector3(tile.centrePoint));
SCNVector3 right = SCNVector3FromGLKVector3(
                      GLKVector3CrossProduct(
                         SCNVector3ToGLKVector3(normal),
                         SCNVector3ToGLKVector3(up)));

```

Now calculate the length of `up` and scale both `right` and `normal` as directed.

```
float upLength = GLKVector3Length(SCNVector3ToGLKVector3(up));
right = SCNVector3FromGLKVector3(
           GLKVector3MultiplyScalar(
               GLKVector3Normalize(SCNVector3ToGLKVector3(right)), upLength));
normal = SCNVector3FromGLKVector3(
            GLKVector3MultiplyScalar(
               GLKVector3Normalize(
                  SCNVector3ToGLKVector3(normal)), upLength));

```

Noting that the `hex.centrePoint` has been calculated by the original hexasphere code, and that calculating the midpoint along the long axis of the hexagon gave essentially the same answer.

I then configured the transformation matrix as directed:

```
GLKMatrix4 transform =  {
  right.x, right.y, right.z, 0,
  up.x, up.y, up.z, 0,
  normal.x, normal.y, normal.z, 0,
  center.x, center.y, center.z, 1
};

node.transform = SCNMatrix4FromGLKMatrix4(transform);

```

This provided the following:

There is still the second component of the scaling to be done. This looks promising though.

**Second Component - Scaling**

I then set about to implement the second component with the following modification to the above (for hexagonal faces only):

In addition to the `keyPoint`, I now needed both a `midLeft` and `midRight` which are the center points of the two "sides" of the hexagon.

I then applied the extra steps as directed to produce the average 'width' of the face:

```
GLKVector3 offsetLeft = GLKVector3Subtract(
                           SCNVector3ToGLKVector3(center), midLeft);

GLKVector3 offsetRight = GLKVector3Subtract(
                            SCNVector3ToGLKVector3(center), midRight);

SCNVector3 average = SCNVector3FromGLKVector3(
                        GLKVector3DivideScalar(
                           GLKVector3Subtract(offsetLeft, offsetRight), 2.0));

```

The matrix then became:

```
GLKMatrix4 transform =  {
  up.x, up.y, up.z, 0,
  average.x, average.y, average.z, 0,
  normal.x, normal.y, normal.z, 0,
  center.x, center.y, center.z, 1
};

```

When I first wrote up this answer, I had skipped a crucial step:

> To make this a drop-in replacement, we change our source hexagon so it's as wide as it is tall, so the side edges end up where we expect without a compensating magic number. ;)

At the time it didn't make sense, but having gone back to the problem I realised my mistake, and with this done, the result is what I've now placed at the top of this answer (and again below). I suspect is as good as this solution is going to get. All told, the answer provided by @DMGregory is great; it just needed time for me to understand it.

---
Tags: 3d, mathematics, hexagonal-grid
---


title: Z buffer for large vs small objects

text:
# Question
Title: Z buffer for large vs small objects
Are there common, tried and tested techniques for making sure that when displaying very large and very small objects, in a 3D environment, those objects don't display in front or behind each other?

The scenario I am thinking of is a small person object being closer to the camera than a single, large (for the sake of argument) wind mill arm. As the wind mill turns, the centre of the arm would pass in front and behind the person object's centre. However, depending on the position of the camera, the arm should only be shown as passing either behind or in front of the person object.

# Answer
> 1 votes
Yes. Modern 3D graphics use a per-fragment (essentially, per-pixel) depth buffer to handle these scenarios correctly.

Rendered geometry (your person, your windmill arm) passes through the transformation pipeline, ultimately arriving in screen space with a screen space depth (distance from the eye point) for every vertex. That depth is interpolated over the surface of the geometry along with other attributes during rasterization. Before a final fragment is written to the output, the fragments depth is compared with the existing value in the depth buffer. If the existing depth is closer to the eye than the depth of the fragment, the fragment isn't written (it would be "behind" something closer).

The specifics of the depth buffer values, comparisons, and writing process can be tweaked via your graphics API, but that's the basic behavior. It handles basically everything except translucent objects, which must further be sorted by depth front-to-back before being rendered (because you *do* want to see some portion of fragments behind transparent fragments).

---

Since it sounds like you need to implement this yourself, I'll talk briefly about how. You don't need access to the GPU to do it; if you're writing your 3D pipeline yourself you're already having to do basically all the same things. At some point in your pipeline you have transformed 3D coordinates for all your vertices. And you'll be rasterizing triangles formed by those vertices by interpolating across the surface of those triangles, so you can interpolate depth (Z) just like any other attribute.

A depth buffer is straightforward: it's a big array of floats, an array that is the same size as your rasterization target (color buffer). For example, `float depthBuffer[640 * 480];`.

At the start of a render frame, clear this entire buffer to 1.0f (or whatever you choose to be the "furthest" depth). Then, when rasterizing your triangles, before you write the final color for the triangle, check the interpolated depth of that pixel against the depth in the buffer for that pixel's coordinates:

```
if (depth[pixelY * frameBufferWidth + pixelX] > interpolatedDepth) {
  // no previously-written pixels were closer than this pixel
  framebuffer[pixelY * frameBufferWidth + pixelX] = finalColor;

  // update the depth buffer
  depth[pixelY * frameBufferWidth + pixelX] = interpolatedDepth
}

```

This can be adapted to ray-tracing renderers as well (there are several papers on ray-z-depth algorithms). If your custom 3D implementation is not rasterization based or otherwises uses some other technique than the above, you'll probably have to post more about it before anybody can provide a drop-in implementation of a depth buffer.

Note that *any* kind of sorting-only process is going to fail at some point, which is why we generally use the depth buffer approach in modern renderers (even modern software renderers). Sorting-only is basically a painter's algorithm, which has impossible cases which will always render incorrectly.

---
Tags: 3d, lua, depth-buffer, culling
---


title: How do PC/Mac games detect piracy?

text:
# Question
Title: How do PC/Mac games detect piracy?
I was recently reading an article about clever ways programmers have protected their games from pirates, such as the creators of Game Dev Tycoon. This made me curious: how do they detect that the copy of the game running is in fact a pirated version on a technical level? The closest answer I was able to find through some research was how SNES cartridges can detect if they're pirated, but that tactic obviously doesn't apply to PCs.

# Answer
First thing first: there is no way for a computer to know whether a file is pirated or not. Piracy is a legal/moral term, and as so, it has no meaning on a file, which is only composed of ones and zeroes.

That said, piracy prevention and countermeasures usually focus on finding out whether or not a user has something (usually an object) which can only be obtained if a copy of the game was purchased, and make that difficult to duplicate. There are tons of ways to do this, each one with advantages as well as flaws. I'll mention a few:

* Early games asked users to input a word from the game manual, which you should only get if you bought a game box. A photocopier or a scanner easily defeats this technique though.
* More recently, media checks are more common. The idea is that you require the game CD to be in the drive for the game to run. To implement this, you can for example access critical data files from the CD without which the game cannot run, or simply check for the existence of a file in the CD. This worked pretty well when CDs were difficult to duplicate, but CD copiers, and more recently drive emulators can be used to easily defeat these technique.
* However, CD copies are not perfect, so many other techniques focus on detecting whether the CD is the original pressed CD, or a copy. To implement this, a game can check for non-standard elements that are inserted on the game disc during press time, but cannot be easily and reliably replicated by a CD burner, on a CD-R. Some common ways to do this are:

+ Creating dummy "ghost" files in the CD during mastering, which are not accessible from the CD filesystem, but do exist, and can be read if you know where to find them. This data is absent on file-by-file disc copies. Copying the entire disc image will copy these files though.
    + Another way is to intentionally insert errors in the disc. CDs contain error correction codes. By inserting errors in the data, which can be transparently corrected by a disc reader, the disc will work normally, but the errors won't be copied to the CD-R. By looking for these intentional errors, a game can consider a CD to be an original pressed copy. RAW disc image copies defeat this though.
    + Inserting twin sectors, with the same address but different data will yield different results when seeking data forward and backward. Checking for the existence of this is possible, and duplicating a CD with these twin sectors is very difficult.
    + Measuring the actual position of the pits in the CD. Once again, duplicating a CD with the pits in the same positions is very difficult.

However, many CD emulators, like Daemon Tools, or Alcohol 120% can actually emulate these features. Because of this, many publishers choose to include a CD emulator detection step, and prevent the game from running if an emulator is detected. The implementation of an emulator detector is outside of the scope of this answer though.
* Instead of, or in addition to checking for a physical CD, a game can request the user to input some data, like a product key. Some ways to use product keys are:

+ Checking for mathematical features in the key. However, this doesn't prevent key duplication, and if the checking algorithm is discovered or reverse-engineered, a pirate may be able to create new keys at will which will appear to be legitimate to the game. Software that creates keys at will are called "keygens".
    + Generating a hash based on the user's hardware, send this hash and the product key (usually a combination, called the "installation key") to a server owned by the game company, and based on the hash and serial, create an activation key. Using one-way numeric methods (like modular arithmetic, or some methods with elliptic curves), a game can see if the activation key matches the hash and serial code, and only run if they match. This technique is called "activation".

With activation, a server may refuse to provide activation keys for multiple hardware hashes with the same serial code. Because of this, even if the serial code, and activation key are copied, the activation key won't match and the game won't run on other computers.

All of these measures are meant to find whether or not the user owns a purchased copy of the game. However, implementing them requires program code that checks for this. It is possible for a pirate to modify the game code to disable or bypass the checks instead of attacking the copy protection mechanisms themselves. The act of modifying game binaries to remove anti-piracy checks is called "cracking".

Cracking can simply consist of disassembling the game executable, finding the place where the relevant checks are made, modifying it to disable the checks, or ignore the results, and reassembling it. Some ways to counter cracking are:

* Checking the binary with some hash. However, there must be a program that checks the hash, which can in turn be cracked as well.
* Encrypting the program, or simply the check routine, and decrypting it in runtime. This makes disassembly more difficult, as it involves one or more additional decryption steps. IF the decryption key is included in the program (as it must be, because without it, the game cannot be decrypted), then the pirate can reverse engineer the decryption, find the routine, and crack the copy protection.

Because of this, as a game publisher, you want to make the key as hard to find as possible, and optionally make the decryption algorithm hard to understand. Some ways to make the key hard to find are:

+ Obscure it by creating it in strange ways. This simply slows the cracking process.
    + Create per-machine master keys similar to the serial protection mentioned above.

However, regardless of the method you use to create your keys, the keys themselves will be in memory while decryption is in progress. Memory inspectors, debuggers and emulators can help a pirate find and copy the key while it is in memory. Memory peeking can be attacked in several ways:

+ Having a privileged service that detects memory accesses in the specified region, and redirect the addressing somewhere else. As this requires ring 0 access, and programs that do this are more commonly used for not-so-legitimate purposes, antivirus software usually block them. (this is why many games and other software ask to turn off virus protection when running). Writing software that correctly does this is *extremely* difficult, and can easily compromise the stability and security of the host OS. The XCP scandal is a good example of an implementation of this method gone wrong.
    + Modern hardware and operating systems provide some tools, like memory curtains, secure media paths and TP modules, to make it easier to make a program that decrypts data, while being resistant to memory inspection.

There are many many more techniques to attack piracy, ranging from the trivial to the esoteric. Unfortunately, it is possible for all of these techniques to fail to recognize a genuine copy, and it's usually the more aggressive techniques that have higher false positive ratios.

As a game publisher, you usually want to choose a set of techniques whose cost of implementation, expected cracking time, and false positive ratio are in line with your expectations.

It is a common misconception that piracy protection is meant to be completely unbreakable. Most game sales happen in the first few months after release, so a piracy protection scheme is usually considered effective if breaking it consumes enough time for the game publisher to collect a large amount of profits before it gets broken.

Regarding Game Dev Tycoon, they did not use any anti-piracy technologies. They simply created a "broken" build, and distributed it over BitTorrent, as is stated in the beginning of the article you mentioned.
> 54 votes

# Answer
It is pretty easy, you just have to run a MD5 or SHA256 on your own executable, then, when you detect the signature has changed from what you hardcoded into the binary after you built the final release, then its clear somebody hacked your executable. Then most companies, don't just show a popup anymore (it was the case before) that says "broken PE" or "virus detected" and then exit the game, because this will be counter-cracked very fast be hackers. Because the game is paused on the message loop of the dialog so it is immediate to see because of what branch the dialog was poped up, and just bypass the branch by changing the code at the condition check.

Today, companies use very subtle change in gameplay, like multiply the life of monsters to make the game unplayable, or incredibly cleverly integrated in this management game, where you run a game company and you loose eventually because too many players were pirating your game. Nice mise en abyme in this case. Sometimes it just gets you a red flag uploaded on the company servers, and when you want to call them for support you get a speech, or trapped into revealing your identity.

but this is all of topic, the technique is hashing. and these checks can be run in many places in the binary so that if hackers find one and clear it, its not enough.

EDIT: If you just copy the game as-is, it may work if the game has no anti-piracy measure at all. It was working with very old games, pre CD burners era. That is why, most of the time, the game has to be installed to run, not just the installation folder copied. This involves hidden files put a bit everywhere in the system, and registry keys. The game checks the presence of these things, which can only be created by the installer. And the installer, can only be run from the CD, which is not copiable because of erratic bits that do not respect the error-correction code system at the first bytes of the disc, which kills most CD player drivers. Some copy software, like nero of alcohol, proposes you to ignore the errors but what they burn is then a corrected copy, the installer detects that and there you go again.

EDIT2:

> Q: how to hash a file then insert the hash into the file which changes the hash ?

@Byte56: Damn we are getting intelligent comments here :) Yes it is a paradox and it cannot be solved. So the hash has to be made on the part of the binary that does not contain the hash. And the check code has to know that, to exclude that zone when hashing to self check. I have seen people using tags, like ~~#### \[put hash here\] ####~~ to enclose their hash and do the exclusion. But it has the flaw of being easy to spot for hackers, so the hash has to be scrambled, and scattered in multiple locations. Even encrypted why not, and the same camouflaging operation goes to store the private key.
> 3 votes

# Answer
cant they just put a ext partition on a mac game

macs cant read ext
> -5 votes

---
Tags: piracy
---


# Question
Title: How do I create 4 rows of SDL_Rects with each row being a different color?
So using a class i've created a vector and managed to make one row of SDL\_rects(with collision detection and destroy on collision). But when I make a second row(and obviously 2 or more rows):
1) it doesn't make the row
2) it makes the row on top of the first row and overrides the color.

BTW this is a breakout game and i've looked through a bunch of source code but I can't find an answer.

I thought if I pass a variable called(barType) using a switch statement I can do this, but it doesn't work.

Here is part of the Bar class:

```
Bar(int xPos, int yPos,  int barType){
    x = xPos; y = yPos;
    type = barType; shown = true;
    gBar.x = x;
    gBar.y = y;
    gBar.w = 130;
    gBar.h = 20;
}
int x,y;
int type;

void show() {
    //if(shown) {
        switch(type) {
            case 0:
                SDL_SetRenderDrawColor(gRenderer, 255, 0, 0, 255);
                break;
            case 1:
                SDL_SetRenderDrawColor(gRenderer, 0, 205, 0, 255);
                break;

        }
  //  }
}

```

I managed to do it by using images but when I use color it doesn't work.I get a "Bad access" error from Xcode.

Here is the for loop that creates the Bars:

```
for (int j = 0; j < 2; ++j) {
    for (int i =0; i < 5; ++i) {
        //if (bars.size() <=4) {
            bars.push_back(Bar(xOffset, yOffset, j));
        //}

        xOffset = xOffset + 154;
       // SDL_SetRenderDrawColor(Renderer, 204, 204, 0, 255);
        SDL_RenderDrawRect(Renderer, &bars.at(i).barsRectGet());
        SDL_RenderFillRect(Renderer, &bars.at(i).barsRectGet());

    }
    xOffset = 0;
    yOffset += 20;
}

```

TLDR: I want to created 4 rows of SDL\_Rect. Each row containing 4 or 5 Rects(doesn't really matter right now).And each row being a different color.

I hope I formatted this question so you guys can understand easily.

# Answer
> 0 votes
I believe your issue is that you're using SDL\_RenderDrawRect. If you simply set the color using SDL\_SetRenderDrawColor, then call SDL\_RenderFillRect, you should get exactly what you want. Here's a quick re-work of your code that should hopefully work:

Bar:

```
SDL_Rect rect;
int r,g,b;
bool shown;

Bar(int x, int y, int r, int g, int b) {
    this->rect = { x, y, 130, 20 };
    this->shown = true;
    this->r = r;
    this->g = g;
    this->b = b;
}

void show(SDL_Renderer* renderer) {
    if(this->shown) {
        SDL_SetRenderDrawColor(renderer, this->r, this->g, this->b, 255);
        SDL_RenderFillRect(renderer, this->rect);
    }
}

```

Main Loop:

```
SDL_SetRenderDrawColor(renderer, 0, 0, 0, 0);
SDL_RenderClear(renderer);

for (int i =0; i < 5; ++i) {
    bars.at(i).render(renderer);
}

//Update screen
SDL_RenderPresent(gRenderer);

```

---
Tags: c++, sdl2
---


title: Making a Sphere Jump

text:
# Question
Title: Making a Sphere Jump
I'm making a very simple game with a sphere that's supposed to roll and bounce on "planets". **Also, please be ready to read a lot. I want to be very descriptive for you.** :)

I've pretty-much-done everything for the game already, except I have a problem with jumping. When I press the space bar, the sphere will hop once. But after pressing space again, it will not.

# What We're Dealing With

Now this sounds like an easy fix, but keep in mind that the player object was designed with the mesh (rendered) `Player_Ball`, and the jump collider named `Player_JumpBox`, which is just an invisible collider smaller than `Player_Ball`. My idea was that when an object with a "static" tag is the object the `Player_JumpBox` collides with (which is a trigger), it will enable the user to jump. So this meant I had to make two different classes. One for the parent object, that holds both `Player_Ball` and `Player_JumpBox`, and one for the `Player_JumpBox` titled "JumpControl.cs", so it could handle the `Player_JumpBox` `OnTriggerEnter` event.

The `JumpControl.cs` file located on the `Player_JumpBox` object, takes input from the user, and controls when to jump. (Note: I did not say how to jump)

The `PlayerController.cs` file located on the parent `Player` object, controls everything about the player. It controls how to jump. (Basically has variables like `jumpForce` and a function that `JumpControl.cs` uses to tell the parent object to jump.)

# The Scripts (C#)

`JumpControl.cs`

```
using UnityEngine;
using System.Collections;

public class JumpControl : MonoBehaviour {

    public GameObject player;   // The parent object, holding both

    private bool canJump;

    void Start () {
        canJump = true;
    }

    // Every physics update, check if the user is pressing `space', and if so, jump, then set 'canJump = false'.
    void Update () {
        if (Mathf.Abs(Input.GetAxis("Jump")) > 0.1 && canJump == true) {
            player.GetComponent<PlayerController> ().Jump ();
            canJump = false;
            print ("DEBUG: canJump = " + canJump);
        }
    }

    // When the user nears the ground, enable them to jump again.
    void OnTriggerEnter (Collider c) {
        if (c.CompareTag("Static")) {
            canJump = true;
            print ("DEBUG: canJump = " + canJump);
        }
    }
}

```

`PlayerController.cs`

```
using UnityEngine;
using UnityEngine.UI;
using System.Collections;

public class PlayerController : MonoBehaviour {

    public float speed;                 // The player's rolling speed.
    public int maxCoins;                // The number of coins in the level.
    public Text counter;                // The text that displays the number of coins the player has.
    public Text finalText;              // The text that displays win-text.
    public bool isTutorial;             // Whether or not this is a tutorial.
    public float jumpForce;             // The force of jumping.

    private Rigidbody rb;               // The rigidbody.
    private float moveVertical;
    private float moveHorizontal;
    private int coins;                  // Number of coins the player has.

    void Start () {
        rb = gameObject.GetComponent<Rigidbody> ();
        coins = 0;
        UpdatePoints ();
        finalText.text = "";
    }

    void Update() {
        moveHorizontal = Input.GetAxis ("Horizontal");
        moveVertical = Input.GetAxis ("Vertical");
    }

    void FixedUpdate () {
        Vector3 movement = new Vector3 (moveHorizontal, 0.0f, moveVertical);

        rb.AddForce (movement * speed);
    }

    void OnTriggerEnter(Collider c) {
        if (c.gameObject.CompareTag ("Coin")) {
            c.gameObject.SetActive (false);
            coins++;
            UpdatePoints ();
        }
    }

    /// <summary>
    /// Updates points the user has, and displays them on the screen.
    /// </summary>
    void UpdatePoints() {
        if (coins < maxCoins) {
            counter.text = "Coins: " + coins;
        } else {
            counter.text = "Coins: " + coins;
            if (isTutorial) {
                finalText.text = "Tutorial complete!";
            } else {
                finalText.text = "You win!";
            }
        }
    }

    /// <summary>
    /// The method JumpControl.cs uses to make the player jump.
    /// </summary>
    public void Jump() {
        Vector3 jump = new Vector3 (0.0f, jumpForce);
        rb.AddForce (jump);
        print ("Jumped");
    }
}

```

(The only truly important thing is the `Jump` method at the bottom of `PlayerController.cs`)

# What I Want

I really just want to know why the player isn't bouncing everytime I press 'space'. It's really bam-boozled me for a while, and I really need your help.

Thanks for reading! I tried to make it easy to understand.

# Answer
> 0 votes
Silly me, I assumed I already made the `Player`'s Rigidbody a trigger.

Also, you need to make each and every child of the planet (like the tops of the planet) that you want to let the player bounce on to be **static**; not just the empty object parent.

I'm very sorry I never double-checked, but I hope this helps others out.

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


title: Positioning game object on a grid

text:
# Question
Title: Positioning game object on a grid
I am learning how to code by programming easy, 2D games. Here I want to try to get only a map, like in strategy games (2D isometric) and put new objects (pictures) on it.

In short: I want load a big picture and put little pictures on this big picture.

My thought was:

1. Find a big map picture. (or make it with Photoshop)
2. Put a grid-layout over that base (this will not be visible to the player).
3. Put smaller objects (as pictures) on this map using this grid-layout.

Is it possible to make it like this, or are there better solutions?

# Answer
> 1 votes
The easiest way of creating a grid is a 2 dimensional array. You didn't tell what language/game engine you plan to use but a search on *arrays* combined with your language of choice should give you the information you need. Treat all code examples in this answer as pseudo code- you will have to convert it, but it should illustrate the concept.

An array is basically a list of items that can be accessed by the position in the list. A 2 dimensional array works like a grid. In most languages a 2 dimensional array is represented like this:

```
Array[x][y]

```

Now you can put items in the Array at the x and y coordinate, for example place an item at coordinate 3,6 would be:

```
Array[3][6] = myItem;

```

If you want to draw a grid, it would be as easy as (suppose the grid is 20x20):

```
SquareSize = 10
GridSize = 20
for(x=0 to GridSize)
  for(y=0 to GridSize)
    if(Array[x][y].containsitem)
        draw_X_Y_Item(x*SquareSize,y*SquareSize,Array[x][y])
    end if
  next
next

```

Now you wanted an isometric grid. The trick is that each odd row X is offset `0.5 * SquareSize` and the height of each row is `0.5*SquareSize`.

```
SquareSize = 10
GridSize = 20
for(x=0 to GridSize)
  for(y=0 to GridSize)

    if(Array[x][y].containsitem)

      if(y%2=0) // odd or even?
        draw_X_Y_Item(x*SquareSize,y*SquareSize*0.5,Array[x][y])
      else
        draw_X_Y_Item(x*SquareSize+0.5*SquareSize,y*SquareSize*0.5,Array[x][y])
      end if

    end if
  next
next

```

If you also use this method to draw your map; you will save a lot on memory; do a search on 'tilemaps' for more information.

# Answer
> 0 votes
Yes. But it depends on your goal, whether it's the best solution or not. I would do it like that:
-Create a large array for tiles (grid layout)
-Put on each array the specific texture (grass, sand etc..)
-And put items on the specific tiles.
Huge textures can cause problems on some of the devices like old android phones. E.g they don't support textures larger than 1024px..
So I would use arrays and put each world tile on it.
(Sorry for bad english)

---
Tags: 2d, grid
---


# Question
Title: Is it sensible to make all physics on GPU using transform feedback?
I'm learning OpenGL and today I read something new to me. It's called transform feedback, and if I understand right, it can help to get information about vertex shader variables. And I read an example where a particle system was created, with collisions. After reading it I have a question: Is it sensible to make all physics like this, i.e. is there any kind of profit from this?

# Answer
> 6 votes
Physics done on the GPU are usually cosmetic effects. Particles are a good example, but hair and tall grass are similar. The GPU is very good at doing a massive number of calculations and since it also handles the drawing if these things it is a good match.

A GPU isn't very fast at communicating the results back to the CPU. This is why physics used in actual gameplay is done locally on the CPU: Collisions may affect both colliding objects or trigger other gameplay effects (e.g. points scored) so it makes more sense to handle that on the CPU.

Some physics effects may benefit from using the GPU to do some calculation offloading, but those are often handled by a specially designed physics core.

So in general, non-gameplay special effects that require some degree of physics are suited to run on the GPU.

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


# Question
Title: Clamping camera forward and backward vector in Unity3D
My perspective camera is rotated on the x axis. I've implemented a zoom with the scroll wheel and it works great.

I'm trying to limit the zoom, however. My solution right now is to take the relative scale of the `transform.forward` y and z components and clamp the y and z position of the camera by using `Mathf.Clamp` and multiplying the `minZoom` and `maxZoom` floats by the corresponding `transform.forward` component. It works well, except it limits the y axis, so when I translate around I can't go below a given y due to my clamp with is ideally meant to affect the zoom only.

Is there a way to clamp the forward and backward movement of the camera? I've been looking everywhere but can't find a thing.

Thanks.

**Code**

```
public class ClickManager : MonoBehaviour

{
    public float dragSpeed = 2;
    public float minZoom = 0.5f;
    public float maxZoom = 5.0f;

    private Vector3 dragOrigin;

    private float lerpPercentBack = 0; // value between 0 and 1 representing percentage of lerp
    private float lerpPercentForward = 0;
    private bool isLerpingBack = false;
    private bool isLerpingForward = false;

    void Update()
    {
        float scroll = Input.GetAxis("Mouse ScrollWheel");

        if (Input.GetMouseButtonDown(1))
        {
            dragOrigin = Input.mousePosition;
            return;
        }

        if (scroll > 0)
        {
            isLerpingForward = true;
            lerpPercentForward = 0;
        }
        if (scroll < 0)
        {
            isLerpingBack = true;
            lerpPercentBack = 0;
        }

        if (isLerpingBack)
        {
            scrollLerperBack();
            lerpPercentBack += 0.05f;

            if (lerpPercentBack >= 1.0f)
            {
                lerpPercentBack = 0;
                isLerpingBack = false;
            }
        }

        if (isLerpingForward)
        {

            scrollLerperForward();
            lerpPercentForward += 0.05f;

            if (lerpPercentForward >= 1.0f)
            {
                lerpPercentForward = 0;
                isLerpingForward = false;
            }
        }

        //Debug.Log(lerpPercent);

        /*if (!Input.GetMouseButton(1)) return;

        Vector3 pos = Camera.main.ScreenToViewportPoint(Input.mousePosition - dragOrigin);
        Vector3 move = new Vector3(pos.x * dragSpeed, pos.y * dragSpeed, 0);

        transform.Translate(move, Space.World);

        Debug.Log(scroll);*/

    }

    void scrollLerperBack()
    {
        transform.position -= Vector3.Lerp(transform.forward, Vector3.zero, lerpPercentBack);
    }

    void scrollLerperForward()
    {
        transform.position += Vector3.Lerp(transform.forward, Vector3.zero, lerpPercentForward);
    }

    void LateUpdate()
    {
        Vector3 pos = transform.position;

        pos.y = Mathf.Clamp(pos.y, minZoom * transform.forward.y,
            maxZoom * transform.forward.y);
        pos.z = Mathf.Clamp(pos.z, minZoom * transform.forward.z,
            maxZoom * transform.forward.z);
        transform.localPosition = pos;
    }

}

```

# Answer
`scroll` value resets when it's not scrolling. For one time scrolling the value turns `+/- 0.1f`. For multiple time scrolling at a time it changes `+/- 0.1f` on the current `scroll` value. Else it resets to **Zero** on next frame. That's why `scrollCount` will be used as scroll counter.

Two new variables:

```
private float scrollCount = 0f; //scroll count is related to max zoom

[SerializeField]
private float maxZoomLevel = 0.2f; //so zoom levels are -0.2f, -0.1f, 0.0f, 0.1f, 0.2f

```

Changes in `Update()` which will replace your `if (scroll > 0)` and `if (scroll < 0)` blocks of code.

```
    if ((Mathf.Abs(scroll) == 0.1f && //Checking for one time scrolls only
             scrollCount < maxZoomLevel + 0.1f && scrollCount > -maxZoomLevel - 0.1f)) //Margins on max and min zoom level
    {
        if (scroll == 0.1f && scrollCount < maxZoomLevel) //Zoom In
        {
            scrollCount += 0.1f;

            isLerpingForward = true;
            lerpPercentForward = 0;

            isLerpingBack = false;
            lerpPercentBack = 0;
        }

        if (scroll == -0.1f && scrollCount > -maxZoomLevel) //Zoom Out
        {
            scrollCount -= 0.1f;

            isLerpingForward = false;
            lerpPercentForward = 0;

            isLerpingBack = true;
            lerpPercentBack = 0;
        }
    }

```

Get rid of your `FixedUpdate()` statements and enable the code at the end of `Update()` regarding `Vector3 pos` and `Vector3 move`.

There is another solution for Zoom. You may use `Camera.main.fieldOfView` for perspective camera. Field of view is by default `60f`. Less than `60f` will zoom in and greater than `60f` will zoom out. For little amount of zoom changing field of view is harmless.
> 1 votes

# Answer
```
//
//Filename: maxCamera.cs
//
// original: http://www.unifycommunity.com/wiki/index.php?title=MouseOrbitZoom
//
// --01-18-2010 - create temporary target, if none supplied at start

using UnityEngine;
using System.Collections;

[AddComponentMenu("Camera-Control/3dsMax Camera Style")]
public class maxCamera : MonoBehaviour
{
        public Transform target;
        public Vector3 targetOffset;
        public float distance = 5.0f;
        public float maxDistance = 20;
        public float minDistance = .6f;
        public float xSpeed = 200.0f;
        public float ySpeed = 200.0f;
        public int yMinLimit = -80;
        public int yMaxLimit = 80;
        public int zoomRate = 40;
        public float panSpeed = 0.3f;
        public float zoomDampening = 5.0f;

        private float xDeg = 0.0f;
        private float yDeg = 0.0f;
        private float currentDistance;
        private float desiredDistance;
        private Quaternion currentRotation;
        private Quaternion desiredRotation;
        private Quaternion rotation;
        private Vector3 position;

        void Start() { Init(); }
        void OnEnable() { Init(); }

        public void Init()
        {
            //If there is no target, create a temporary target at 'distance' from the cameras current viewpoint
            if (!target)
            {
                GameObject go = new GameObject("Cam Target");
                go.transform.position = transform.position + (transform.forward * distance);
                target = go.transform;
            }

            distance = Vector3.Distance(transform.position, target.position);
            currentDistance = distance;
            desiredDistance = distance;

            //be sure to grab the current rotations as starting points.
            position = transform.position;
            rotation = transform.rotation;
            currentRotation = transform.rotation;
            desiredRotation = transform.rotation;

            xDeg = Vector3.Angle(Vector3.right, transform.right );
            yDeg = Vector3.Angle(Vector3.up, transform.up );
        }

        /*
     * Camera logic on LateUpdate to only update after all character movement logic has been handled.
     */
        void LateUpdate()
        {
            // If Control and Alt and Middle button? ZOOM!
            if (Input.GetMouseButton(2) && Input.GetKey(KeyCode.LeftAlt) && Input.GetKey(KeyCode.LeftControl))
            {
                desiredDistance -= Input.GetAxis("Mouse Y") * Time.deltaTime * zoomRate*0.125f * Mathf.Abs(desiredDistance);
            }
            // If middle mouse and left alt are selected? ORBIT
            else if (Input.GetMouseButton(2) && Input.GetKey(KeyCode.LeftAlt))
            {
                xDeg += Input.GetAxis("Mouse X") * xSpeed * 0.02f;
                yDeg -= Input.GetAxis("Mouse Y") * ySpeed * 0.02f;

                ////////OrbitAngle

                //Clamp the vertical axis for the orbit
                yDeg = ClampAngle(yDeg, yMinLimit, yMaxLimit);
                // set camera rotation
                desiredRotation = Quaternion.Euler(yDeg, xDeg, 0);
                currentRotation = transform.rotation;

                rotation = Quaternion.Lerp(currentRotation, desiredRotation, Time.deltaTime * zoomDampening);
                transform.rotation = rotation;
            }
            // otherwise if middle mouse is selected, we pan by way of transforming the target in screenspace
            else if (Input.GetMouseButton(2))
            {
                //grab the rotation of the camera so we can move in a psuedo local XY space
                target.rotation = transform.rotation;
                target.Translate(Vector3.right * -Input.GetAxis("Mouse X") * panSpeed);
                target.Translate(transform.up * -Input.GetAxis("Mouse Y") * panSpeed, Space.World);
            }

            ////////Orbit Position

            // affect the desired Zoom distance if we roll the scrollwheel
            desiredDistance -= Input.GetAxis("Mouse ScrollWheel") * Time.deltaTime * zoomRate * Mathf.Abs(desiredDistance);
            //clamp the zoom min/max
            desiredDistance = Mathf.Clamp(desiredDistance, minDistance, maxDistance);
            // For smoothing of the zoom, lerp distance
            currentDistance = Mathf.Lerp(currentDistance, desiredDistance, Time.deltaTime * zoomDampening);

            // calculate position based on the new currentDistance
            position = target.position - (rotation * Vector3.forward * currentDistance + targetOffset);
            transform.position = position;
        }

        private static float ClampAngle(float angle, float min, float max)
        {
            if (angle < -360)
                angle += 360;
            if (angle > 360)
                angle -= 360;
            return Mathf.Clamp(angle, min, max);
    }
}

```
> 0 votes

---
Tags: unity, camera
---


title: How to make game like Gals Panic

text:
# Question
Title: How to make game like Gals Panic
Any one have a idea how to build game like Gals Panic. I want to know the basic idea how can i start building the game.

Note : im a flash game developer.So anything related to flash would be helpful.

reference : https://en.wikipedia.org/wiki/Gals\_Panic

Thanks in advance

# Answer
> 5 votes
Gals Panic, is a Qix type game. You may search for Qix to get more information on how things work.

The general concept here is, having two images. One is the picture that you want to be revealed. The 2nd one is the actual gamefield where the game is checked against. These two are combined to produce the end result. So suppose the filled game area is white and the backdrop is black, a simple multiplication can make those white areas show the revealed picture.

There are two ways of realizing the gameplay field. The first one, is the way Gals Panic actually works: checking against pixels. The 2nd one is create a polygon structure. Both have advantages and drawbacks.

**The Pixel way**

Think of the game Snake. The line drawn by a player is like the snake. Each movement a check runs: does the player hit a pixel colored as its own line? Yes -prevent movement. Does the player hit a pixel colored as the revealed area (white)? yes- do a floodfill in the closed off area. The Closed of area is determined by the position of the "big bad" in the game. So if you do a quick floodfill on say- left of the drawn line; check if the "big bad" is in the filled area. If he is, then you need to flood fill the other side of the line.

Pro:

* Like in Gals Panic, "big bad" can destroy revealed areas. This results in arbitrary shaped holes or isolated revealed areas. For the pixel method; this is easy.
* Percentage filled is similar to counting the revealed pixels versus the obscured ones.

Con:

* Speed. Since you work on a per pixel basis, flood fills become more expensive as the resolution increases. Gals Panic is an arcade game during the 224x256 screen resolution area.
* Gameplay speed has a direct relation to the number of pixels checked each frame. You can do speedbonusses, but those are a bit tougher to construct.
* Enemies etc. need a pixel collision type to move around etc.

**The Polygon way**

This method is based on adding polygons to the existing start polygon. Basically the line starts on a edge on the source polygon. When the line drawn ends intersects the start polygon, the polygon is expanded. So determine where the start and endpoints are, then do a check if the "big bad" (via a point-in-polygon check) is inside the closed off area, then do a left or rightsided add of the line and the polygon has become bigger. The polygons are then filled using a ear-clipping algorithm.

Pro:

* Speed, this method is really fast, it also scales well (doesn't care the resolution of the source material for speed).
* There may be libraries to do polygon adding and ear-clipping algorithms for you.
* Enemies and other gameplay can do simple line intersection and point-in-polygon checks against the gameworld.

Con:

* The big bad "Eating" from the outside of the play area in the polygon is possible, but it makes the checks way more complex.
* Splitting the area up (due to the big bad doing something) makes this approach also more complex because you end up with multiple "source" polygons. It can be done but consider this from the start.

**Inside out or Outside in**

Gals Panic is a *inside out* style Qix clone. It starts with a revealed block inside the image and the gameplay extends to the edges.

Qix, Volfied, Styx use an *outside in* approach; the player starts on the outer edge of the playfield and fils the area inwards.

This has an important effect on your game if you plan to use the polygon approach. If you go *outside in* the polygon represents the area that is obscured (thus at start, the entire polygon covers the game area). This means you make the polygon smaller as the game proceeds. The reason is, the player can move along the edge of the polygon, thus at start this is the entire edge of the play area. For *inside out* the polygon represents the revealed area, and is expanded as the gameplay proceeds.

---
Tags: game-design, flash, actionscript-3, logic
---


# Question
Title: How would I implement a level for a vertical shooter game
I've been working in my free time on a vertical shooter similar to Xenon 2 Megablast. It's a tribute of sorts to the game that destroyed a considerable part of my childhood.

I've got the basic stuff in place - weapons, enemies, collision detection and a scrolling background. Now, I want to design the levels.

I want to create some kind of an engine which can render a level based on some kind of (say) textual description so that I can easily create levels. Are there any articles or links to how platformer/vertical shooter levels can be stored as files and loaded by the game engine? I'm not looking for completely solutions but ideas and starting points so that I can try to do it myself.

Specifically, how would you store the level of a platformer game like Prince of Persia or a shooter like Xenon 2?

# Answer
> 5 votes
I don't know if you can find any valuable resources or articles about the topic, but I think that the idea of the textual description is good. Personally, I have some experience with vertical-scroller shmups, and I have always followed this approach.

Roughly speaking, you can have a series of text files (or other kind of file...); each file corresponds to a level of your game. Every row of a file contains the essential informations that you need for generating the enemies (or other objects, such as background elements - like planets, stars,...). These informations, obviously, vary accordingly with your specific game but, in general, they could be:

* **The spawn time**: this is the time that you have to wait between a "row" and another. Basically, you control the frequency of spawning, with this "parameter";
* **The enemy type**: this could be an index, or a string, that represents the specific enemy type. As an example, if you have 20 types of enemies in your game, this can be a numerical index, from 1 to 20, that represents the type of object to be instantiated: a particular function in your code will bind the index with the specific asset of the enemy. As I said, you could also use the string that represents the asset's name in your project: It will just be a unique identifier for the object to be instantiated.
* **The** x and y **coordinates** that define the spawn point (y-coordinate could be avoided, and defined as a constant, if all the enemies come from the top of the screen).

So, your txt file can be structured in a similar fashion:

```
4.0 little_enemy_1 200 150
0.0 little enemy_1 240 150
0.0 little_enemy_1 280 150
3.5 mothership 140 170

```

In Unity (sorry, but I'm familiar with that...) these lines correspond to:

```
yield WaitForSeconds(4);
Instantiate (little_enemy_1, Vector3.Position(200, 150, 0), Quaternion.identity);
Instantiate (little_enemy_1, Vector3.Position(240, 150, 0), Quaternion.identity);
Instantiate (little_enemy_1, Vector3.Position(280, 150, 0), Quaternion.identity);
yield WaitForSeconds(3.5);
Instantiate (mothership, Vector3.Position(140, 170, 0), Quaternion.identity);

```

If you're not familiar with Unity, those lines say: "*wait 4 seconds, generate 3 little enemies in a row, wait 3.5 seconds, and generate a mothership (all in the proper coordinates)*". In my example I have not considered the particular rotation of the objects that have to be spawned, but, obviously, you can also add that.

I know that it was just a quick tip, but I hope that it could represent a good starting point for you, as you asked. Any feedback will be appreciated, of course.

# Answer
> 0 votes
Similar to @Goblin's answer here, I am using a random endless wave generator for my game, which is an HTML5 side-scrolling space shooter. The code below is plain Javascript. I am not posting the entire code here. Some functions are left out for your implementation. I just wanted to depict the logic.

```
var shipTypes = ['warbird','crosswing','raider','drone','tinydrone'];
var levelTimer = 0; // This variable increments by 1 per frame
var wave = {};
var screenHeight = canvas.innerHeight; // Dont bother about this step
function generateNextWave () {

    var numberOfShips = getRandomNumberBetween(1,5); // This function is to pick a integer between the two numbers (inclusive)
    wave = {};

    var len = shipTypes.length - 1,ships = [];
    for(i=0;i<numberOfShips;i++) {
      var pickAShipType = shipTypes[getRandomNumberBetween(0,len-1)];
      ships.push(createShip(pickAShipType)); // Assume I have a function to create a ship according to its type
    }
    wave[levelTimer + getRandomNumberBetween(100,200)] = ships;

}

function gameLoop() {

    ....

    // check if there is a wave this time
    if(wave[levelTimer]) {

      // add the ships to the list of ships on screen
      addShipsToScreen(wave[levelTimer]);

      // now generate the next wave
      generateNextWave();

    }

   ....
   levelTimer+=1;

}

```

Every frame in our game loop we check for `wave[levelTimer]` to see if its empty. If its not we add all the ships in that wave to the game. Please let me know if you need more clarification.

---
Tags: level-design, platformer
---


# Question
Title: How to get nicer shadows from distant point lights?
I get too unsatisfying results for shadows when using a point light that is far away. *(The quality settings are maxed.)*

The scene:

The result:

The light:

What can I do to get better shadows?

# Answer
Point lights are not usually used for distant lighting. Use a Spot light instead. The results will be better.

Be sure to increase the Range.

If looks too bright, decrease Intensity.

Range 130, Intensity 1.3, Anti aliasing 8x multi, Shadow Res Very high.

Distance between light and shadow receiver 30 Unit. Distance between light and shadow caster 25 Unit.
> 1 votes

# Answer
Use hard shadow instead of soft shadows.
> -2 votes

---
Tags: unity, lighting, shadows
---


# Question
Title: Why I get inconsistent occlusion query results?
My system: Catalyst 15.12, mesa 11.2.1, Archlinux, kernel 4.5.1

Depending on camera position I get inconsistent occlusion query results. Following scene contains wall, objects behind wall and objects on sides. Objects behind wall are always invisible(correct). Objects on sides should be always visible but sometimes marked as invisible. Why? On screenshots green means visible, red boundary means occluded:

This is the code that I use:

```
void gems_render_objects(Scene *scene) {
    int i = 0, j = 0, res;
    AssetInstance *inst;

    if(!s_queryIds) {
        s_queryIds = (GLuint*)malloc(sizeof(GLuint)*(scene->numInstances));
        glGenQueries(scene->numInstances, s_queryIds);
    }

    //draw everything
    for(i = 0; i < scene->numInstances; i++) {
        glc_draw_inst(scene, scene->instances+i, &s_curProgramId, &s_curVaoId);
    }

    //query everything
    glDepthMask(GL_FALSE);
    glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
    for(i = 0; i < scene->numInstances; i++) {
        inst = scene->instances+i;

        glBeginQuery(GL_SAMPLES_PASSED, s_queryIds[i]);
        glc_draw_inst(scene, inst->bbInst, &s_curProgramId, &s_curVaoId);
        glEndQuery(GL_SAMPLES_PASSED);
    }
    glDepthMask(GL_TRUE);
    glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);

    //draw bounding boxes of invisible
    glDepthMask(GL_FALSE);
    glDisable(GL_DEPTH_TEST);
    for(i = 0; i < scene->numInstances; i++) {
        inst = scene->instances+i;

        res = 0;
        glGetQueryObjectiv(s_queryIds[i], GL_QUERY_RESULT, &res);

        if(res == 0) {
            GLenum prevDrawType = inst->bbInst->asset->drawType;
            inst->bbInst->asset->drawType = GL_LINE_STRIP;
            glc_draw_inst(scene, inst->bbInst, &s_curProgramId, &s_curVaoId);
            inst->bbInst->asset->drawType = prevDrawType;
        }
    }
    glEnable(GL_DEPTH_TEST);
    glDepthMask(GL_TRUE);
}

```

# Answer
I needed to use glDepthFunc(GL\_LEQUAL) for queries because bounding boxes have the same size as objects size (z-fighting).

```
//query everything
    glDepthMask(GL_FALSE);
    glDepthFunc(GL_LEQUAL); //this is critical
    glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
    for(i = 0; i < scene->numInstances; i++) {
        inst = scene->instances+i;

        glBeginQuery(GL_SAMPLES_PASSED, s_queryIds[i]);
        glc_draw_inst(scene, inst->bbInst, &s_curProgramId, &s_curVaoId);
        glEndQuery(GL_SAMPLES_PASSED);
    }
    glDepthMask(GL_TRUE);
    glDepthFunc(GL_LESS);
    glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);

```
> 2 votes

---
Tags: opengl, occlusion
---


# Question
Title: Unity - Small holes of light seems to go through my blender mesh
So, I am currently working on a low-poly terrain in Blender which will be flat-shaded in Unity. It all works great, however I am working on a cave for the terrain, and I seem to be getting these small odd light artifacts:

I have tried to highlight them with the read circles. If you look carefully, you can see the small holes.

The odd thing is, the entire mesh should be completely solid. Here's a screenshot of the cave entrance in blender (which is the floor I'm looking at in Unity)

All normals of the faces seems to be facing correctly, and mesh has simply been modelled by extruding edges from existing parts of the mesh, so there shouldn't actually be any actual holes.

Does anyone have any experince with this kind of problem?

# Answer
I believe that might be related to "shadow acne." Try lowering the bias of your directional lights.

**http://answers.unity3d.com/questions/925812/unity-5-real-time-lights-cast-shadows-with-gaps-li.html**
> 4 votes

---
Tags: unity, rendering, lighting, blender, mesh
---


# Question
Title: How to keep text on top of openGL in a perspective projection
I have a game that has a score, I found out how to render text in a ortho projection but I can find a way to mix the two, or have text stay in the same position on the screen at the same time as camera movement. Would I need to constantly change the position and depth of the text to keep it on top of everything and on the screen at the same time?

# Answer
No, you can first render your perspective scene normally, and then switch to an orthographic mode and render your text on top of that, supplying the text vertices in screen space and using a shader that doesn't do much notable transformation to the vertices.

(Strictly speaking you don't even *need* to do this second pass with an orthographic projection, but you can if you want.)

You may need to disable the depth test for the second pass that renders the text depending on how you render it.
> 3 votes

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


title: Check if vertex is visible in shader

text:
# Question
Title: Check if vertex is visible in shader
Im trying to figure out when a vertex is visible from the main camera. I have this function:

```
bool in_frustum(float4x4 M, float4 p) {
            float4 Pclip = mul(M, float4(p.x, p.y, p.z, 1.0));
            return abs(Pclip.x) < Pclip.w &&
                abs(Pclip.y) < Pclip.w &&
                0 < Pclip.z &&
                Pclip.z < Pclip.w;
        }

```

I call it in the vertex shader, and it works fine. The problem is when I have multiple cameras, and I only want to know if it is within the frustum on one of the cameras. If the vertex is not visible from my target camera, I want all other cameras to render it (if it is visible) a particular way (for example red).

I am a little rusty on matrix transformations and the graphics pipeline, but maybe instead of passing UNITY\_MVP\_MATRIX into the in\_frustum function, I need to pass in the MVP matrix of the target camera? Or maybe just the View of the target camera needs to be replaced in.

# Answer
My guess was right. I just had to pass in the MVP matrix with respect to my target camera. So in unity:

```
    void LateUpdate () {
    _TargetRenderer.sharedMaterial.SetMatrix("_MVPTargetCam",
        _TargetCam.projectionMatrix *_TargetCam.worldToCameraMatrix * _TargetRenderer.localToWorldMatrix);
}

```
> 0 votes

---
Tags: unity, shaders, camera, glsl, hlsl
---


title: Draw bug is creating a lot of Enemies

text:
# Question
Title: Draw bug is creating a lot of Enemies
I'm working on 2d java game and I have little issues what I can't resolve. My problem is when I want to create 5 enemies with for loop, random post is creating lot of Enemies, not 5. How can I resolve it?

Enemy Class:

```
package game.entities;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Rectangle;

import game.handler.ID;
import game.handler.Objects;

public class Enemy extends Objects{

public Enemy(int x, int y, ID id) {
    super(x, y, id);
}

public void tick(){
}

public Rectangle getEnemyBounds(){
    return new Rectangle(x, y, 32, 32);
}

public void render(Graphics2D g){
    g.setColor(Color.RED);
    //g.fillRect(x, y, 32, 32);
    g.draw(getEnemyBounds());
}

}

```

Enemy Controller Class :

```
package game.handler;

  import java.awt.Graphics;
  import java.awt.Graphics2D;
  import java.util.LinkedList;
  import java.util.Random;

 import game.entities.Enemy;

public class EnemyController {

public static LinkedList<Enemy> e = new LinkedList<Enemy>();
private Random r = new Random();
Enemy enemy;

public EnemyController(){
    addEnemy(new Enemy(440, 400, ID.Enemy));
}

public void render(Graphics2D g){
    for(int i = 0;i <e.size();i++){
        enemy = e.get(i);

        enemy.render(g);
    }
}

public void tick(){
    for(int i = 0;i <e.size();i++){
        enemy = e.get(i);

        enemy.tick();
    }
}
public void addEnemy(Enemy enemy){
    e.add(enemy);
}

public void removeEnemy(Enemy enemy){
    e.remove(enemy);
}

public static LinkedList<Enemy> getEnemyBounds(){
    return e;
}

}

```

Tile Class :

```
package game.Tile;

import java.awt.Graphics;
import java.util.Random;

import game.engine.Game;
import game.entities.Enemy;
import game.handler.EnemyController;
import game.handler.Handler;
import game.handler.ID;

public class Tile {

private final int EnemyCount = 5;
private int level = 1;
private Handler handler;
private Random r = new Random();
private EnemyController enc = new EnemyController();

public void tick(){

}

public void render(Graphics g){
    for(int i=0;i< EnemyCount;i++){
        enc.addEnemy(new Enemy(r.nextInt(400), r.nextInt(400), ID.Enemy));
    }
}
}

```

Game Class :

```
package game.engine;

import java.awt.Canvas;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferStrategy;
import java.util.Random;
import game.graphics.HUD;
import game.handler.Handler;
import game.input.KeyBoard;
import game.states.Gameover;
import game.states.Menu;
import game.states.Shop;

public class Game extends Canvas implements Runnable{

public final static int WIDTH = 600;
public final static int HEIGHT = 600;
final int EnemyCount = 5;
int level = 1;

private Thread th;
private boolean running = false;

////////////////////////
private Handler handler;
private Menu menu;
private Shop shop;
private HUD hud;
private Gameover ga;
private Random r = new Random();

public enum STATE{
    GAME,
    MENU,
    HELP,
    HELPP,
    OPTIONS,
    SHOP,
    GAMEOVER,
}

public static STATE gamestate = STATE.MENU;

public Game(){

    ga = new Gameover();
    hud = new HUD();
    shop = new Shop();
    menu = new Menu(this);
    handler = new Handler();
    this.addKeyListener(new KeyBoard());
    this.addMouseListener(menu);
    this.addMouseListener(shop);
    this.addMouseListener(ga);

    new Main(WIDTH, HEIGHT, "Game", this);

    if(gamestate == STATE.GAME){

    }
}

public void  start(){
    th = new Thread(this);
    th.start();
    running = true;

}

public void stop(){
    try {
        th.join();
        running = false;
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

@Override
public void run() {
    while(running){
        this.requestFocus();
        render();
        tick();
    }
}

public void tick(){
    if(gamestate == STATE.GAME){
        handler.player.tick();
        handler.enemyc.tick();
        handler.enemyc.tick();
        handler.hud.tick();
    }else if (gamestate == STATE.MENU){
        menu.tick();
    }else if(gamestate == STATE.SHOP){
        handler.shop.tick();
    }else if(gamestate == STATE.GAMEOVER){
        ga.tick();
    }
}

public void render(){
    BufferStrategy b = this.getBufferStrategy();
    if(b == null){
        this.createBufferStrategy(3);
        return;
    }

    Graphics g = b.getDrawGraphics();
    Graphics2D g2 = (Graphics2D) g;
    g.setColor(Color.BLACK);
    g.fillRect(0, 0, WIDTH, HEIGHT);
    if(gamestate == STATE.GAME){
        handler.player.render(g2);
        handler.enemyc.render(g2);
        handler.hud.render(g);
    }else if(gamestate == STATE.MENU || gamestate == STATE.HELP){
        menu.render(g);
    }else if(gamestate == STATE.OPTIONS || Game.gamestate == STATE.HELPP){
        menu.render(g);
    }else if(gamestate == STATE.SHOP){
        handler.shop.render(g);
    }else if(gamestate == STATE.GAMEOVER){
        ga.render(g);
    }
    try {
        th.sleep(3);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

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

public static void main (String [] args){
    new Game();
}
}

```

# Answer
> 1 votes
OK, assuming that `render()` gets called once per frame you are telling your game to create 5 new enemies every frame in the tile class. This would lead to creating hundreds of enemies per second.

I think you only want to use that for loop once when initialising the game. That way you will only make 5 (until you decide to make more).

look in the documentation for your game engine for what is called first when the game starts, most engines will have a start method that is called in which case move the code inside the `render()` method to that initialisation method.

Good luck, and welcome to stack exchange :)

# Answer
> 0 votes
How many times are you calling render from the Tile class? Because every time you do it adds 5 new enemys. If you are calling that render method a lot then I would suggest moving the for loop to the constructor.

---
Tags: java, graphics, rendering
---


# Question
Title: Per-Texel lighting? (not per-vertex or per-pixel)
In my game, I have a 3D shader that does lighting using color ramps on models with very low resolution textures. Basically, the vertex shader calculates color values for direct light and ambient occlusion, and then I look up into a color ramp what color to draw, and multiply this by the texture map.

Here's some pseudocode for that:

```
// vertex shader:
color_vert.r = ambient_occlusion(vertex)
color_vert.g = direct_lighting(vertex)
color_vert.b = shadow_lighting(vertex)

// fragment shader:
// First, the color is whatever the direct lighting was
color_fragment = direct_lighting_ramp_lookup(color_vert.g)
// Multiply by ambient occlusion and shadow
color_fragment *= ambient_lighting_ramp_lookup(color_vert.r)
color_fragment *= shadow_lighting_ramp_lookup(color_vert.b)
// Mutiply by the surface texture
color_fragment *= texture_lookup(color_vert.uv)

```

Now, this kind of lighting would be fine if I had very high resolution textures, but unfortunately my textures are very low resolution. So each texel (that is, the block of pixels corresponding to one pixel of the texture) is quite large, and lighting gets interpolated across the texel.

Here's an image of what that looks like:  And here's a closeup to show you what I mean:

Notice how the color is smoothly getting interpolated accross the low-resolution texels? How can I write my shader such that the lighting gets clamped on a per-texel basis? Is such a thing even possible? The only solution I can think of is to first generate a lightmap for the whole scene with 1-1 mapping to texels, but I'm afraid that would be too slow / use too much memory.

# Answer
BTW, I ended up solving this using a lightmap. My process was as follows:

1. Generate a UV map for the mesh by packing all the triangles together using a simple scanline algorithm.
2. Render the scene directly to the UV map instead of to the screen. This way, pixels are 1:1 related to texels.
3. Render the scene again to the screen, this time using the generated UV light map as a texture.

Here's what the lightmap ended up looking like:

And the final composite:
> 1 votes

---
Tags: shaders, lighting, fragment-shader, resolution
---


title: Unity SOAP wsdl problem

text:
# Question
Title: Unity SOAP wsdl problem
i'm trying to using a SOAP service from my game but the problem is that after using wsdl.exe for generete the connector Unity inform me that System.Web namespace doesn't exist.

How can I use the wsdl? There is some workaround without writing a lot of code?

Many thanks

# Answer
> -1 votes
I've been able to resolve my issue by importing these DLLs in my project:

* `System.Web.dll`
* `System.Web.Services.dll`

---
Tags: unity
---


# Question
Title: Best way of approach? Mob moving around a section of tiles
Think the beginning stages of Metroid, where there would be a turtle-like mob that would move around a section of tiles, normally 1-3 in a line.

What would be the best approach to accomplish this sort of AI?

It seems so simple but its giving me headache.

The solution I've found have been to have a fixed distance for it to move, and changing directions once the distance has been met. This isn't that OOP though.

Another would be have a rectangle made of the section of tiles, and when the bounds of the mob no longer contains the line of rectangle, change directions. This is proving to be harder to implement and only works for rectangular sections, not for abstract "tetris" like sections of tiles.

# Answer
Found an easy way of doing it, after having troubles with getting smooth movement under milk's suggestion. Here's the source, (python / jython):

s == the mob, and territory == its rectangular "home" area. The +1's and +2's I added to some corners to make it look better as it was a bit "snappy".

```
fullBounds = s.getFullBounds()
rightBounds = s.getRightBounds()
leftBounds = s.getLeftBounds()
topBounds = s.getTopBounds()
bottomBounds = s.getBottomBounds()

top = s.territory.getTop()
right = s.territory.getRight()
left = s.territory.getLeft()
bottom = s.territory.getBottom()

if s.clockWise:
    if fullBounds.intersects(right) and not fullBounds.intersects(bottom):
        s.setVelocity(0, speed)
        s.setX(s.territory.pos.x + s.territory.getWidth())
        s.setY(restrict(s.getY(), s.territory.getY() - 2))
    elif fullBounds.intersects(top):
        s.setVelocity(speed, 0)
        s.setY(s.territory.pos.y - s.HEIGHT)
        s.setX(restrict(s.getX(), s.territory.getX() - 1))

    if fullBounds.intersects(left) and not fullBounds.intersects(top) and not topBounds.intersects(bottom):
        s.setVelocity(0, -speed)
        s.setX(s.territory.pos.x - s.HEIGHT)
    elif fullBounds.intersects(bottom):
        s.setVelocity(-speed, 0)
        s.setY(s.territory.pos.y + 2 + s.HEIGHT)

elif not s.clockWise:
    if fullBounds.intersects(right) and not fullBounds.intersects(top):
        s.setVelocity(0, -speed)
        s.setX(s.territory.pos.x + s.territory.getWidth())
        s.setY(restrict(s.getY(), s.territory.getY() - 2))
    elif fullBounds.intersects(top) and not fullBounds.intersects(left):
        s.setVelocity(-speed, 0)
        s.setY(s.territory.pos.y - s.HEIGHT)

    if fullBounds.intersects(bottom) and not fullBounds.intersects(right):
        s.setVelocity(speed, 0)
        s.setY(s.territory.pos.y + s.HEIGHT + 2)
    elif fullBounds.intersects(left):
        s.setVelocity(0, speed)
        s.setX(s.territory.pos.x - s.HEIGHT)

```
> 0 votes

# Answer
You want to patrol between different locations, so you could just create a list of locations to visit in order (so you would have two locations for a move back and forth behavior). Once your actor has visited each location she can start over and return to the first location (or you could visit the locations in reverse order, or stop, or whatever).

For arbitrary shaped patrols like you mention in the last paragraph, you can just add more locations to visit on the patrol (eg- (0,0) -\> (5,0) -\> (5,5) to create an L-shaped patrol).

Some pseudo-code for this kind of behavior:

```
class Patroller
{
    private List<Location> _locationsToVisit;

    private int _nextLocationIndex;

    public void Update()
    {
        // Visit each location
        var nextLocation = _locationsToVisit[_nextLocationIndex];
        MoveToward(nextLocation);

        if (IsAt(nextLocation))
        {
            _nextLocationIndex++;
            // If visited each location, then set the next as the first location.
            // Alternately you could start visiting the locations in reverse order
            if (_nextLocationIndex >= _locationsToVisit.Count)
            {
                _nextLocationIndex = 0;
            }
        }
    }
}

```
> 0 votes

---
Tags: ai, tilemap, tiles
---


title: Trajectory Arcs

text:
# Question
Title: Trajectory Arcs
Ok so I have read this question Calculating trajectory. And it is sort of working in my program. I am trying to produce nice parabolic arcs with this. Like so ..

The results I am getting look more like this..

Here is my the code that gets updates every frame. Note: my object is starting on the right side of the screen and moving towards the left which is what I want.

```
public void update(float deltaTime)
{
    this.mDeltaTime = deltaTime;
    ....

    mPosition = new Vector2(mPosition.X + .5f * (mDeltaTime - 5.35f)*.25f,
    mPosition.Y + .5f * (mDeltaTime + 5.35f)*.25f);

    ....
}

```

I am going to go back and clean it up once its producing what I need it to. I am not sure if the initial starting position is the apex of the arc or if it is just moving linearly.

# Answer
The accepted answer can be found at Animate Sprite Along a Curve path in XNA

I appreciate the help people have tried to post.

```
static float mFlightTime = 0.0f;

Vector2 mVelocity = new Vector2(-12, -8);
Vector2 mAcceleration = new Vector2(0f, 1f);
Vector2 mStartingPosition =  new Vector2(260.0f, 31.0f);

Vector2 mPosition = Vector2.Zero;

public void update(float deltaTime)
{
    this.mDeltaTime = deltaTime;
    ....

    mFlightTime += .3f;

    mPosition = mStartingPosition + mVelocity * mFlightTime +
                            0.5f * mAcceleration * mFlightTime * mFlightTime;
    ....
}

```
> -1 votes

# Answer
Parameterized equations of (2D) motion for a parabola are as follows:

```
x = x0 + t * Vx
y = y0 + t * Vy - 0.5 * g * t^2

```

with a sign convention of increasing X rightward, increasing Y upward.

These are a simple adaptation of the kinematic equations of motion under constant acceleration.
> 1 votes

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


# Question
Title: How do I pixelate a scene with SceneKit and Metal, in Swift?
I managed to get pixelation working by using the OpenGLES2 rendering API, and a CIFilter. But it was way too slow, so I want to use the Metal API and just have a very simple filter that pixelates everything in the scene.

Would really appreciate some help, maybe just explaining how to set up SceneKit to use a Metal shader. Is there something I can just drop in with a few lines?

# Answer
I don't think this is going to be quite as easy as you'd like, that said you should be able to copy/paste the code below to get something going.

There might be a better way to approach this, but as I see it you'll need 2 render passes. The first to render the scene to a low resolution to introduce pixelation, and a second to resample the low resolution render to the resolution of the screen. `SCNTechnique` is how multi-pass rendering is supported in SceneKit.

The following xml defines the rendering passes for this pixelate technique, add a plist file to you project (`pixelate.plist`) and paste this in.

```
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
    <dict>
        <key>passes</key>
        <dict>

            <key>pixelate_scene</key>
            <dict>
                <key>draw</key>
                <string>DRAW_SCENE</string>
                <key>inputs</key>
                <dict/>
                <key>outputs</key>
                <dict>
                    <key>color</key>
                    <string>color_scene</string>
                </dict>
                <key>colorStates</key>
                <dict>
                    <key>clear</key>
                    <true/>
                    <key>clearColor</key>
                    <string>sceneBackground</string>
                </dict>
            </dict>

            <key>resample_pixelation</key>
            <dict>
                <key>draw</key>
                <string>DRAW_QUAD</string>
                <key>program</key>
                <string>doesntexist</string>
                <key>metalVertexShader</key>
                <string>pixelate_pass_through_vertex</string>
                <key>metalFragmentShader</key>
                <string>pixelate_pass_through_fragment</string>
                <key>inputs</key>
                <dict>
                    <key>colorSampler</key>
                    <string>color_scene</string>
                </dict>
                <key>outputs</key>
                <dict>
                    <key>color</key>
                    <string>COLOR</string>
                </dict>
            </dict>

        </dict>
        <key>sequence</key>
        <array>
            <string>pixelate_scene</string>
            <string>resample_pixelation</string>
        </array>
        <key>targets</key>
        <dict>
            <key>color_scene</key>
            <dict>
                <key>type</key>
                <string>color</string>
                <key>size</key>
                <string>75x75</string>
            </dict>
        </dict>
        <key>symbols</key>
        <dict></dict>
    </dict>
</plist>

```

If you'd like to understand more about what's going on in this block of XML refer to the Apple docs, I'll only cover the specifics here. The `sequence` element defines the order of our two render passes; `pixelate_scene` and `resample_pixelation`. The definition of each pass is defined in the `passes` element.

With the `DRAW_SCENE` draw instruction and not setting any shaders to the `pixelate_scene` we tell SceneKit to simply render the scene to the output target (a texture) using its standard shaders. The target in this case `color_scene` is a color texture with a size of 75x75px, this is defined in the `targets` element at the end of the xml file.

The `resample_pixelation` pass is a bit different, as now we want to perform a rendering pass over the texture in `color_scene`. To do this we use the `DRAW_QUAD` draw instruction, with this SceneKit builds us a fullscreen quad on which our input texture is mapped. This time we do need to define a vertex and fragment shader.

It doesn't matter what `.metal` file you include this in, only the shader names do need to match those found in the plist definition.

```
#include <metal_stdlib>
using namespace metal;
#include <SceneKit/scn_metal>

struct custom_vertex_t
{
    float4 position [[attribute(SCNVertexSemanticPosition)]];
};

constexpr sampler s = sampler(coord::normalized,
                              address::repeat,
                              filter::nearest);

struct out_vertex_t
{
    float4 position [[position]];
    float2 uv;
};

vertex out_vertex_t pixelate_pass_through_vertex(custom_vertex_t in [[stage_in]],
                                                 constant SCNSceneBuffer& scn_frame [[buffer(0)]])
{
    out_vertex_t out;
    out.position = in.position;
    out.uv = float2((in.position.x + 1.0) * 0.5 , (in.position.y + 1.0) * -0.5);
    return out;
};

fragment half4 pixelate_pass_through_fragment(out_vertex_t vert [[stage_in]],
                                              texture2d<float, access::sample> colorSampler [[texture(0)]])
{
    float4 fragment_color = colorSampler.sample( s, vert.uv);
    return half4(fragment_color);
};

```

This is a simple Metal shader for our fullscreen quad. The vertex shader calculates the UV texture coordinates, and the fragment shader simply resamples the input texture (low res 75x75 texture) and writes it to the output. One thing to point out is in the sampler definition, using `filter::nearest` means that we'll get nice sharp pixels. You could also use something like `filter::linear`, but this would blur the pixels.

Lastly you'll need to apply this `SCNTechnique`.

```
if let path = NSBundle.mainBundle().pathForResource("pixelate", ofType: "plist") {
    if let plistDict = NSDictionary(contentsOfFile: path)  {
        let plistStrDict = plistDict as! [String : AnyObject]
        let pixelateTechnique = SCNTechnique(dictionary:plistStrDict)
        scnView.technique = pixelateTechnique
    }
}

```

And if all goes according to plan...

Source code for this can be found in my GitHub repo, just make sure you check out the pixelate branch.
> 8 votes

---
Tags: shaders, rendering, ios, swift, scenekit
---


# Question
Title: Transforming Position in y-axis (going down) in Unity
I want the gameobject to go down (position.y) after pressing a key instead of pressing the key repeatedly. So in my current code the object goes down(0.05f) each time I press a key. But I want it to go down (1.2) with a smooth animation when I press a key.

```
Vector2 Pos;

void Update ()
{
 Pos = transform.position;

 if(Input.anyKeyDown)
 {
   ChangePosY();
 }
 transform.position = Pos;
}

void ChangePosY()
{
 if (Pos.y >= 1.2)
 {
  Pos.y -= 0.05f;
 }
}

```

# Answer
> 0 votes
You may use smooth translation with `Vector2.Lerp()`. One new variable `isKeyPressed` to detect key pressed which is changed when target position condition meets, until it translates towards target position with 1.2 unit in y-axis/downward with 0.1 frequency. See Lerp() Ref.

```
Vector2 Pos;
bool isKeyPressed = false;

void Update()
{
    Pos = transform.position;

    if (Input.anyKeyDown)
    {
        isKeyPressed = true;
    }

    if (isKeyPressed)
    {
        ChangePosY();
    }
    transform.position = Pos;
}

void ChangePosY()
{
    if (Pos.y >= 1.2f)
    {
        Pos = Vector2.Lerp(Pos, new Vector2(Pos.x, Pos.y - 1.2f), 0.1f);
    }
    else
    {
        isKeyPressed = false;
    }
}

```

# Answer
> 1 votes
I'd do this with a coroutine:

```
// Keep track of the current coroutine so we don't stack up multiple.
Coroutine translation;

void Update()
{
     if(Input.anyKeyDown)
     {
         translation = StartCoroutine(
                           TranslateTo(
                              /* Put the final position you want here */,
                              1.0f
                           )
                       );
     }
}

IEnumerator TranslateTo(Vector3 destination, float duration)
{
     // Stop previous coroutine if the last motion didn't finish yet.
     if(translation != null)
         StopCoroutine(translation);

     Vector3 initialPosition = transform.position;

     // Shifting the start back one frame so we move a little immediately.
     float startTime = Time.time - Time.deltaTime;
     float endTime = startTime + duration;

     while(Time.time < endTime)
     {
         float t = (Time.time - startTime)/duration;
         transform.position = Vector3.Lerp(initialPosition, destination, t);

         // Wait one frame, then resume here.
         yield return null;
     }

     // Ensure we finish exactly at the destination.
     transform.position = destination;

     // Clear coroutine cache to signal that we're done.
     translation = null;
}

```

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