# Question
Title: How can I find multiple starting areas on a procedural map?
I'm using perlin noise to generate a 2d map, with ground types and natural resources.

When you start a new game I need to place your town hall as well as your opponents in such a way they are on grassland and near natural resources.

For an oversimplification, I have a 2d array of integers where a block of 0s and a couple 1s would be great for starting but anything lower than a 0 would be bad. How can I isolate a few blocks of what I'm looking for, ideally with a distance threshold so town halls aren't next to each other.

How does civilization do this for example?

# Answer
Finding locations that are suitable close to resource can be done using influence maps \- data structures that model various relationships with respect to their locations, and typically assume that the impact of these relationships spread outward across space and/or time. (I recall having heard that some titles in the Civilization series use influence maps, bu I don't have a definitive reference for that at the moment)

The core concept of an influence map is that some locations have values which in turn influence the values of the surrounding area. The good news is that they are very flexible & you have a lot of options in terms of their design & implementation. Unfortunately, that's also the bad news - there's so much choice that finding the right balance of features & functions requires a bit of experience or experimentation. Here's a couple of examples based on the situation you've described.

First, we assign some value to the resource locations. I arbitrary picked 5 locations on a 8x8 grid & gave them all the value of 10 as shown on the left. Next, the influence spreads, as shown on the right. Since I was doing this all by hand, I simply decreased the value based on Manhattan distance, but you can change the metric to suit your needs.

The next thing to do is decide how influence is combined from multiple sources. I've shown two options. The one on the left uses uses addition. This is most appropriate for situations where the combined amount of resources is important, for instance, if more ore allows you to get more gold. On the right I used the `max` function; this would be more appropriate when only the distance to the nearest source matters, but additional source don't help.

I've also colored coded things to make them a bit easier to read. For each I picked a threshold & everything at that level or higher, I tinted green.

From here, you can look for other factors such as masking to include only acceptable terrain. Then consider candidate locations. That part should straight forward. Identifying all location pairs that are at least a minimum distance apart is the really hard part. Often times there are just too many possible combinations to consider, so practice, it tends to be solved stochastically. You randomly pick a location & then see if there's a suitable partner location for the opposing base. Using the fast Poisson disk sampling techniques might help.

Finally, you need to consider what might go wrong. There's a chance that a given random map might not have a suitable combination of locations. There's also a chance that a few combination exist, but there are some many invalid combinations that you're statistically unlikely to find them. In that case, you need a fall back solution. Some options are:

* generate a new map & try again
* force the current map to have certain features
* relax your constraints & have one or more locations further than desired from the resources
> 2 votes

# Answer
An option is to avoid searching for locations and just force them.

You could place all the starting locations a suitable distance away from each other, and for every location, change the local terrain to grassland and add resource nodes nearby if there aren't enough.
> 3 votes

---
Tags: tilemap
---


# Question
Title: Can you have shader variables that vary per primitive?
A shader normally has values that vary per-vertex and values that vary per-fragment.

Can you have values that vary only per primitive, such as per-triangle or per-quad?

# Answer
No, you can't, there is no such concept in the graphics pipeline.

If you are using instancing, you can control the rate at which the instanced attributes advance for a given attribute index. This can be done independently for each attribute, and is probably the closest you're going to get to what you are asking for using the actual functionality of the pipeline. It may not be flexible enough for your needs, however, and it does require instanced rendering.

You can, of course, always build this abstraction into your CPU-side rendering layer by having a buffer object that understands what kind of primitive it stores (triangles, quads, lines, et cetera) and provides a way to manipulate per-primitive attribute buffers which, under the hood, it will replicate out into the *real* vertex buffer on a per-vertex basis. This won't give you the space-saving advantages, but it would present the simpler client-side interface that you are probably interested in.
> 2 votes

# Answer
For this pupose, you may use buffer texture and access it in the fragment shader using gl\_PrimitiveID.
> 0 votes

---
Tags: glsl, webgl
---


# Question
Title: Hide an image once all enemies in a zone are defeated
In my game there are several buildings that a main character has to free from enemies. I put a kind of a logo above all those have-to-be-released buildings, indicating that a certain building is not free and it has to be released.

What I want to achieve is that when I kill all of the enemies near a certain building, the logo above that building has to disappear, indicating means that the building was released.

I don't know how to detect this condition of "all nearby enemies defeated" in my script — how can I do that, and hide the image when the condition is met?

# Answer
Assuming that your logo is a unity object, the simplest thing you can do is:

```
GameObject myImage;

void myfunc() {
    myImage.SetActive(false);
}

```

This will disable your image and all its components, it will also not be visible (since it deactivates the mesh as well).

Edit:

I forgot to mention, you can also deactivate the image's component, if you want to keep the rest of the object alive:

```
Sprite myImage;

void myfunc() {
    myImage.enabled = false;
}

```

Both examples assume that you know how to get a reference of an object inside a script, if you do not know how let me know and I'll update my answer.

Assuming all your enemies are inside a `List`, every time an enemy dies, you can remove them from the `List` (`List.RemoveAt(index)`). Once the `List` is empty for a particular building, that means the building is free and you can make the logo disappear.

If your enemies are inside an array where you can't remove them from, add a variable inside enemies like `bool isDead = false;`, when they die, it becomes `true`. Once all enemies inside the array have this variable as `true` it means they are all dead and you can proceed to free the building.

Edit2:

Here's how a script would (ideally) look:

```
public Transform enemyPrefab;
List<Transform> enemies = new List<Transform>();
int numberOfEnemies = 5;

public Start() {

    // Generate enemies for this building
    for (int i = 0; i < numberOfEnemies; i++) {
        Enemy e = Instantiate(enemyPrefab);
        e.position = new Vector3(i, 0, 0); // Position you want the enemy to have
        enemies.Add(enemy); // Add enemy in the list
    }

}

public void EnemyDied(Enemy e) {
    enemies.Remove(e);
    if (enemies.Count == 0) {
        // All enemies died, free building
    }
}

```

This assumes that you have a prefab of the enemy you want to use. Attach this to each of your buildings, and they will spawn enemies. Once the player attacks an enemy and they die, they should call `myBuilding.EnemyDied(this)` to announce to the building that they died. (where `myBuilding` is the building they belong to)

Unfortunately I can't write anything more precise since I don't know what your code looks like so far. If you are struggling with some concepts like what a prefab is, I would suggest looking some unity tutorials online to familiarise yourself with them.

This script is also meant to give you an idea of how this problem could be solved, it's not the only way, and certainly not the best way. Adjust as needed to your situation.
> 1 votes

# Answer
You can use sphere collider (or something like this, can't say now) to detect enemies in specified area. When collider won't be able to find anybody it can be understood as "building is free".

I think first answer (with all edits) can work here better tho, but my solution works too :D Please let me know if you would like to know more about this so I will make an edit with explanations.
> 0 votes

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


title: Unity Vector3 position inside collider

text:
# Question
Title: Unity Vector3 position inside collider
I am trying to create a "wander" action that will make my NPC walk to a random position.

The catch is that the NPC should only go positions inside of a collider.

I have a huge Sphere that has a collider on it now I only want my NPC to go to positions that are inside that Sphere collider.

My question is how do i find a random position inside of a colider?

**Update**

So after testing i am unable to use colliders because the sphere is too big here is an image of my gameobject:

As you can see from the image I have a huge sphere that my NPC's will have to stay inside when wandering

In order to use the `Collider.ClosestPoint()` the collider has to be a Box, sphere or a mesh collider with a convex.

Sadly this is not feasible for me because the sphere should not collide with other objects.

So my question is how do I find a point inside this gameobject?

# Answer
> 4 votes
Use `Collider.ClosestPoint(Vector3 position)`. From the documentation:

> Returns a point on the collider that is closest to a given location.

Update:

> Sadly this is not feasible for me because the sphere should not collide with other objects.

If you want your collider to not limit movement of objects, you can turn it into a Trigger. The function `Collider.ClosestPoint` can be used regardless.

Here's some example:

```
class MyNPC {

    // Assign through inspector
    public Collider bigSphere;

    // Where to move to
    Vector3 target;

    // Called when NPC has to select a new location to move to
    void SelectTarget() {

        // Bounds of the sphere
        Bounds b = bigSphere.bounds;

        // Get a random point inside the bounds
        target = new Vector3(
            Random.Range( b.min.x, b.max.x ),
            Random.Range( b.min.y, b.max.y ),
            Random.Range( b.min.z, b.max.z )
        );

        // Find the closest point that belongs in the collider from that
        target = bigSphere.ClosestPoint(target);

        // Now target holds a random point inside the sphere

    }

```

# Answer
> 0 votes
Why not do some maths?

To generate a point which is inside said sphere, just make sure the distance from the sphere's origin (center) to the random generated point is lower than the sphere's radius. (you can work the calculation out with the squared distance since you don't need the actual difference - to optimize calculations speed)

To reduce the number of randomly generated coordinate tuples which don't satisfy the condition above, make it so that your random function generates numbers between 0 and your sphere's radius. Then there is a great chance that the resulting 3d point will be inside - if not then generate another one etc.

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


# Question
Title: How can I resolve collisions a little better?
I'm currently developing a physics engine and I'm not sure the best way to go about resolving my problem. I have a little box, that I can move around with in my scene.

When I'm resolving collisions, I take in the two bodies that are colliding, determine what both of their normal forces are and apply it to them (I also multiple it by a small number, if I don't I can't continue to walk around the scene).

Anyways, while I'm resolving the collision I do this:

```
a.Position -= a.Velocity;
b.Position -= b.Velocity;

```

I know this isn't a very good way to resolve the collision, but I'm just not sure how to do it correctly.

How should I go about resolve collision correctly?

Also, here is the whole method I use to resolve collision at the moment:

```
    private void ResolveCollision(Body a, Body b)
    {
        // Calculate normals forces (N = M * G)
        Vector2 normalForceA = this.CalculateNormalForce(a);
        Vector2 normalForceB = this.CalculateNormalForce(b);

        // Resolve collision, which is super buggy and obviously a bad idea.
        a.Position -= a.Velocity;
        b.Position -= b.Velocity;

        // Apply normal forces
        a.ApplyForce(-normalForceA * 11);
        b.ApplyForce(-normalForceB * 11);
    }

```

**EDIT:**

This is for a 2D game.

**EDIT**

Here is a video of what's going on when I applied TomTsagk's answer.

The video is here

# Answer
> 0 votes
It really depends on what result you would like to have. Here are some examples:

## Stick together

When two objects collide, you can make them "stick" to each other. For example, based on your code, replace

```
a.Position -= a.Velocity;
b.Position -= b.Velocity;

```

With

```
a.Position -= normalForceA;
b.Position -= normalForceB;

```

This assumes that `CalculateNormalForce` returns the length of the penetration of the objects. You may need to change `-` to `+` depending on your calculations. It makes objects stick together and not penetrate each other. Using `Velocity` is not a bad idea, but if an object is moving too fast, it can have a big distance from another object and trigger a collision. With this, your objects will be next to each other when colliding.

## Bounce

This is more realistic, but a little trickier to implement. Basically the idea is when an object is moving towards a direction, and it collides with another object, you calculate the distance that it travelled to reach that object. Most likely that distance is smaller than the object's velocity (otherwise there wouldn't be a collision) in which case the remaining velocity is applied in a "mirrored" direction.

Update:

If you are dealing with primarily objects that do not rotate (so they have fixed axis) one suggestion I can give would be (based on the video):

```
if (collide(a, b)) {

    b.position = a.top +b.height/2;

}

```

This assumes that `a` is a static object (in your case the ground) and `b` is the box falling on it. When collision happens, just move the box on top of the ground. I know this can't really apply to everything, but maybe it can help you find a better solution.

---
Tags: physics, physics-engine
---


# Question
Title: Unity for loop: (List) Argument out of range
I am attempting to copy the contents of one list into another. On the first iteration I get an "Argument out of range" error.

```
static List<Building> SaveBuildings(List<Building> buildings)
{
    if (buildings.Count == 0)
        return null;
    Debug.Log("Save Buildings Count: " + buildings.Count);
    List<Building> records = new List<Building>();
    for (int i = 1; i < buildings.Count; i++)
    {
        Debug.Log("i: " + buildings[i].name);
        records[i] = buildings[i].GetRecord();
    }
    return records;
}

```

The offending line is: **records\[i\] = buildings\[i\].GetRecord();**

This code "*Debug.Log("Save Buildings Count: " + buildings.Count);*" shows that the list is not empty. The following code "*List records = new List();*" instantiates a new list to be used.

My understanding is that everything should work well, but when I run the code this line fires "*Debug.Log("i: " + buildings\[i\].name);*" and then the error.

I've changed "int i" to be "0" and "i \< buildings.Count" to "i \<= buildings.Count" with i being 1 and 0. Same results.

I need fresh eyes to find the error lol thank you for your help

# Answer
> 3 votes
The issue is that `records` is empty. Are you intentionally skipping the first building? If not, I think this is what you want:

```
for (int i = 0; i < buildings.Count; i++)
{
    records.Add(buildings[i].GetRecord());
}

```

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


title: shooting in the direction of the mouse

text:
# Question
Title: shooting in the direction of the mouse
My game is a 2D, top-down game where you aim with the mouse and the gun follows it. I'm trying to get the bullet to go in the direction of where the mouse is. The code will be a component of the bullet prefab. here my code:

```
public class BulletBehavior : MonoBehaviour {

public float speed;

// Use this for initialization
void Start () {

}

// Update is called once per frame
void Update () {
    GetComponent<Rigidbody2D>().velocity = new Vector2(speed, GetComponent<Rigidbody2D>().velocity.y);
}

private void OnTriggerEnter2D(Collider2D collision)
{
    Destroy(gameObject);
}

```

}

# Answer
use this code it will lock the mouse position

```
  this.transform.position = Input.mousePosition;

```

and then add your bullet direction to follow it.
> 1 votes

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


# Question
Title: LibGDX transparent textures look weird for a brief moment during skeleton animation
So I have a stage with some characters (Spine2D Skeletons). Each character has a health bar/stamina bar texture above them. The textures are simple PNGs with some gradient on them and transparency too.

Sometimes, when I set an animation on one of the skeletons in the stage, some of the health/stamina bars textures look like they're color burned or the transparency doesn't work on them while the animation lasts.

I tried setting PremultiplyAlpha to true and to false on the skeleton renderer but it didn't help.

Do you have any idea why this could be?

Edit: Sample before and after images:

# Answer
I ended up setting the blend mode of the batch to what it was before the SkeletonRenderer used it to render the shapes. Not sure if this is the correct approach but it does look like it's working.

```
int blendDst = batch.getBlendDstFunc();
int blendSrc = batch.getBlendSrcFunc();

// skeleton renderer.draw(batch, skeleton); goes here

batch.setBlendFunction(blendSrc, blendDst);

// ordinary texture batch.draw() goes here

```
> 1 votes

---
Tags: libgdx, textures, animation, blending
---


# Question
Title: Why are my shapes teleporting to the center of the map?
I am making a Diep.io Clone, and everything was going smooth until I made a collision resolution system for when a shape collides with another shape. Instead of them bouncing off of each other, they teleport to the center of the map and don't move. The collision resolution for when a bullet hits a shape works just fine, but I cannot figure out why this is happening and how I can fix it. Thanks

Here is the collision resolution code:

```
this.update = function() {
    this.x -= this.velx;
    this.y -= this.vely;
    this.x -= this.pushx;
    this.y -= this.pushy;
    this.rot -= this.r;
    if(this.pushx > 0) {
        this.pushx -= this.acc;
    }
    if(this.pushy > 0) {
        this.pushy -= this.acc;
    }
    if(this.pushx < 0) {
        this.pushx += this.acc;
    }
    if(this.pushy < 0) {
        this.pushy += this.acc;
    }
    if(Math.abs(this.pushx) < this.acc) {
        this.pushx = 0;
    }
    if(Math.abs(this.pushy) < this.acc) {
        this.pushy = 0;
    }
};

this.gothit = function(other) {
    switch(other.constructor.name){
        case "shape":
            this.pushx += other.xvel * 5;
            this.pushy += other.yvel * 5;
            break;
        case "bullet":
            this.pushx += (other.dx / other.mag) * other.ms;
            this.pushy += (other.dy / other.mag) * other.ms;
            break;
    }
}

```

And here is the full code, if needed.

```
   var canvas = document.getElementById("canvas");
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
var c = canvas.getContext("2d");
c.lineCap = "round";
var mouseIsPressed = false;
var mouseClicked = false;
var autofire = false;
var autospin = false;
var tanks = [];
var keys = [];
var bullets = [];
var shapes = [];
var xpamt = [
0,
4,
13,
28,
50,
78,
113,
157,
211,
272,
350,
437,
536,
653,
784,
938,
1109,
1301,
1516,
1757,
2026,
2325,
2653,
3017,
3416,
3854,
4334,
4857,
5428,
6048,
6720,
7448,
8235,
9084,
9998,
10981,
12036,
13167,
14377,
15671,
17053,
18526,
20094,
21762,
23545
];
var tankstats = {
basic: {
 knockback: 1,
 reload: 500,
 bspeed: 3,
 bdamage: 3,
 bpenetration: 1,
 spread: 5
},
sniper: {
 knockback: 3,
 reload: 1000,
 bspeed: 5,
 bdamage: 3,
 bpenetration: 3,
 spread: 2
},
twin: {
 knockback: 1,
 reload: 250,
 bspeed: 0,
 bdamage: 3,
 bpenetration: 3,
 spread: 5
},
flankguard: {
 knockback: 0,
 reload: 500,
 bspeed: 1,
 bdamage: 3,
 bpenetration: 3,
 spread: 5
},
machinegun: {
 knockback: 2,
 reload: 150,
 bspeed: 3,
 bdamage: 3,
 bpenetration: 3,
 spread: 10
},
flamethrower: {
 knockback: 0.5,
 reload: 0,
 bspeed: 4,
 bdamage: 0.5,
 bpenetration: 1,
 spread: 20
},
overseer: {
 knockback: 0,
 reload: 3000,
 bspeed: 3,
 bdamage: 5,
 bpenetration: 3,
 spread: 0
},
};
var camx = 0;
var camy = 0;
var mousex = 0;
var mousey = 0;
var millis = 0;

function shape(x, y, id) {
this.x = x;
this.y = y;
this.id = id;
this.r = 0.01 - Math.random() / 50;
this.rot = 0;
this.velx = Math.random() / 10;
this.vely = Math.random() / 10;
this.pushx = 0;
this.pushy = 0;
this.acc = 0.1;
this.update = function() {
 this.x -= this.velx;
 this.y -= this.vely;
 this.x -= this.pushx;
 this.y -= this.pushy;
 this.rot -= this.r;
 if(this.pushx > 0) {
  this.pushx -= this.acc;
 }
 if(this.pushy > 0) {
  this.pushy -= this.acc;
 }
 if(this.pushx < 0) {
  this.pushx += this.acc;
 }
 if(this.pushy < 0) {
  this.pushy += this.acc;
 }
 if(Math.abs(this.pushx) < this.acc) {
  this.pushx = 0;
 }
 if(Math.abs(this.pushy) < this.acc) {
  this.pushy = 0;
 }
};
this.gothit = function(other) {
 switch(other.constructor.name) {
  case "shape":
   this.pushx += other.xvel * 5;
   this.pushy += other.yvel * 5;
   break;
  case "bullet":
   this.pushx += (other.dx / other.mag) * other.ms;
   this.pushy += (other.dy / other.mag) * other.ms;
   break;
 }
}
this.show = function() {
 c.save();
 c.translate(this.x, this.y);
 c.rotate(this.rot);
 switch(this.id) {
  case 0:
   c.fillStyle = "rgb(250, 250, 150)";
   c.strokeStyle = "rgb(200, 200, 100)";
   c.fillRect(-18, -18, 36, 36);
   c.beginPath();
   c.moveTo(-18, -18);
   c.lineTo(18, -18);
   c.stroke();
   c.beginPath();
   c.moveTo(18, -18);
   c.lineTo(18, 18);
   c.stroke();
   c.beginPath();
   c.moveTo(18, 18);
   c.lineTo(-18, 18);
   c.stroke();
   c.beginPath();
   c.moveTo(-18, 18);
   c.lineTo(-18, -18);
   c.stroke();
   break;
  case 1:
   c.fillStyle = "rgb(250, 150, 150)";
   c.strokeStyle = "rgb(200, 100, 100)";
   c.beginPath();
   c.moveTo(-20, 12);
   c.lineTo(0, -23);
   c.lineTo(20, 12);
   c.fill();
   c.beginPath();
   c.moveTo(20, 12);
   c.lineTo(0, -23);
   c.stroke();
   c.beginPath();
   c.moveTo(0, -23);
   c.lineTo(-20, 12);
   c.stroke();
   c.beginPath();
   c.moveTo(-20, 12);
   c.lineTo(20, 12);
   c.stroke();
   break;
  case 2:
   c.fillStyle = "rgb(150, 150, 250)";
   c.strokeStyle = "rgb(120, 120, 200)";
   c.beginPath();
   c.moveTo(0, 30);
   c.lineTo(29, 9);
   c.lineTo(18, -24);
   c.lineTo(-18, -24);
   c.lineTo(-29, 9);
   c.lineTo(0, 30);
   c.fill();
   c.beginPath();
   c.moveTo(0, 30);
   c.lineTo(29, 9);
   c.stroke();
   c.beginPath();
   c.moveTo(29, 9);
   c.lineTo(18, -24);
   c.stroke();
   c.beginPath();
   c.moveTo(18, -24);
   c.lineTo(-18, -24);
   c.stroke();
   c.beginPath();
   c.moveTo(-18, -24);
   c.lineTo(-29, 9);
   c.stroke();
   c.beginPath();
   c.moveTo(-29, 9);
   c.lineTo(0, 30);
   c.stroke();
   break;
 }
 c.restore();
};
}

function bullet(x, y, dx, dy, r, id, t, s, d, p) {
this.x = x;
this.y = y;
this.dx = this.x - dx;
this.dy = this.y - dy;
this.mag = Math.sqrt(this.dx * this.dx + this.dy * this.dy);
this.r = r;
this.id = id;
this.t = t;
this.ms = s;
this.xs = 0;
this.ys = 0;
this.d = d;
this.p = p;
this.update = function() {
 if(this.id != 1) {
  this.x -= (this.dx / this.mag) * this.ms;
  this.y -= (this.dy / this.mag) * this.ms;
  this.p -= 0.01;
 } else {
  this.xs = Math.abs(this.x - this.dx) / 20;
  if(this.xs > this.ms) this.xs = this.ms;
  if(Math.abs(this.x - this.dx) > 7) {
   this.x -= (this.dx / this.mag) * this.xs;
  }
  this.ys = Math.abs(this.y - this.dy) / 20;
  if(this.ys > this.ms) this.ys = this.ms;
  if(Math.abs(this.y - this.dy) > 7) {
   this.y -= (this.dy / this.mag) * this.ys;
  }
  this.dx = this.x - (-camx + mousex);
  this.dy = this.y - (-camy + mousey);
  this.mag = Math.sqrt(this.dx * this.dx + this.dy * this.dy);
 }
};
this.show = function() {
 c.beginPath();
 switch(this.id) {
  case 0:
   switch(this.t) {
    case 0:
     c.fillStyle = "rgb(100, 200, 250)";
     c.strokeStyle = "rgb(50, 150, 200)";
     break;
    case 1:
     c.fillStyle = "rgb(250, 150, 150)";
     c.strokeStyle = "rgb(200, 100, 100)";
     break;
    case 2:
     c.fillStyle = "rgb(150, 250, 150)";
     c.strokeStyle = "rgb(100, 200, 100)";
     break;
    case 3:
     c.fillStyle = "rgb(250, 150, 250)";
     c.strokeStyle = "rgb(200, 100, 200)";
     break;
   }
   c.arc(this.x, this.y, this.r, 0, 2 * Math.PI);
   c.fill();
   c.stroke();
  case 1:
   switch(this.t) {
    case 0:
     c.fillStyle = "rgb(100, 200, 250)";
     c.strokeStyle = "rgb(50, 150, 200)";
     break;
    case 1:
     c.fillStyle = "rgb(250, 150, 150)";
     c.strokeStyle = "rgb(200, 100, 100)";
     break;
    case 2:
     c.fillStyle = "rgb(150, 250, 150)";
     c.strokeStyle = "rgb(100, 200, 100)";
     break;
    case 3:
     c.fillStyle = "rgb(250, 150, 250)";
     c.strokeStyle = "rgb(200, 100, 200)";
     break;
   }
   c.arc(this.x, this.y, this.r, 0, 2 * Math.PI);
   c.fill();
   c.stroke();
 }
};
}

function tank(x, y, r, t, n, xp, lvl, id, inv) {
this.x = x;
this.y = y;
this.velx = 0;
this.vely = 0;
this.acc = 0.075;
this.maxSpeed = 3;
this.knockback = tankstats.basic.knockback;
this.bulletP = tankstats.basic.bpenetration;
this.bulletS = tankstats.basic.bspeed;
this.bulletD = tankstats.basic.bdamage;
this.r = r;
this.t = t;
this.n = n;
this.xp = xp;
this.lvl = lvl;
this.id = id;
this.inv = inv;
this.reload = tankstats.basic.reload;
this.reloading = false;
this.cooldown = this.reload;
this.timetill = 0;
this.update = function(r) {
 this.r = r;
 if(keys[87] && !keys[83]) {
  this.vely -= this.acc;
 }
 if(keys[83] && !keys[87]) {
  this.vely += this.acc;
 }
 if(keys[65] && !keys[68]) {
  this.velx -= this.acc;
 }
 if(keys[68] && !keys[65]) {
  this.velx += this.acc;
 }
 if(this.velx > this.maxSpeed) {
  this.velx = this.maxSpeed;
 }
 if(this.velx < -this.maxSpeed) {
  this.velx = -this.maxSpeed;
 }
 if(this.vely > this.maxSpeed) {
  this.vely = this.maxSpeed;
 }
 if(this.vely < -this.maxSpeed) {
  this.vely = -this.maxSpeed;
 }
 if(!keys[87] && !keys[83]) {
  if(this.vely < 0) {
   this.vely += this.acc;
  }
  if(this.vely > 0) {
   this.vely -= this.acc;
  }
  if(Math.abs(this.vely) <= this.acc) {
   this.vely = 0;
  }
 }
 if(!keys[65] && !keys[68]) {
  if(this.velx < 0) {
   this.velx += this.acc;
  }
  if(this.velx > 0) {
   this.velx -= this.acc;
  }
  if(Math.abs(this.velx) < this.acc) {
   this.velx = 0;
  }
 }
 this.x += this.velx;
 this.y += this.vely;
 if(mouseIsPressed || keys[32] || autofire) {
  if(this.cooldown === this.reload && !this.reloading) {
   switch(this.id) {
    case 0:
     bullets.push(new bullet(this.x + Math.sin(this.r) * 50, this.y - Math.cos(this.r) * 50, this.x + Math.sin(this.r) * 70, this.y - Math.cos(this.r) * 70, 10, 0, this.t, this.bulletS, this.bulletD, this.bulletP));
     break;
    case 6:
     bullets.push(new bullet(this.x + Math.sin(this.r) * 50, this.y - Math.cos(this.r) * 50, mousex, mousey, 10, 1, this.t, this.bulletS, this.bulletD, this.bulletP));
     break;
   }
   this.dx = Math.sin(this.r);
   this.dy = -Math.cos(this.r);
   this.mag = Math.sqrt(this.dx * this.dx + this.dy * this.dy);
   this.velx -= ((this.dx / this.mag) * this.knockback);
   this.vely -= ((this.dy / this.mag) * this.knockback);
   this.reloading = true;
   return;
  }
 }
 if(this.reloading) {
  this.cooldown -= 100;
  this.timetill = millis;
 }
 if(this.cooldown <= 0) {
  this.cooldown = 0;
  this.reloading = false;
 }
 if(this.cooldown !== this.reload && !this.reloading) {
  if(this.cooldown < this.reload) {
   this.cooldown = millis - this.timetill;
  } else {
   this.cooldown = this.reload;
  }
 }
};
this.show = function() {
 c.save();
 c.translate(this.x, this.y);
 c.rotate(this.r);
 c.fillStyle = "rgb(200, 200, 200)";
 c.strokeStyle = "rgb(150, 150, 150)";
 c.fillRect(-9, 0, 18, -45 * (1 - (this.reload - this.cooldown) / 3000));
 c.beginPath();
 c.moveTo(-9, 0);
 c.lineTo(-9, -45 * (1 - (this.reload - this.cooldown) / (this.reload * 8)));
 c.stroke();
 c.beginPath();
 c.moveTo(-9, -45 * (1 - (this.reload - this.cooldown) / (this.reload * 8)));
 c.lineTo(9, -45 * (1 - (this.reload - this.cooldown) / (this.reload * 8)));
 c.stroke();
 c.beginPath();
 c.moveTo(9, 0);
 c.lineTo(9, -45 * (1 - (this.reload - this.cooldown) / (this.reload * 8)));
 c.stroke();
 switch(this.t) {
  case 0:
   c.fillStyle = "rgb(100, 200, 250)";
   c.strokeStyle = "rgb(50, 150, 200)";
   break;
  case 1:
   c.fillStyle = "rgb(250, 150, 150)";
   c.strokeStyle = "rgb(200, 100, 100)";
   break;
  case 2:
   c.fillStyle = "rgb(150, 250, 150)";
   c.strokeStyle = "rgb(100, 200, 100)";
   break;
  case 3:
   c.fillStyle = "rgb(250, 150, 250)";
   c.strokeStyle = "rgb(200, 100, 200)";
   break;
 }
 c.beginPath();
 c.arc(0, 0, 25, 0, 2 * Math.PI);
 c.fill();
 c.stroke();
 c.restore();
};
}
tanks.push(new tank(50, 50, 0, 0, "test", 0, 0, 0, 1));
for(var i = 0; i < 1000 - (shapes.length - 1); i++) {
shapes.push(new shape(Math.round(Math.random() * 6000) - 3000, Math.round(Math.random() * 6000) - 3000, Math.round(Math.random() * 2)));
}

function draw() {
millis = new Date();
millis = millis.getTime();
if(autospin) {
 mousex = (canvas.width / 2) + Math.sin(millis / 1500) * 200;
 mousey = (canvas.height / 2) + Math.cos(millis / 1500) * 200;
}
camx = (canvas.width / 2) - tanks[0].x;
camy = (canvas.height / 2) - tanks[0].y;
c.fillStyle = "rgb(220, 220, 220)";
c.fillRect(0, 0, canvas.width, canvas.height);
c.strokeStyle = "rgb(200, 200, 200)";
c.lineWidth = 1;
for(var i = 0; i < canvas.width / 20; i++) {
 c.beginPath();
 c.moveTo(0, (i * 25) - tanks[0].y % 25);
 c.lineTo(canvas.width, (i * 25) - tanks[0].y % 25);
 c.stroke();
 c.beginPath();
 c.moveTo((i * 25) - tanks[0].x % 25, 0);
 c.lineTo((i * 25) - tanks[0].x % 25, canvas.height);
 c.stroke();
}
c.lineWidth = 3;
c.save();
c.translate(camx, camy);
for(var i = shapes.length - 1; i >= 0; i--) {
 shapes[i].show();
 shapes[i].update();
 for(var j = shapes.length - 1; j >= 0; j--) {
  if(i !== j) {
   if(Math.abs(shapes[i].x - shapes[j].x) < 50 && Math.abs(shapes[i].y - shapes[j].y) < 50) {
    shapes[i].gothit(shapes[j]);
    shapes[j].gothit(shapes[i]);
   }
  }
 }
 for(var j = bullets.length - 1; j >= 0; j--) {
  if(Math.abs(shapes[i].x - bullets[j].x) < 18 + bullets[j].r && Math.abs(shapes[i].y - bullets[j].y) < 18 + bullets[j].r) {
   shapes[i].gothit(bullets[j]);
   bullets[j].p--;
  }
 }
}
for(var i = bullets.length - 1; i >= 0; i--) {
 bullets[i].show();
 bullets[i].update();
 if(bullets[i].p <= 0) {
  bullets.splice(i, 1);
 }
}
for(var i = tanks.length - 1; i >= 0; i--) {
 tanks[i].show();
 tanks[i].update(Math.atan2(-(tanks[i].x - (mousex - camx)), (tanks[i].y - (mousey - camy))));
}
c.restore();
mouseClicked = false;
c.beginPath();
c.arc(mousex, mousey, 5, 0, 2 * Math.PI);
c.fill();
window.requestAnimationFrame(draw);
}
window.requestAnimationFrame(draw);
window.addEventListener("mousemove", function(e) {
if(!autospin) {
 mousex = e.clientX;
 mousey = e.clientY;
}
});
window.addEventListener("mousedown", function() {
mouseIsPressed = true;
});
window.addEventListener("mouseup", function() {
mouseIsPressed = false;
mouseClicked = true;
});
window.addEventListener("keydown", function(e) {
keys[e.keyCode] = true;
});
window.addEventListener("keyup", function(e) {
if(keys[69]) {
 if(!autofire) autofire = true;
 else autofire = false;
}
if(keys[67]) {
 if(!autospin) autospin = true;
 else autospin = false;
}
keys[e.keyCode] = false;
});
```

```

@font-face {
font-family: 'Ubuntu';
src: url("Ubuntu-B.ttf") format('ttf');
}

html, body, canvas, p {

margin: 0;
font-family: "Ubuntu";
padding: 0;
overflow: hidden;

}

```

```
<!DOCTYPE html>
<html>
 <head>
  <title>peip.io</title>
 </head>
 <body>
  <canvas id="canvas" width="800px" height="600px"></canvas>
 </body>
</html>
```

Additional info:

Edit: I halfway figured out the problem, and by logging the collision variables, I found out that they were NaN, so I will experiment further to find out why

# Answer
> 2 votes
It turns out, I was calling `this.xvel` and `this.yvel`, when I defined them as `this.velx` and `this.vely`

# Answer
> 1 votes
Nobody will really read your whole code, but one thing I can tell you is, maybe you should use a physics engine to take care of this for you. Here I will link Box2D for Javascript:

http://box2d-js.sourceforge.net/

There is a little guide there too, but you can find other tutorials! Good luck!

---
Tags: javascript, html-canvas, collision-resolution, css
---


# Question
Title: Getting position of a coordinate on the surface of a sphere
So I want to create a object B close to another object A, but I'm trying to avoid that A covers B:

I have thinking how to achieve that. Take a look of the following drawing:

I have been thinking in a solution in a math - geometry way before searching for some Unity3D function to solve the problem. I have realise A and B would be on the same surface if the camera is within a sphere with radius c-A. So I guess the solution can be related to get a point at a B at a distance A-B from A on the surface of the sphere with radius c-A. Does it has sense? Any other idea? How to do it with maths and Unity?

# Answer
> 1 votes
Well first of all, is the arrow a vector or just your own way of pointing? Particle A minus B doesn't produce what's on the second image. A minus B can mean several things depending on perspective! If A and B are POINTS in space, then subtracting them will give you the distance or displacement between them (scalar or vector). But if instead you view A and B as Velocity vectors, then your experiment changes. For an easy fix, when the object collides with the other, examine the variable 'closestPoint'. Its in there somewhere. No guarantees, but worth a shot.

# Answer
> 0 votes
Create object `B` on the center of the camera

```
Transform B = Instantiate(prefabB, camera.position, Quaternion.Identity);

```

Move it's local position to object `A`

```
B.localPosition = A.position;

```

Rotate object `B` by some angles, this will cause it to rotate around camera, so it will be on the same distance as `A` but in a different angle

```
B.Rotate( new Vector3(0, 30.0f, 0) );

```

This assumes that the circle is on the x-z axis and the perpendicular axis is the y-axis.

---
Tags: unity, geometry, coordinates
---


title: Unity - AudioClip lags when played

text:
# Question
Title: Unity - AudioClip lags when played
My AudioClip is lagging when I play it in Unity3d. The AudioClip is supposed to play when you left-click inside the game window.

Steps I've tried for fixing it:

* Uncompressing the .wav sound file.
* Setting the clip variable of an AudioSource to a clip and then playing the sound, but that's a different story.

How the issue occurs: When I start the game, on the first click it plays fine. But then after a few clicks, it starts slowing down and/or lagging.

This is my code:

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

[RequireComponent(typeof(AudioClip))]
[RequireComponent(typeof(AudioSource))]

public class GameProcess : MonoBehaviour {

    public Canvas Game;
    public AudioClip explosion;
    AudioSource beatBox;
    Transform btn;
    Vector3 canvasMin;
    Vector3 canvasMax;
    Vector3 pointerMin;
    Vector3 pointerMax;
    Vector3 pointerPos;

    void Start () {
        btn = Game.transform.FindChild("Pointer");
        canvasMin = Game.GetComponent<Collider>().bounds.min;
        canvasMax = Game.GetComponent<Collider>().bounds.max;
        pointerMin = btn.GetComponent<Collider>().bounds.min;
        pointerMax = btn.GetComponent<Collider>().bounds.max;
        beatBox = GetComponent<AudioSource>();
    }

    void Update () {
        if (Input.GetMouseButton(0))
        {
            beatBox.PlayOneShot(explosion);
        }
        if (!(pointerMin.x <= canvasMin.x) || !(pointerMin.y <= canvasMin.y))
        {
            if(!(pointerMax.x >= canvasMax.x) || !(pointerMax.y >= canvasMax.y))
            {
                btn.transform.position = Input.mousePosition;
            }else
            {
                btn.transform.position.Set(pointerPos.x - 1, pointerPos.y - 1, 0);
            }
        }else
        {
            btn.transform.position.Set(pointerPos.x + 1, pointerPos.y + 1, 0);
        }
    }
}

```

# Answer
> 2 votes
When you're using the uncompressed WAV file, check the option that says "Preload audio data". This will ensure the sound clip is loaded into RAM and ready to use at a moment's notice instead of being loaded every time (or the first time) it's needed.

Sounds like bullets, explosions etc. should always be loaded into memory. Sounds that have narration or music can be loaded later on for size related reasons.

The original problems seems to be an audio slow-motion effect rather than a lag.

Possible problems that may cause this:

Audio Sources' pitch setting is less than 1 (means slower rate audio).

Doppler Factor of your audio manager is not zero and the object that makes the sound is moving away from the Audio Listener. (Shouldn't be the case since all you do is make sounds on the screen itself so they shouldn't be moving.)

Your sampling rate might be too high and it might have to pick a lower sampling rate in-game (not likely with the current technology but if you have an older system, this may be the case).

# Answer
> 0 votes
Your problem might came from 2 things : Unity adds audio latency and ALSO input latency. Your sound is a result of clicking a button. Audio latency is one thing but input latency also indirectly increase the perceived audio latency. (You can look at my research here : https://github.com/5argon/UnityiOSNativeAudio) Though, I think input latency is noticable only on mobile device.

To fix audio latency : Project Setting \> Audio \> DSP Buffer Size \> set it to Best Latency (small buffer size). As of today with this settings, it make a glitched sound on Windows build while on macOS, Android, iOS is completely fine. You might want to have larger buffer size on Windows. (at the expense of more latency)

If that is not enough you can use native methods of each platform. I just made Native Audio asset store plugins which can make a native call to both iOS and Android's fastest native way from one central interface. https://www.assetstore.unity3d.com/#!/content/107067

There are various ways of playing audio at native side, here's my choice :

* On iOS it uses OpenAL. It is faster than AVAudioPlayer, AudioToolbox, and SystemSound.
* On Android it uses OpenSL ES (C), I confirmed it to be faster than SoundPool and AudioTrack (Java).

I have compiled all of my findings in here : http://exceed7.com/native-audio

PS. I have used FMOD for Unity before. The best settings that I could do. In addition to setting the best file format, requires editing FMOD Unity's source code to use very low number of buffer size. With that still the latency is just about equal to Unity's "Best Latency" (ant the sound cracks more too due to a low buffer size)

To fix input latency : This is much more difficult as the path that Unity receives touch from Xcode project is almost hardwired and is not meant to be replaced easily. (Unlike audio, we just left the Unity one and use our native method)

I made iOS Native Touch which can reduce this input latency. But you will lose many conveniences that Unity provides including finger ID tracking, stationary state, etc.

http://exceed7.com/ios-native-touch/

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


title: How do I get a table of AABB's?

text:
# Question
Title: How do I get a table of AABB's?
**I am not sure if this is the right site to put this question on.**

What would be a good, time saving method to reference an AABB with an integer id in Java programming language?

AABB class:

```
public class AABB {
private EndPoint[] min = new EndPoint[3];
private EndPoint[] max = new EndPoint[3];
private int entityId = 0;
private Boolean isStatic = false;
private static Map<Integer, AABB> table = new HashMap<>();
private Vector3f pos;
private int id = 0;

public AABB(Vector3f min,Vector3f max,Vector3f pos,int entityId,Boolean isStatic) {
    this.min[0] = new EndPoint(true,pos.x - min.x,id);
    this.min[1] = new EndPoint(true,pos.y - min.y,id);
    this.min[2] = new EndPoint(true,pos.z - min.z,id);

    this.max[0] = new EndPoint(false, pos.x + max.x,id);
    this.max[1] = new EndPoint(false,pos.y + max.y,id);
    this.max[2] = new EndPoint(false,pos.z + max.z,id);
    this.pos = pos;
    this.entityId = entityId;
    this.id = UniqueIdentifier.nextInt();
    this.isStatic = isStatic;
}
public static AABB setAABB(AABB aabb) {
    return table.put(Integer.valueOf(aabb.getId()), aabb);
}

public static AABB getAABB(int id) {
    return table.get(Integer.valueOf(id));

}

public static AABB getAABB(EndPoint endpoint) {
    return getAABB(endpoint.getId());

}

@Override
public boolean equals(Object arg0) {
    if(arg0 == this) {
        return true;
    }
    if((arg0 == null) || !(arg0 instanceof AABB)) {
        return false;
    }

    AABB aabb = null;
    try {
        aabb = (AABB) arg0;
    } catch (ClassCastException e) {
        return false;
    }

    return ((aabb.getMax() == getMax()) && (aabb.getMin() == getMin()) && (aabb.isStatic() == isStatic || aabb.isStatic().equals(isStatic())) && (aabb.getPos() == getPos()) && (aabb.getId() == getId()) && (aabb.getEntityId() == getEntityId()));

}

@Override
public int hashCode() {
    int hash = 17;
    hash += 5 * ((Boolean) isStatic).hashCode();
    hash += 5 * ( min == null ? 0 : min.hashCode());
    hash += 5 * ( max == null ? 0 : max.hashCode());
    hash += 5 * ( pos == null ? 0 : pos.hashCode());
    hash += 5 * id;
    hash += 5 * entityId;
    return hash;
}

}

```

SAP class:

```
 public class SAP {
public static List<EndPoint> xaxis = new ArrayList<>();
public static List<EndPoint> yaxis = new ArrayList<>();
public static List<EndPoint> zaxis = new ArrayList<>();
private SAP() {}

public static void addObject(AABB aabb) {
    if(!PairManager.isInPairs(aabb)) {
        xaxis.add(aabb.getMax()[0]);
        xaxis.add(aabb.getMin()[0]);

        yaxis.add(aabb.getMax()[1]);
        yaxis.add(aabb.getMin()[1]);

        zaxis.add(aabb.getMax()[2]);
        zaxis.add(aabb.getMin()[2]);

                    // Where i set table
        AABB.setAABB(aabb);
    }
}

private static boolean  intersects(AABB a,AABB b, int axis)
{
            // Where exeption is thrown a and b == null
    return !(a.getMax()[axis].getValue() < b.getMin()[axis].getValue() || b.getMax()[axis].getValue() < a.getMin()[axis].getValue());
}

private static boolean intersects(AABB a,AABB b) {
    return intersects(a,b,0) && intersects(a,b,1) && intersects(a,b,2);
}

}

```

# Answer
> 0 votes
I think that the cause is that your `EndPoint`s always have the id of zero. Try moving the creation of them after you've assigned the id using `UniqueIdentifier`.

---
Tags: java, aabb
---


# Question
Title: How do you get a license from Marvel comics for game?
I want to use Marvel comics character in my game but I don't know how to get Marvel comics character licence for game

# Answer
> 4 votes
The answer to your question is easily findable via Google:

https://www.disneystudiolicensing.com/who-do-i-contact-to-license-content-from-marvel-films/

> Marvel Studios manages the rights to all Marvel Studios produced films only. Iron Man 2008 thru the present slate of films. Request must be sent in writing only to: edenton@marvelstudios.com
>
> Who do I contact to request permission to use Marvel intellectual property for commercial and non-commercial use (including comic books, animated television shows and how to become a licensee). All requests must be submitted in writing to: permissions@marvel.com
>
> Due to the high volume of requests, it can take several weeks for a response.

However as a game developer of many years, I can tell you now that you are unlikely to get permission without a well established publisher backing you, or proof of an extensive track record delivering high quality games.

My advice would be to revisit your game idea and consider if it would still be fun / interesting / saleable if you replaced all of the Marvel characters you wish to license with original characters that you have developed yourself.

---
Tags: licensing
---


title: SAP method freezes

text:
# Question
Title: SAP method freezes
When I run this method in game the code freezes.

Here are the methods:

```
public static void sort(List<EndPoint> axis,int ax) {
    for(int j = 1; j < axis.size();j++) {
        EndPoint keyelement = axis.get(j);
        float key = keyelement.getValue();

        int i = j - 1;

        while(i >= 0 && axis.get(i).getValue() > key) {
            EndPoint swapper = axis.get(i);

            //TODO check bounding boxes
            AABB aabb = AABB.getAABB(swapper);
            AABB aabb1 = AABB.getAABB(keyelement);
            if(intersects(AABB.getAABB(swapper), AABB.getAABB(keyelement),ax)) {
                if(intersects(aabb,aabb1)){
                    System.out.println("Collision "+ aabb + " : " + aabb1);
                    PairManager.addPair(aabb, aabb1);
                }
            }

            axis.add(i + 1, swapper);
            i--;
        }
        axis.add(i + 1, keyelement);

    }
}

public static void updateObjects() {
    sort(xaxis,0);
    sort(yaxis,1);
    sort(zaxis,2);
}

```

# Answer
Everytime you get to the end of this loop:

`for(int j = 1; j < axis.size();j++) {`

you add to the axis:

`axis.add(i + 1, keyelement);`

I didn't see any place that you ever remove elements from `axis`. Since it gains at least one element on every iteration & are iterating one element at a time, you can't ever process all of the elements.

As suggested by @Wondra - you should add some break points to the code, run the debugger & step through the lines one at a time to see how the execution of your code does & does not match what your intent.
> 2 votes

# Answer
My suggestion to you is to place break points in your code to determine what is making your application freeze, I do however, get the feeling that you might be iterating through your loop incorrectly. Without further information I can't really say much else.
> 1 votes

---
Tags: java, collision-detection, aabb
---


# Question
Title: When I start running, it won't stop when I let go of shift. Why?
Following is my code, and after I let go of shift the image speed goes back to normal but not the variable I created called `movespeed`. What should I add or change to fix it?

```
//Run with left shift
if (keyboard_check(vk_lshift))
{
     movespeed = 5;
     image_speed = 0.14;
}

```

# Answer
The reason your image won't stop moving is because you need to reset the speed variable, like so:

```
if(keyboard_check_released(vk_lshift))
{
    movespeed = 0;
}

```

Or, you could just put the `movespeed` variable in the bottom of the step event, after all relevant movement code has been calculated.

**EDIT**

One other solution is do something like this:

```
//Run with left shift
if (keyboard_check(vk_lshift))
{
    movespeed = 5;
    image_speed = 0.14;
}
else
{
    // We only come here if the key is not determined to be down
    movespeed = 0;
    image_speed = 0;
}

```

All 3 options will virtually give the same result.
> 0 votes

---
Tags: game-maker
---


title: Ugly Textures in the Distance

text:
# Question
Title: Ugly Textures in the Distance
I'm here with another question about direct 3d 11 (sharpdx). My terrain engine is working good, but theres a problem with texture mip maps or filter which I can't figure out :/

The problem is basic. Near, the textures look OK:

Far away they're kinda ugly?

Loading it:

```
 internal Texture2D CreateTexture2DFromBitmap(BitmapSource bitmapSource)
       {
            int Byte = bitmapSource.Size.Width * 4;
            using (var buffer = new DataStream(bitmapSource.Size.Height * Byte, true, true))
            {
                bitmapSource.CopyPixels(Byte, buffer);
                var tex = new Texture2D(device, new Texture2DDescription()
                {
                    Width = bitmapSource.Size.Width,
                    Height = bitmapSource.Size.Height,
                    ArraySize = 1,
                    BindFlags = BindFlags.RenderTarget | BindFlags.ShaderResource,
                    Usage = ResourceUsage.Default,
                    CpuAccessFlags = CpuAccessFlags.None,
                    Format = SharpDX.DXGI.Format.R8G8B8A8_UNorm_SRgb,
                    MipLevels = 1,
                    OptionFlags = SharpDX.Direct3D11.ResourceOptionFlags.Shared,
                    SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0)
                },
                new DataRectangle(buffer.DataPointer, Byte));
                return tex;
            }
       }

```

Rendering it:

```
 public override void Create(long assetID, Importeur content, DeviceContext context)
        {
            try
            {
                _diffuseTexture = content.LoadTexture(assetID, TextureType.DiffuseMap);
                context.GenerateMips(_diffuseTexture.MapView);
                context.PixelShader.SetShaderResource(0, _diffuseTexture.MapView);
            }

            catch (Exception e)
            {
                throw e;
            }
        }

```

Filter:

```
var samplerStateDescription = new SamplerStateDescription
            {
                AddressU = TextureAddressMode.Wrap,
                AddressV = TextureAddressMode.Wrap,
                AddressW = TextureAddressMode.Wrap,
                Filter = Filter.Anisotropic,
                MaximumLod = float.MaxValue,
                MinimumLod = 0
            };

```

Finally got it working, the problem was a thread block code line from my engine.

Thanks for helping!

# Answer
**ID3D11DeviceContext::GenerateMips method**

> If the base resource wasn't created with D3D11\_BIND\_RENDER\_TARGET, D3D11\_BIND\_SHADER\_RESOURCE, and D3D11\_RESOURCE\_MISC\_GENERATE\_MIPS, the call to GenerateMips has no effect.

However, if we also look at the documentation for the D3D11\_RESOURCE\_MISC\_FLAG enumeration we see the following remark:

> **D3D11\_RESOURCE\_MISC\_SHARED**
> Enables resource data sharing between two or more Direct3D devices. **The only resources that can be shared are 2D non-mipmapped textures**.

So you basically have two problems:

1. You're not setting D3D11\_RESOURCE\_MISC\_GENERATE\_MIPS, so you can't use GenerateMips, but,
2. You are setting D3D11\_RESOURCE\_MISC\_SHARED which is illegal to use with mipmapped textures.

To resolve, and assuming that you don't actually need D3D11\_RESOURCE\_MISC\_SHARED (it's not clear why you're setting it), you need to replace this:

```
OptionFlags = SharpDX.Direct3D11.ResourceOptionFlags.Shared

```

With the SharpDX equivalent of D3D11\_RESOURCE\_MISC\_GENERATE\_MIPS; probably something like this:

```
OptionFlags = SharpDX.Direct3D11.ResourceOptionFlags.GenerateMips

```

(Unfortunately the SharpDX documentation is a bit lacking in this regard, but you should be able to figure it out.)

If however you do need D3D11\_RESOURCE\_MISC\_SHARED then you're out of luck.
> 1 votes

---
Tags: c#, shaders, textures, directx11, sharpdx
---


# Question
Title: How to convert game object world position to hex grid cell coordinates?
I have a hex grid and a game object, let's say it's the player. What I want to do is know on which cell the player is on based on his world position, this would be easy on a simple grid but on a hex grid it's giving me a headache.

# Answer
Maybe this useful and complete article may help you : https://www.redblobgames.com/grids/hexagons/

There's 4 different possibilities for implementing an hexagrid. Depending on your "offset coordinates". For each type the article explains how you can convert position to hex coordinate.

And good luck, I had to implement such system too before this article ever existed ^^
> 2 votes

---
Tags: unity, hexagonal-grid
---


title: Why is my image speed not changing?

text:
# Question
Title: Why is my image speed not changing?
Following is my code for my platformer. However, in the `//Run with left shift//` section when I made the image speed change, the speed is still the same and doesn't change so is there any piece of code that is preventing this task?

```
///Get player's input
key_right = keyboard_check(vk_right);
key_left = -keyboard_check(vk_left);
key_jump = keyboard_check_pressed(vk_space);
key_jump_held = keyboard_check(vk_space);
key_shoot = keyboard_check(ord("D"));

//React to inputs
move = key_left + key_right;
hsp = move * movespeed;
if (vsp < 10) vsp += grav;

if (place_meeting(x, y+1, Obj_Floor))
{
 vsp = key_jump * -jumpspeed;
}

if (vsp < 0) && (!key_jump_held) vsp = max(vsp,0)

//Run with left shift
if (keyboard_check(vk_lshift))
{
 movespeed = 5;
 image_speed = 0.14;
}

if (keyboard_check_released(vk_lshift))
{
 movespeed = 3;
 image_speed = 0.025;
}

//Shooting direction
if (keyboard_check(vk_right))
{
 mpfacing = 0;
}

if (keyboard_check(vk_left))
{
 mpfacing = 180;
}

//Shooting
if (keyboard_check(ord("D"))) && (canshoot = true)
{
 instance_create(x+13, y-0.5, Obj_MP_Laser);
 canshoot = false;
 alarm[1] = 30;
}

//Horizontal Collision
if (place_meeting(x+hsp, y, Obj_Floor))
{
 while(!place_meeting(x+sign(hsp), y, Obj_Floor))
 {
  x += sign(hsp);
 }
 hsp = 0;
}
x += hsp;

//Vertical Collision
if (place_meeting(x, y+vsp, Obj_Floor))
{
 while(!place_meeting(x, y+sign(vsp), Obj_Floor))
 {
  y += sign(vsp);
 }
 vsp = 0;
}
y += vsp;

//Animate
if (move != 0)
{
 image_xscale = move;
}

if (place_meeting(x, y+1, Obj_Floor))
{

 if (move != 0)
 {
  sprite_index = CalvinWalking;
  image_speed = 0.05;
 }

 else
 {
  sprite_index = CalvinStanding;
  image_speed = 0.025;
 }
}

else
{
 if (vsp < 0) sprite_index = CalvinJumping
 else sprite_index = CalvinJumping
}

```

# Answer
The issue with your code seems to be here:

```
 if (move != 0)
 {
      sprite_index = CalvinWalking;
      image_speed = 0.05;
 }

 else
 {
      sprite_index = CalvinStanding;
      image_speed = 0.025;
 }

```

Right now you're saying this:

```
if player is pressing left or right:
    set sprite_index = CalvinWalking
    set image_speed = 0.05
otherwise if player is not pressing left or right:
    set sprite_index = CalvinStanding
    set image_speed = 0.025

```

Every frame you're checking whether or not the player is pressing the `left` or `right` key, and if they aren't to adjust the speed. Because you do this after you check if the player is pressing the `shift` key, the players speed never increases.

A few things to note:

1. I'm fairly certain that GM compiles code much like C++, in that it compiles line by line (don't quote me on this)
2. When organising code, you should generally try to isolate things; for example, you're managing collision detection, player input, shooting **and** animations, you should try to isolate these things into separate scripts, this way you can easily turn things on and off and will determine what the issue is.
> 1 votes

---
Tags: movement, game-maker
---


# Question
Title: How can I make car respawn with temporary invulnerability i.e. no collisions?
I'm using Unity's standard assets scripts to move my car, but the camera just follows the road.

At certain moments when the car misses or overturns the player can press 'R' to reposition the car in the middle of the road in the position where I miss or turn over.

When the car respawns, it should not collide with other cars in the race, for a few seconds. After those few seconds everything returns to normal.

I thought about using layers, but I did not find how to modify the "Layer Collision Matrix" dynamically from a script. How do I do that?

# Answer
> 2 votes
Thanks to DMGregory!!

I Change the layer, I make that layer 10 and 9 not collision, but if the 10 collides with itself:

```
void Update () {
    delay -= Time.deltaTime;

    if (Input.GetKeyDown(KeyCode.R))
        Respawn();

    if (delay <= 0)
        gameObject.layer = 10;
}

private void Respawn()
{
    transform.position = new Vector3(OriginalPosition.x, OriginalPosition.y, transform.position.z-2);
    transform.rotation = OriginalRotation;
    if (rbCar != null)
    {
        rbCar.velocity = Vector3.zero;
        rbCar.angularVelocity = Vector3.zero;
    }
    delay = 5;
    gameObject.layer = 9;
}

```

# Answer
> 0 votes
While the OP has already found a solution I figured I would give my input.

Yes, changing the game objects layer is one way of stopping the car from colliding with other objects, however, another way you could do this is by setting the Rigidbody.isKinematic property to false for the duration you wish the object to not detect & resolve collisions.

Of course this will stop the car from reacting to any physics, which in this case, the OP would more than likely want the user to be able to continue driving the car when it is re-spawned, but I just figured it would be worth the mention.

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


# Question
Title: Pull OVRCameraRig over RTS map via touch controller grabbing gesture
Currently developing a little prototype RTS with the Oculus VR devkit. I want to implement camera movement via "grabbing" onto the world space with a touch controller and move the OVRCameraRig object on the X- and Z-axes. For the prototype purpose, I rather decided to go with a simpler approach, namely just pull the map around, since it's not that big, and not much is happening on it.

So far I got this script:

```
public class MapMover : MonoBehaviour
{
    private bool movementEnabled;

    Transform map;
    Transform leftController;
    Vector3 offset;

    public bool IsMovementEnabled { get { return movementEnabled; } }

    private void Awake()
    {
        leftController = GameObject.Find("LeftHandAnchor").transform;
    }

    public void BeginMovement()
    {
        offset = transform.position - leftController.position;
        movementEnabled = true;
    }

    public void EndMovement()
    {
        movementEnabled = false;
    }

    private void LateUpdate()
    {
        if (movementEnabled)
        {
            transform.position = new Vector3(
                (leftController.position.x * 1.1f + offset.x),
                transform.position.y,
                (leftController.position.z * 1.1f + offset.z)
            );
        }
    }
}

```

`BeginMovement()` is called when I press the Hand Trigger on the left Touch controller. My current results are unproductive: The first `BeginMovement()` call is sufficient, but the movement of the map is very minimal, since the controller models are tiny and their position clamps around `-1.0f` and `1.0f`. The second call of `BeginMovement()` makes the map do a jump to either side before going back to the minimal movement.

My question is, what exactly am I missing? Is there a simpler approach to this?

# Answer
> 0 votes
I have changed my approach to the problem and came up with a basic solution that supports my needs:

```
public class MapMover : MonoBehaviour
{
    private bool movementEnabled;
    private float factor = 45.0f;

    Transform leftController;

    Vector3 lastControllerPosition;
    Vector3 currentControllerPosition;

    private void Awake()
    {
        leftController = GameObject.Find("LeftHandAnchor").transform;
        currentControllerPosition = leftController.transform.position;
    }

    public void BeginMovement() { movementEnabled = true; }

    public void EndMovement() { movementEnabled = false; }

    private void Update()
    {
        lastControllerPosition = currentControllerPosition;
        currentControllerPosition = leftController.transform.position;
    }

    private void LateUpdate()
    {
        if (movementEnabled) {
            Vector3 distance = currentControllerPosition - lastControllerPosition;
            transform.Translate(distance.x * factor, 0, distance.z * factor);
        }
    }
}

```

Basic function explained:

The script is a component of the map object and is initialized with the current position of the left controller's `transform.position`. Each frame, this value is moved to the last position, while the current position is retrieved anew. During the `LateUpdate()`, upon meeting the condition of being moved, the difference between current and last position is calculated, and the map object is translated by the result's X- and Z-values multiplied by a factor (after extensive testing, a factor of `45.0f` seems comfortable for moving around, but you should definitely test it out to meet your needs).

I hope this will help someone.

---
Tags: unity, c#, camera, virtual-reality, oculus
---


# Question
Title: Why does SDL2 blur pixel art even with SDL_HINT_RENDER_SCALE_QUALITY set to 0?
I am working on a game with SDL2 and having trouble turning off linear filtering when upscaling textures.

My game has a bunch of 32x32 tiles. I used `SDL_RenderSetLogicalSize` so that there is a one-to-one pixel mapping (i.e. my logical size is `n * 32` x `m * 32`.)

However, when the the whole scene is upscaled to fit the actual screen, it seems to be interpolated (blurry).

I saw these two other posts (, ) which recommended using `SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "0");`. I did that, but nothing seems to change at all. It returns `true` and it is in fact changing the hint, but the rendering just doesn't change at all. I even tried setting it with priority but nothing changes.

Any idea how to fix this? I am on Windows if that's relavent.

# Answer
> 6 votes
`SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "0");` needs to happen before texture *creation*.

This is because interpolation mode is a property of created textures, not the rendering pipeline.

---
Tags: sdl, sdl2
---


# Question
Title: Enemy fire does not travel to player using RayCast2D
Enemies are using raycast to fire and detect player. The bullet has its own script that makes it move forward after instantiating it, but the problem is that it always moves in the right direction and does not take into account the rotation of the enemy.

Here is my enemy fire script

```
public class EnemyFire : MonoBehaviour {

    public GameObject ustaazPlayer;
    public GameObject enemyLaser;
    float timeToSpawnEffect = 0;
    public float effectSpawnRate = 4;
    public int damage;

    // Use this for initialization
    void Start () {
        InvokeRepeating("EnemyShoot", 0.00001f, effectSpawnRate);
    }

    void EnemyShoot()
    {
        Vector2 playerPosition = new Vector2(ustaazPlayer.transform.position.x, ustaazPlayer.transform.position.y);  //position of player
        Vector2 bossPosition = new Vector2(transform.position.x, transform.position.y); //enemy location
        RaycastHit2D hit = Physics2D.Raycast(bossPosition, playerPosition - bossPosition, 100);

        //if (Time.time >= timeToSpawnEffect)
        //{
            Instantiate(enemyLaser, transform.position, transform.rotation);
            AudioManager.instance.PlaySound("enemyLaser");
        //    timeToSpawnEffect = Time.time + 1 / effectSpawnRate;
        //}
        Debug.DrawLine(bossPosition, (playerPosition - bossPosition) * 100, Color.cyan);
        if (hit.collider != null)
        {
            Debug.DrawLine(bossPosition, hit.point, Color.red);
            //Debug.Log("We hit " + hit.collider.name + " and did " + damage + " damage.");
            Player player = hit.collider.GetComponent<Player>();
            if (player != null)
            {
                player.DamagePlayer(damage);
            }
        }
    }
}

```

and here is the script on the laser object

```
public class MoveBulletTrail : MonoBehaviour {

    public int speed = 200;

    // Update is called once per frame
    void Update () {
        transform.Translate(Vector3.right * Time.deltaTime * speed); //move it forward in the direction it was spawned
        Destroy(gameObject, 1); //destroy the trail after 1 second so that inspector does not get bogged down in them - so much easier than having a shredder!
    }
}

```

How would I make it shoot towards the player?

# Answer
In order to make the bullet follow the player, you can use this:

```
public class MoveBulletTrail : MonoBehaviour {

    public int speed = 200;
    Transform target; // What the bullet is following

    // Function to call to tell the bullet what to follow
    // You can call it like "SetTarget(player.transform);"
    public void SetTarget(Transform t) {
        target = t;
    }

    // Update should make the bullet go closer to the target
    void Update () {

        // Make bullet look at target
        transform.LookAt(target.position);

        // Make bullet go slightly towards target
        // Please note this is in 3D, if you want to use it in 2D
        // Change speed to either the X axis or Y axis
        transform.Translate(0, 0, speed);

        // Optionally check if the bullet reached target
        // This example assumes that if bullet is closer than 0.1f units
        // it means it reached the target, feel free to lower that number to suit your needs
        if ((target.position -transform.position).magnitude < 0.1f) {
            // Bullet reached target, destroy it and probably do something else?
            Destroy(gameObject);
            target.DamagePlayer(); // or whatever
        }
}

```

Basically the idea is that for every bullet, you give them a target to follow. Every frame, the bullet looks towards the target, then moves forward to where it's looking. Once the bullet's distance with the target is small enough, it means they are touching.

Optionally, you can give the player a `Collider` so that it detects itself when collision happen, but that's another story.
> 1 votes

---
Tags: unity, 2d, raycasting
---


# Question
Title: FindWithTag returning a game object from "Preview Scene". What is that and why is it not detecting from the active scene?
I have a script that fetches a transform using `GameObject.FindWithTag("Tag").GetComponent<Transform>();`. This has worked fine for a long time, but now it retrieves a transform from a preview scene(whatever that is). How do I prevent it from looking at preview scene?

# Answer
> 1 votes
Apparently it's a bug, to make that Preview Scene go away you need to close and restart Unity.

For some users though it's not even working that close/restart trick.

# Answer
> 1 votes
I had just ran into this bug really recently, and when closing/restarting Unity doesn't work for me, I do these following things (assuming Windows, and with Unity closed):

1. Open 'Run...' and type in "%APPDATA%" (without the quotes)
    * this will open you into the Roaming folder.
    * delete the Unity folder within
2. Navigate up one folder, and you'll see Local, and LocalLow, along with Roaming.
    * Enter each of the folders, and delete Unity from within them.

Afterwards, re-open Unity and your 'ghost tag gameObjects' should be gone. I plan on submitting a bug report to Unity, and referencing this post.

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


title: How can I load a texture from VBO?

text:
# Question
Title: How can I load a texture from VBO?
I already have the *.png* file in my project, and the *.png* file has the "Embedded Resource" and "Do not copy" settings.

The game runs fine - nothing throws an error, but the game does not show anything.

What did I forget, how can I load the *.png* from the VBO?

Here is my code:

```
using System;
using OpenTK;
using OpenTK.Input;
using OpenTK.Graphics;
using OpenTK.Graphics.OpenGL4;
using System.Drawing;
using System.Reflection;

namespace Tutorial_05
{
    class Game : GameWindow
    {
        private static int WIDTH = 1200;
        private static int HEIGHT = 720;
        private static KeyboardState keyState;

        private int vaoID;
        private int vboID;
        private int iboID;

        private Vector3[] vertices =
        {
            new Vector3(-0.5f, 0.5f, 0.0f), // V0
            new Vector3(-0.5f, -0.5f, 0.0f), // V1
            new Vector3(0.5f, -0.5f, 0.0f), // V2
            new Vector3(0.5f, 0.5f, 0.0f) // V3
        };

        private Vector2[] texcoords =
        {
            new Vector2(0, 0),
            new Vector2(0, 1),
            new Vector2(1, 1),
            new Vector2(1, 0)
        };

        private int[] indices = {
            0, 1, 3,
            3, 1, 2
        };

        private string vertsrc =
            @"#version 450 core

            in vec3 position;
            in vec2 textureCoords;

            out vec2 pass_textureCoords;

            void main(void)
            {
                gl_Position = vec4(position, 1.0);
                pass_textureCoords = textureCoords;
            }";

        private string fragsrc =
            @"#version 450 core

            in vec2 pass_textureCoords;

            out vec4 out_color;

            uniform sampler2D textureSampler;

            void main(void)
            {
                out_color = texture(textureSampler, pass_textureCoords);
            }";

        private int programID;
        private int vertexShaderID;
        private int fragmentShaderID;

        private int textureID;
        private Bitmap texsrc;

        public Game() : base(WIDTH, HEIGHT, GraphicsMode.Default, "Tutorial 05 - Texturing", GameWindowFlags.Default, DisplayDevice.Default, 4, 5, GraphicsContextFlags.Default)
        {
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            CursorVisible = true;

            GL.GenVertexArrays(1, out vaoID);
            GL.BindVertexArray(vaoID);

            GL.GenBuffers(1, out vboID);
            GL.BindBuffer(BufferTarget.ArrayBuffer, vboID);
            GL.BufferData(BufferTarget.ArrayBuffer, (IntPtr)(vertices.Length * Vector3.SizeInBytes), vertices, BufferUsageHint.StaticDraw);

            GL.GenBuffers(1, out iboID);
            GL.BindBuffer(BufferTarget.ElementArrayBuffer, iboID);
            GL.BufferData(BufferTarget.ElementArrayBuffer, (IntPtr)(indices.Length * sizeof(int)), indices, BufferUsageHint.StaticDraw);

            vertexShaderID = GL.CreateShader(ShaderType.VertexShader);
            GL.ShaderSource(vertexShaderID, vertsrc);
            GL.CompileShader(vertexShaderID);

            fragmentShaderID = GL.CreateShader(ShaderType.FragmentShader);
            GL.ShaderSource(fragmentShaderID, fragsrc);
            GL.CompileShader(fragmentShaderID);

            programID = GL.CreateProgram();
            GL.AttachShader(programID, vertexShaderID);
            GL.AttachShader(programID, fragmentShaderID);
            GL.LinkProgram(programID);

            // Loading texture from embedded resource
            texsrc = new Bitmap(Assembly.GetEntryAssembly().GetManifestResourceStream("Tutorial_05.example.png"));
            textureID = GL.GenTexture();

            GL.BindTexture(TextureTarget.Texture2D, textureID);

            GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)All.Linear);
            GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)All.Linear);

            GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba, texsrc.Width, texsrc.Height, 0, PixelFormat.Bgra, PixelType.UnsignedByte, IntPtr.Zero);

            System.Drawing.Imaging.BitmapData bitmap_data = texsrc.LockBits(new Rectangle(0, 0, texsrc.Width, texsrc.Height), System.Drawing.Imaging.ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppRgb);

            GL.TexSubImage2D(TextureTarget.Texture2D, 0, 0, 0, texsrc.Width, texsrc.Height, PixelFormat.Bgra, PixelType.UnsignedByte, bitmap_data.Scan0);

            texsrc.UnlockBits(bitmap_data);

            GL.Enable(EnableCap.Texture2D);
            GL.BufferData(BufferTarget.TextureBuffer, (IntPtr)(texcoords.Length * Vector2.SizeInBytes), texcoords, BufferUsageHint.StaticDraw);

            GL.BindAttribLocation(programID, 0, "position");
            GL.BindAttribLocation(programID, 1, "textureCoords");
        }

        protected override void OnResize(EventArgs e)
        {
            base.OnResize(e);
            GL.Viewport(0, 0, ClientRectangle.Width, ClientRectangle.Height);
        }

        protected override void OnUpdateFrame(FrameEventArgs e)
        {
            base.OnUpdateFrame(e);
            keyState = Keyboard.GetState();
            if (keyState.IsKeyDown(Key.Escape))
            {
                Exit();
            }
        }

        protected override void OnRenderFrame(FrameEventArgs e)
        {
            base.OnRenderFrame(e);
            // Prepare for background
            GL.Clear(ClearBufferMask.ColorBufferBit);
            GL.ClearColor(Color4.Red);

            // Draw traingles
            GL.EnableVertexAttribArray(0);
            GL.EnableVertexAttribArray(1);
            GL.BindVertexArray(vaoID);
            GL.UseProgram(programID);
            GL.BindBuffer(BufferTarget.ArrayBuffer, vboID);
            GL.VertexAttribPointer(0, 3, VertexAttribPointerType.Float, false, 0, IntPtr.Zero);
            GL.ActiveTexture(TextureUnit.Texture0);
            GL.BindTexture(TextureTarget.Texture3D, textureID);

            GL.BindBuffer(BufferTarget.ElementArrayBuffer, iboID);
            GL.DrawElements(BeginMode.Triangles, indices.Length, DrawElementsType.UnsignedInt, 0);
            GL.DisableVertexAttribArray(0);
            GL.DisableVertexAttribArray(1);

            SwapBuffers();
        }

        protected override void OnClosed(EventArgs e)
        {
            base.OnClosed(e);

            GL.DeleteVertexArray(vaoID);
            GL.DeleteBuffer(vboID);
        }
    }
}

```

# Answer
> 0 votes
I think it may be because you're binding a `Texture3D` and not a `Texture2D` in the `OnRenderFrame` method.

Also, you should probably be binding the location of your texture sampler like you are the position and texture coordinate attributes as with some drivers this is a requirement.

Finally, there is no need to call `glEnable(GL_TEXTURE_2D)` as it's not required with the introduction of the programmable pipeline (3.0+, I believe).

---
Tags: c#, opentk
---


title: Model texture flipped?

text:
# Question
Title: Model texture flipped?
Im making a custom Wavefront .obj loader and the images loads but the texture is flipped. What is the problem? here is code and a image.

```
std::vector<UINT> vertexIndices, uvIndices, normalIndices;
std::vector<UINT> indices(4119);
std::vector< XMFLOAT3> temp_vertices;
std::vector< XMFLOAT2 > temp_uvs;
std::vector< XMFLOAT3 > temp_normals;
std::vector< XMFLOAT3> out_vertices;
std::vector< XMFLOAT3> out_normals;
std::vector< XMFLOAT2> out_uvs;
std::vector<Vertex::Basic32> vertices( 4119);
const char *path = "C:\\Users\\terry\\Desktop\\untitled.txt";

FILE * file = fopen(path, "r");
if( file == NULL ){
    printf("Impossible to open the file !\n");
    return;
}

while( 1 ){

    char lineHeader[128];
    // read the first word of the line
    int res = fscanf(file, "%s", lineHeader);
    if (res == EOF)
        break; // EOF = End Of File. Quit the loop.

    // else : parse lineHeader

    if ( strcmp( lineHeader, "v" ) == 0 ){
    XMFLOAT3 vertex;
    fscanf(file, "%f %f %f\n", &vertex.x, &vertex.y, &vertex.z );
    temp_vertices.push_back(vertex);
    }else if ( strcmp( lineHeader, "vt" ) == 0 ){
    XMFLOAT2 uv;
    fscanf(file, "%f %f\n", &uv.x, &uv.y );
    temp_uvs.push_back(uv);
    }else if ( strcmp( lineHeader, "vn" ) == 0 ){
    XMFLOAT3 normal;
    fscanf(file, "%f %f %f\n", &normal.x, &normal.y, &normal.z );
    temp_normals.push_back(normal);
    }else if ( strcmp( lineHeader, "f" ) == 0 ){
    std::string vertex1, vertex2, vertex3;
    unsigned int vertexIndex[3], uvIndex[3], normalIndex[3];
    int matches = fscanf(file, "%d/%d/%d %d/%d/%d %d/%d/%d\n", &vertexIndex[0], &uvIndex[0], &normalIndex[0], &vertexIndex[1], &uvIndex[1], &normalIndex[1], &vertexIndex[2], &uvIndex[2], &normalIndex[2] );
    if (matches != 9){
        printf("File can't be read by our simple parser : ( Try exporting with other options\n");
        return;
    }
    vertexIndices.push_back(vertexIndex[0]);
    vertexIndices.push_back(vertexIndex[1]);
    vertexIndices.push_back(vertexIndex[2]);
    uvIndices    .push_back(uvIndex[0]);
    uvIndices    .push_back(uvIndex[1]);
    uvIndices    .push_back(uvIndex[2]);
    normalIndices.push_back(normalIndex[0]);
    normalIndices.push_back(normalIndex[1]);
    normalIndices.push_back(normalIndex[2]);
    }
}

 for( unsigned int i=0; i<4119; i++ ){
     unsigned int vertexIndex = vertexIndices[i];
     XMFLOAT3 vertex = temp_vertices[ vertexIndex-1 ];
     out_vertices.push_back(vertex);
     unsigned int normalIndex = normalIndices[i];
     XMFLOAT3 normal = temp_normals[ normalIndex-1 ];
     out_normals.push_back(normal);
     unsigned int uvIndex = uvIndices[i];
     XMFLOAT2 uv = temp_uvs[ uvIndex-1 ];
     out_uvs.push_back(uv);

 }

 for( unsigned int i=0; i<4119; i++ ){
     vertices[i].Pos = out_vertices[i];
     vertices[i].Normal = out_normals[i];
     vertices[i].Tex = out_uvs[i];
     vertices[i].Tex.y = vertices[i].Tex.y * -1.0f;
     indices[i] = i;
 }

```

# Answer
> 0 votes
I'm pretty sure Direct 3D flips the textures Y coordinates for you, so you don't need to do it yourself.

---
Tags: models
---


# Question
Title: How to get Entitas components from gameObject.getEntityLink()
I'm new to Entitas. I have a `DamageSystem` that should `Physics.Raycast()` toward the target and if tag is enemy it should reduce enemy health.

I have `HealthComponent`:

```
public class HealthComponent: IComponent{

public float value;

}

```

In `DamageSystem` I wanna do something like:

```
if(Physics.Raycast(target, direction, out hit)){

     tag.gameObject.entity.health.value = currentHealth - damage ;

}

```

But after `Physics.Raycast()`, I have only the `gameObject` and `getEntityLink()` method that return `EntityLink` without actual components... I guess that `getEntityLink()` returns only abstract components, and there is no way to get `HealthComponent` from `EntityLink`?

Does someone know how to get components from `EntityLink`, in a clean manner? Thanks!

# Answer
Here is the answer

```
  if(Physics.Raycast(target, direction, out hit)){

        var target = hit.transform.gameObject.GetEntityLink().entity;

            HealthComponent component = ((HealthComponent)target.GetComponent(GameComponentsLookup.Health));
             //reduce health
            component.value -= weapon.weaponDamage;

            target.ReplaceComponent(GameComponentsLookup.Health, component);

    }

```

Thanks!
> 0 votes

# Answer
First of all, You can read about Physics.Raycast Here. Second of all, You need to store the data that the Physics.Raycast outputs.

I will keep it really simple but you should use layermasks with Raycast to avoid hitting colliders and triggers that can stop the raycast from hitting the target.

How layers work can be found Here. More about Layermasks you can read Here.

So the code should look something like this:

```
void Shoot(int damage) //Function that shoots raycast
{
  RaycastHit hit; //variable to store raycast data
  Enemy enemy; //Enemy component that will be stored and used

  if(Physics.Raycast(transform.position, transform.forward, out hit)) //We shoot the ray
  {
    if(hit.collider.tag == "Enemy") //We check if what we hit has an Enemy Tag
       enemy = hit.collider.gameObject.GetComponent<Enemy>(); //We store that component to use later.

    if(enemy != null) //We check if the component is existing and not empty
       enemy.TakeDamage(damage); //We apply damage based on value the function input damage
  }
}

```

As for the health system there should be a function that takes the damage.

```
private int _health = 100; //Private variable so it won't be changed from outside the script

public void TakeDamage(int damage) //A simple function to apply damage, its public so other scripts can access it and use it to damage the health system
{
  _health -= damage; //We apply the damage that was given to the function.
}

```
> -1 votes

---
Tags: unity, entity-system, entity-component
---


# Question
Title: How to get access to framebuffer as a uint32_t * in SDL2?
I am making my first foray into SDL. To do this, I would like to have direct access to the framebuffer on the window as a `uint32_t *`. This is because I have to pass this framebuffer to another file that my friend wrote which only accepts raw framebuffers like this one. I know that to write pixels you have to set up an `SDL_Renderer` but here I want direct access to the raw framebuffer. How would I do this using only SDL2?

# Answer
This is actually covered in the migration guide from SDL1 to SDL2.

First, you'll need a texture that holds your framebuffer: `SDL_Texture* framebuffer = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_ARGB8888, SDL_TEXTUREACCESS_STREAMING, width, height);`

The important bit here is the `SDL_TEXTUREACCESS_STREAMING` flag. This texture can be quickly changed to point to a different array of pixels. Also make sure you use the correct format flag.

Now you need to manually construct a buffer of pixels: `uint32_t* pixels = new uint32_t[width*height];`. This is the buffer that you can now freely modify and pass around.

Then, when you want to render the pixels in the buffer, all you have to do is to update the texture with the pixel buffer, and render the texture using the renderer to the screen.

```
SDL_UpdateTexture(framebuffer , NULL, pixels, width * sizeof (uint32_t));

SDL_RenderClear(renderer);
SDL_RenderCopy(renderer, framebuffer , NULL, NULL);
SDL_RenderPresent(renderer);

```

Note that this code is untested but it should give you an idea of how to approach this. Implementation details are exactly that, implementation details.
> 3 votes

---
Tags: sdl2, frame-buffer
---


# Question
Title: What are the consequences of adding a progress stat to a live Steam achievement?
Say I have an achievement in my game, "Collect your first thingamajig", and I publish this to the live version of the game without a progress stat. Later on I decide I want to add some new achievements in an update, including one based on the previous achievement: "Collect 10 thingamajigs".

I create a progress stat for this one which is updated in code, but I also edit the original achievement so that it's unlocked through the progress stat rather than an AwardFirstThingamajigAchievement() function in code.

What are the consequences of this? Will a player that already had this unlocked find the achievement has been relocked because the achievement has been edited, technically making it a new one? Will it remain unlocked, but still cause a little popup for the first achievement on the next Thingamajig collected? Or will Steam simply not touch already unlocked achievements?

# Answer
From what I remember about the Steam API you can set/reset the players progress through the steam API manually which allows you to solve the problem in multiple ways.

As long as the achievement identifiers in the backend reflect the values in your code you should be fine and the new achievement should reflect the already achieved progress in the old stat.

if you want to migrate the already running achievement to new type you can "deprecate it".

* Make the old one "hidden" and remove the game code that updates the value.
* Create new achievement in the steam backend
* Create a game code that will take the players value from the old achievement and save it to new one plus will set the old value to 0.

> I think you get my point here. This approach has some ups and downs but is pretty safe and will probably cause the popup. But I'm more or less sure that you can set the achievement value without causing the popup.

On the other hand I don't think that steam will wipe the players data if you change the original achievement to "progressable". It is is just a flag that makes the progress bar popup and even if you change the max value or modify the achievement in other way it still shoud keep the already existing data. So just do it and observe!

> If you don't want to take the risk do a little experiment. If you are taking the steam deployment seriously you should have a testApp ID anyway.

Hope this helps!
> 1 votes

# Answer
I'm not familiar with how steam handles things (yet to publish there) but I would assume that any player that has unlocked an achievement already would keep the achievement. This is because achievements are not like bool variables that are switched on and off. An achievement will be registered on the steam server as having been achieved. Therefore, any additional progress made after that, regardless of any changes to the code shouldn't matter. This way, even if I deleted the game, my achievement would still be there. If Steam didn't do this (i.e. the achievement would have to be reunlocked when you change the code), the achievement would also be gone when you redownloaded the game- as all local data about the acheivement conditions would have been deleted. However, steam keeps the client unaware of the Servers computation of achievements, so that a fresh client running for the same user can keep acheivements.

Hope this helps.
> -1 votes

---
Tags: steam, achievements
---


# Question
Title: Unity WebGL audio not looping when started with playdelayed()
I have an audioSource in which loop is set to true. I am starting it playing by calling playdelayed()

In the editor its plays fine. In a webgl build it does not loop. It just plays once.

Also in firefox it does not start playing at the correct time, it is a good fraction of a second off.

```
public override void MatchStarted()
{
    Intro.Play();
    Loop.PlayDelayed(Intro.clip.length);
}

```

PlayScheduled has exactly the same effect.

```
public override void MatchStarted()
{
    Intro.Play();
    Loop.PlayScheduled(AudioSettings.dspTime + Intro.clip.length);
}

```

Play(ulong) has the same effect

```
public override void MatchStarted()
{
    Intro.Play();
    Loop.Play((ulong)(44100 * Intro.clip.length));
}

```

I'm posting this here seeking workarounds. Any suggestions? As you can see from my code, my use case is a piece of music with an intro and a loop.

...

ps. I have seen some posts saying that if the bitrate is not 44.1 KHz this can cause looping issues on WebGl. The audio file in question is set to override the bitrate to 44.1 in its import settings.

# Answer
> 1 votes
Ok here is my workaround. I added the intro and loop together into one file. I also added on a little bit more of the start of the loop onto the end, and I made a note of exactly what time the loop should start and end at.

```
const float startlooptime = 11.875f;
const float endlooptime = 74.375f;

public override void MatchStarted()
{
    Loop.Play();
}

void Update()
{
    if (!Loop.isPlaying) return;

    if (Loop.time > endlooptime) Loop.time = startlooptime + (Loop.time - endlooptime);
}

```

---
Tags: unity, audio, unity-webgl
---


# Question
Title: Setting position and look direction of a GameObject
I'm making a bendable game object comprised of a number of bones. The bones positions are calculated using some joints and some maths and that is all working as expected. But I am struggling to rotate the bones to face the correct direction. I'm settings the bones positions like:

```
for ( int i = 0; i <= bonesCount; i++ ){
    Vector3 newPosition = someFunction();
    bones[i].transform.position = newPosition;
}

```

And that works correctly:

But when the bendable object bends the bones retain their original rotation:

I thought I could use `Transform.LookAt` on the bone at position `i` to look at the bone at position `i + 1` but this gives strange results:

It seems like it's an issue with using the wrong axis (up, right or forward). I see `Transform.LookAt` accepts a second argument for `worldUp` but I haven't figured out how that works.

Any suggestions? Is `Transform.LookAt` the correct method to be using?

# Answer
It seems like the everything is working, except that the bones are made in such a way that the forward axis is not the one you'd expect, so that they don't "look at" each other.

A very lazy solution would be, after you execute `LookAt`, on the same object, make a `Rotate` of 90 degrees. It's probably going to be on the X axis, but it depends how your scene is laid out.
> 1 votes

---
Tags: unity, rotation
---


title: GameObjects deleted before scene loads

text:
# Question
Title: GameObjects deleted before scene loads
I am trying to persist objects on scene loading, but the objects always get deleted when the scene does load.

LevelManager.CS

```
public void LoadLevel(string name){
    if (name == "Main")
    {
        SceneManager.LoadSceneAsync(name);
        GameManager.LoadState();
    }
    else
    {
        GameManager.SaveState();
        SceneManager.LoadScene(name);
    }
    Debug.Log("the scene is: " + name);
}

```

I placed the LoadScene method ontop in the hopes it would complete loading the scene before moving onto the next method call. In the next method call, I restore objects to their state.

GameManager.CS

```
public static void LoadState()
        {
            ES3.Load<Dictionary<Vector2, Building>>("Buildings");

            foreach(Vector2 v2 in buildingPositions.Keys)
            {
                Building b = buildingPositions[v2];

                if(b.GetType() == typeof(Farm))
                {
                    newFarm = Instantiate(farmPrefab) as Farm;
                    Debug.Log("Build: " + newFarm);
                    newFarm.transform.position = v2;
                    Debug.Log(newFarm.transform.position);
                    newFarm.level = b.level;
                    **//newFarm.name = b.name;**
                    newFarm.levelText = newFarm.GetComponentInChildren<Text>();
                }
            }

            CheckTheCall();
    }

```

What actually happens is when the scene is changed, the LoadState code is run at the same time, which then causes my object to be deleted after the scene has finished loading, because its created before the scene changes.

The third last line "newFarm.name = b.name" gives me an error that newFarm was destroyed. The last line "CheckTheCall()" calls newFarm (which I declare at the top of the script to ensure scope wasn't the issue) and that shows newFarm exists as a farm. **THEN** after all this, the scene changes, so my instantiated object is deleted.

I'm so confused I tried with just SceneManager.LoadScene(name) but the result is still the same. It's like the entire function completes and then the scene loads.

Any ideas on how to get around this one? I need the objects to spawn back into the main scene in the same state they were.

# Answer
> 1 votes
LoadSceneAsync says explicitly "DO NOT wait for the scene to finish loading before proceeding to the next line." The Async stands for "asynchronous," meaning the load will happen in the background while the rest of your game keeps running, which helps you avoid a visible hitch, and can let you display progress or even have interactivity on your loading screen.

If you want to call a function after the load has completed, you can use the AsyncOperation.completed event:

```
public void LoadLevel(string name){
    if (name == "Main")
    {
        var asyncLoad = SceneManager.LoadSceneAsync(name);
        asyncLoad.completed += PopulateSceneAfterLoad;
    }
...
}

void PopulateSceneAfterLoad(AsyncOperation op) {
    GameManager.LoadState();
}

```

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


# Question
Title: How can I iterate over the vertices of a mesh without an IndexOutOfRangeException?
I'm trying to draw a gizmo sphere at the location of each vertex in my mesh with the following code:

```
private void OnDrawGizmos()
    {
        MeshFilter selectedMeshFilter = (MeshFilter)objecttodraw.GetComponent("MeshFilter");
        Mesh mesh = selectedMeshFilter.sharedMesh;
        Vector3[] vertices = mesh.vertices;
        Color[] colors = new Color[vertices.Length];
        for (var i = 0; i <= vertices.Length; i++)
        {
            Gizmos.DrawSphere(vertices[i], vertices.Length);
        }
    }

```

I'm getting an exception, "Array index is out of range" on this line:

```
Gizmos.DrawSphere(vertices[i], vertices.Length);

```

> IndexOutOfRangeException: Array index is out of range.
>
> GetBounds.OnDrawGizmos () (at Assets/Scripts/GetBounds.cs:32)
>
> UnityEngine.GUIUtility:ProcessEvent(Int32, IntPtr)

# Answer
Arrays in C# are zero-based. That means an array of vertices of length 4 has entries at:

```
0, 1, 2, 3

```

Trying to access an entry at index 4 is asking for the fifth item from a list of four things — so the runtime complains that you're indexing out of the array's bounds.

Your for loop should look like this:

```
for( int i = 0, i < vertices.Length; i++)

```

With a "less than" in the test, not "less than or equal to"
> 3 votes

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