# Question
Title: Can I use the HD Graphics 3000's quad list primitive type via D3D?
I was studying some technical documentation on the Intel HD Graphics 3000 GPU, which I'm using as a lower-end reference for my 2D game engine. I noticed the hardware supports a nice "Quad List" topology, where every 4 vertices in a vert buffer are interpreted as an independent quad. My engine draws nothing but sprite quads, so that would be a nice optimization in my case, to eliminate the need for copying / caching / processing an accompanying index buffer with 12 bytes per quad of trivial triangle edge definitions (I'm using indexed TriangleList primitives at the moment).

From what I can tell though, DirectX 9 doesn't expose quad list, and after some cursory peeking around in DX10/11 (which I don't plan to support at this point) it seems they don't expose this feature either.

Does anyone know if there's a way to use Quad Lists in DirectX? I'd be curious about OpenGL also, if anyone has experience on that side.

# Answer
> 7 votes
There's no *documented* way to do this in Direct3D; it simply does not have support at the API level for quads as a primitive type.

D3D doesn't have an extension mechanism like OpenGL does, but in some cases driver vendors support enabling certain kinds of "extended" features by passing certain combinations of invalid or otherwise-nonsense parameters to certain APIs. If this is the case for this GPU, you'll likely find the information you need in the GPU documentation, not the D3D documentation.

It's also possible that the card simply supports this primitive type internally as a optimization or a bootstrapping phase of certain kinds of higher-order primitive or tessellation support.

It's *also* possible that this is simply a legacy mode left over from, and still existing to support, older OpenGL versions (which had a quad primitive type), or for use with other more specialized APIs than D3D and OpenGL.

# Answer
> 5 votes
While D3D doesn't support quad primitives, there's nothing in principle wrong with continuing to draw them as a triangle list.

First thing to realise is that the index buffer used to simulate quads with a triangle list can always remain static, so you can create it once only (during startup), then just reuse it every time you wish to draw. The code to generate it is utterly trivial:

```
unsigned int *ndx = // pointer to memory returned by ID3DIndexBuffer9::Lock; change to unsigned short for 16-bit indices

// MAX_QUAD_VERTS should be a multiple of 4 and be 4 times the maximum number of quads you draw
for (int v = 0; v < MAX_QUAD_VERTS; v += 4, ndx += 6)
{
    ndx[0] = v;
    ndx[1] = v + 1;
    ndx[2] = v + 2;

    ndx[3] = v;
    ndx[4] = v + 2;
    ndx[5] = v + 3;
}

```

Using this index buffer you can then pass the *exact same* vertices to your vertex buffer as if you were drawing quads natively and get the same result.

This will also have the advantage of working the very same (and using the very same code) on hardware that doesn't support quads natively. Even on hardware that *does* support quads natively it may provide better performance as hardware and drivers are more likely to be optimized around drawing indexed triangle lists.

OpenGL does support quad lists and quad strips but they're deprecated in modern core contexts.

---
Tags: opengl, 2d, directx, gpu
---


# Question
Title: How does one perform collision detection on objects made of many small triangles?
I understand that any shape can be created (or approximated) by smaller triangles. Any rectangle can be created by 2 smaller triangles. Any circle can be created by many thin "pizza slice" triangles. How does this translate to collision detection?

I understand how to calculate rectangle overlap using the vertices. I understand how to calculate circle overlap using the center, radii, and distance.

But, how does one do collision detection on shapes made of small triangles? Not specifics, but just the general concept....

# Answer
> 26 votes
> But, how does one do collision detection on shapes made of small triangles?

By not doing it.

Collision detection against an arbitrary triangle collection (or worse, between two collections of arbitrary triangles) is prohibitively expensive.

Instead, we typically perform collection detection in a hierarchical fashion, beginning first with extremely crude, simple shapes (like boxes or spheres) that approximate (poorly) the underlying object.

This allows us to quickly reject the majority of potential collisions as "not occurring," which is the usual case. In the case where a such a crude check passes, that indicates a potential actual collision, and we proceed to perform the check against a more-detailed approximation of the underlying shape (such as one made of multiple tightly-fitted capsule shapes, or many aligned bounding boxes).

Essentially, collision detection starts with crude tests and, as those tests pass, continues to more and more detailed representation. This image, provided by Shiro in a comment to Alexandre's answer, illustrates how a complex model (a human) may be represented by a series of simpler shapes:

Rarely do we actually *need* to perform collision at the individual triangle level, and when we do we've usually used the cruder methods to drill down to a very small set of potential triangles to test against. At that point, specific algorithms are used to perform the tests, just like you'd test if two rectangles overlap. For example, you can determine if and where a ray hits a triangle.

# Answer
> 4 votes
The collision detection is based on geometry (primitives like line, planes, spheres, boxes, capsules, cylinders).

If you need to perform collision detection on shapes made out of triangle, for instance a terrain that is not flat, you have to test against all the triangles that form the mesh.

If you get to that point, I would strongly advise to use a pre-made collision detection engine, as this kind of stuff get pretty complex, pretty fast.

---
Tags: collision-detection
---


# Question
Title: Detect if two objects are going to collide
I am working on a car game where I am to create an AI. In the game there are other cars and a few objects moving around that I do not want to crash with, I have the speed, position and direction of all objects including my own car, but how would I go about calculating if my car is on a collision course with another object given my current speed and the other objects current speed? I tried coming up with an algorithm myself but I'm not very good at algebra.

# Answer
I thought this would be an interesting challenge to test some of the math I learned in school, so here's what I figured out.

This approach assumes each object can be considered a circle for collision purposes. Naturally a car isn't a perfect circle, but it could be used as an approximation. You could use more circles to fill the area of the car better if you want a better approximation. E.g you could have one big circle in the center and one more in each corner of the car (for a total of 5 circles), or you could fill the car with 3x2 circles or 4x2 circles.

**To make sure the final solution was correct and actually worked, I have now implemented it so you can see for yourself: http://codepen.io/sveinatle/pen/OPqLKE?editors=011. The code for this demo is at the bottom of the post as well.**

I will describe the main concepts and give the final expressions needed here. To see the details please have a look at this online worksheet. The worksheet includes calculating the relevant values for a test case as well, so you could use that test case to check if you are applying the formulas correctly to the given variables. You can also see a plot which illustrates how the distance of the two points in the test case changes over time. You might want to draw the start- and finish-position of each of the two points on 8x8 grid to visualize meaning of the test case values which are calculated in the worksheet.

For each car/object/**point**, you know the following:

```
initial x position
speed in x direction
initial y position
speed in y direction

```

For two points `a` and `b` then, lets define the following variables:

```
xa0: initial x position of point A
xat: speed in x direction of point A
ya0: initial y position of point A
yat: speed in y direction of point A

xb0 initial x position of point B
xbt speed in x direction of point B
yb0 initial y position of point B
ybt speed in y direction of point B

```

The distance between to points is given by Pythagoras. By expressing this distance as a function of time (based on the given variables above), then we can solve for the minimum possible distance. If we do this then we get a formula which will give us the `time` of minimum distance. The details of this derivation can be seen in the worksheet -- I won't repeat them here -- but the result is the following formula:

```
mintime =
  -(xa0*xat - xat*xb0 - (xa0 - xb0)*xbt + ya0*yat - yat*yb0 - (ya0 - yb0)*ybt)
  /
  (xat^2 - 2*xat*xbt + xbt^2 + yat^2 - 2*yat*ybt + ybt^2)

```

As you can see, this is a straight forward expression using only the given variables. The resulting value `mintime` is the time in seconds (or whatever unit your speeds are expressed in) when the two points will be the closest. This time is relative to the time of the starting positions, so if this time is **negative** then that means that the potential collision would have been in the past. In other words, there is no pending collision in the future and your work is done.

If the calculated `mintime` is **positive**, then that means the time of minimum distance is in the future. The next step then is to determine just how close that minimum distance will be: Is it close enough to consider it a collision?

The distance at any time `t` is given by the following expression:

```
dist = sqrt((t*xat - t*xbt + xa0 - xb0)^2 + (t*yat - t*ybt + ya0 - yb0)^2)

```

Once again a fairly simple expression. It depends on the given variables in addition to `t`. To calculate the minimum distance then, you just evaluate it using the minimum time you calculated previously. So with `t = mintime`:

```
mindist = sqrt(
  (mintime*xat - mintime*xbt + xa0 - xb0)^2
  +
  (mintime*yat - mintime*ybt + ya0 - yb0)^2
)

```

And there you have your answer. The last thing to do now is to compare this minimum distance to the radius of the to circles. If `mindist > radius_A + radius_B`, then the two circles will never touch. If is less than or equal, then they will touch and you know there will be a collision *within* `mintime`-seconds. The collision might actually happen before `mintime`-seconds because the edges of the circles will touch each other before their centers are at their closest.

---

## CoffeeScript

```
$body = $('body')
$state = $('<div class="State">').appendTo $body
w = $body.width()
h = $body.height()

startTime = null
totalTime = null

class Car
  constructor: (@x0,@y0,@xt,@yt)->
    if @x0? # Allow test case
      @disablerandom=true
      @x0 = @x0*100
      @y0 = @y0*100
      @xt = @xt*100
      @yt = @yt*100
      @radius = 50
    @view = $('<div class="Car">').appendTo $body
    @reset()
  reset: ->
    @outside = false
    if not @disablerandom
      @x0 = Math.random() * w
      @y0 = Math.random() * h
      @xt = Math.random() * (w/2-@x0)
      @yt = Math.random() * (h/2-@y0)
      @radius = 5 + Math.random() * 100
    checkForCollision?()
    @view.css
      width: @radius*2
      height: @radius*2
      marginLeft:-@radius
      marginTop:-@radius
  update: ->
    if @x > w or @x < 0 or @y>h or @y<0 then @outside = true
    @x = @x0 + @xt*totalTime
    @y = @y0 + @yt*totalTime
    @view.css left: @x
    @view.css top: h-@y

class CollisionChecker
  constructor: (@a, @b)->
    @mindist=0
    @mintime=0
    @checkForCollision()
  checkForCollision: ->
    @mintime =
      -(@a.x0*@a.xt - @a.xt*@b.x0 - (@a.x0 - @b.x0)*@b.xt + @a.y0*@a.yt - @a.yt*@b.y0 - (@a.y0 - @b.y0)*@b.yt) /
      (Math.pow(@a.xt,2) - 2*@a.xt*@b.xt + Math.pow(@b.xt,2) + Math.pow(@a.yt,2) - 2*@a.yt*@b.yt + Math.pow(@b.yt,2))
    @mindist = Math.sqrt(
      Math.pow(@mintime*@a.xt - @mintime*@b.xt + @a.x0 - @b.x0, 2) +
      Math.pow(@mintime*@a.yt - @mintime*@b.yt + @a.y0 - @b.y0, 2)
    )
  renderCounter: ->
    mintimeView = Math.round(@mintime*100)/100
    mindistView = Math.round(@mindist*10)/10
    minedgedistView = Math.round((@mindist-@a.radius-@b.radius)*10)/10
    if @mintime <= 0
      @mindist = Math.round(@mindist)
      $state
        .css color: 'green'
        .html """
          Will never collide (diverging)<br>
          Minimum center distance: #{mindistView}px<br>
          Minimum edge distance: #{minedgedistView}px<br>
          Time from start of min. dist.: #{mintimeView}s
                """
    else
      timeleft = Math.round((@mintime - totalTime)*100)/100
      if @mindist <= a.radius + b.radius
        $state
          .css color: 'red'
          .html """
            Will collide within #{timeleft}s<br>
            Minimum center distance: #{mindistView}px<br>
            Minimum edge distance: #{minedgedistView}px<br>
            Time from start of min. dist.: #{mintimeView}s
                    """
      else
        $state
          .css color: '#990'
          .html """
            Will not collide, but reach minimum distance in #{timeleft}s<br>
            Minimum center distance: #{mindistView}px<br>
            Minimum edge distance: #{minedgedistView}px<br>
            Time from start of min. dist.: #{mintimeView}s
                    """

# Test case 1
#a = new Car(2,5,1,2/3)
#b = new Car(5,2,-2/3,4/3)

# Random
a = new Car()
b = new Car()
checker = new CollisionChecker a, b

a.view.css backgroundColor: 'red'
b.view.css backgroundColor: 'blue'

startTime = new Date().getTime()/1000.0
setInterval ->
  totalTime = new Date().getTime()/1000.0 - startTime
  a.update()
  b.update()
  checker.renderCounter()
  if a.outside or b.outside
    console.log 'reset'
    startTime = new Date().getTime()/1000.0
    w = $body.width() # Get viewport dimensions again in case of resize
    h = $body.height()
    a.reset()
    b.reset()
    checker.checkForCollision()
, 10

```

## CSS (Stylus)

```
html
  height 100%
body
  position relative
  background-color #ffe
  height 100%

.Car
  position absolute
  border-radius 200px

.State
  font-size 20px
  margin-top 30px
  margin-left 30px

```
> 7 votes

# Answer
The basic idea is that you extend your car's collision box, based on the current velocity of the car. If this extension collides with a car or with car's extension box, you can assume that there will be a collision, so you must have the car that is the most 'behind' to avoid the collision.

There seem to be a nice article here. They use vectors, but you'd want to use boxes in your case.
> 0 votes

# Answer
You could approach the issue by evaluating delta position each frame and check if by moving another delta the collision would trigger.

```
prevPos = pos;
pos = newPos;
deltaPos = prevpos - pos

if(EnterCollision(pos+deltaPos))
//do stuff

```
> 0 votes

---
Tags: collision-detection, mathematics, linear-algebra
---


# Question
Title: Looking for some insight on programming design for attacking and attack types in a game
So, I'm starting to introduce attacking to our 2D space RTS (This is in Unity, so it's component driven). Initially it was as simple as "enemy in range, damage applied". However there will be multiple "types" of weapons/attacks that are associated with their particular ship or structure. As well as other factors involved past just raw damage such as the damage type, and possibly inertia in the future.

Would you guys have each unit and structure type have it's own attacking type. Meaning you make a script for each unit/structure that defines it's attack type, damage, effects, range, particles, sprites...etc And attach that as a component?

Or make a script that defines an attack type, a script for the projectile type associated with that...etc And then extend those and modify those for each unit, attaching each script to the unit/structure.

---

I hope I'm making some sense, I've been pondering this for so long I'm not sure if I'm solving a problem, or just making up my own problems and digging myself into a hole.

When you have a game that can have a multitude of attack types that may or may not be limited to a specific unit/structure, how do you design the framework that tied that together to the specific units/structures in a component-driven design environment?

If this is not clear enough let me know.

**Edit: Great answers, thank you.**

**Expanded Question:**

The answers seem to vary from "each object can have it's own attacking script" to "Have the attack types as their own scripts and assign that to each object for a more reusable solution". Lets say I have a "blaster" attack, it shoots a red projectile at a certain speed. It's damage, rate of fire, and projectile size are dependent on the unit firing it. Is it better to just make an attack script for that unit, or try and modify a "blaster attack" to fit the purpose of each unit that wants to use it?

# Answer
> 12 votes
Well, I'm honestly not an expert on this but... I think it depends on how complex and varied you think the attacks will become. Since it's an RTS I'm guessing you'll have maybe 10-50 or so different units or structures with their own attack types.

Option 1: If there is a relatively low number of units that will have attacks that are somewhat similar I would simply put everything in one big script and define the parameters used in the inspector.

Option 2: If, on the otherhand you envision a large number of attack types with dissimilar behavior you can break everything up so that each unit and building gets their own unique attack script. I'm thinking that if you do this, you might want to create a "helper" script that defines commonly used chunks of code that many of the individual scripts can grab from. This way you won't have to rewrite everything and you'll know where it all is.

Option 3: What you probably shouldn't do is have certain groupings of units share scripts, this will likely confuse you and will become a mess if the code you need for an attack is in 10 different scripts.

Here, I drew you a picture.

# Answer
> 5 votes
I don't know a whole lot about Unity and I haven't done game development in a while, so let me give you general programming answer to this question. I have based my answer on the knowledge I have about entity-component systems in general , where an entity is a number that is associated with N many components, a component only contains data, and a system operates on sets of components that are associated with the same entity.

Your problem space is this:

* There are multiple ways of attacking an enemy in the game as whole.
* Each ship, structure, etc, may have multiple ways of attacking (each determined by some manner)
* Each attack may have it's own particle effects.
* The attack must factor in some factors (such as inertia, or armor, for example), that are present on the target and on the user.

I would structure the solution like the following:

* An attack has an identifier - this could be a string.
* An entity 'knows' that it can use an attack (based on the identifier of the attack).
* When the attack is used by the entity, the corresponding display component is added to the scene.
* You have some logic that knows about the target of the attack, the attacker, and the attack being used - this logic should decide how much damage you do (and have access to the inertia or whatever of both entities).

It is important that the point of contact between the attacks and the entities are as thin as possible - this will keep your code reusable and prevent you from having to come up with duplicate code for each different type of entity that uses the same type of attack. In other words, here's some JavaScript pseudo-code to give you an idea.

```
// components
var bulletStrength = { strength: 50 };
var inertia = { inertia: 100 };
var target = { entityId: 0 };
var bullets = {};
var entity = entityManager.create([bulletStrength, inertia, target, bullets]);

var bulletSystem = function() {
  this.update = function(deltaTime, entityId) {
    var bulletStrength = this.getComponentForEntity('bulletStrength', entityId);
    var targetComponent = this.getComponentForEntity('target', entityId);
    // you may instead elect to have the target object contain properties for the target, rather than expose the entity id
    var target = this.getComponentForEntity('inertia', targetComponent.entityId);

    // do some calculations based on the target and the bullet strength to determine what damage to deal
    target.health -= ....;
  }
};

register(bulletSystem).for(entities.with(['bullets']));

```

Sorry this answer is a bit 'watery'. I only have a half hour lunch break and it's hard to come up with something without knowing fully about Unity :(

# Answer
> 3 votes
When a unit/structure/weapon attacks, I would probably create an Attack (subclassed with all your fun details) that takes the attacker and the defender (or defenders). The Attack can then interact with the target/defender (slow, poison, damage, change state), draw itself (beam, ray, bullet), and dispose of itself when it's done. I can foresee some issues like multiple poison attacks, so maybe your targets would implement a Damageable interface that the Attack interacts with, but I think it's a workable approach that's modular and flexible to change.

**Expanded Answer**
This is how I'd approach the blaster attack with *this approach*. I'll let the others answer for themselves.

I would have my units implement an IAttacker interface or class with basic attack stats/methods. When an IAttacker attacks an IDamageable, it creates its specific Attack passing itself and its target (the IAttacker and the IDamageable, or perhaps a collection of IDamageables). The Attack grabs the stats it needs from the IAttacker (to avoid changes during upgrades or anything like that--we don't want the Attack to change its stats after it's already been launched) and if it needs specialized stats, casts the IAttacker to its needed type (ex. IBlasterAttacker) and gets the specialized stats that way.

Going with this approach, a BlasterAttacker just needs to create a BlasterAttack, and BlasterAttack takes care of the rest. You can subclass BlasterAttack or create separate FastBlasterAttacker, MegaBlasterAttacker, SniperBlasterAttacker, etc, and the attacking code for each is the same (and possibly inherited from BlasterAttack): Create the BlasterAttack and pass myself and my target(s) in. BlasterAttack handles the details.

---
Tags: c#, unity, game-design
---


# Question
Title: (Java) Trying to animate an arraylist of coins with a (working) animation class
I have a coin class which takes in an integer `numOfCoins`and an enum `LayoutType`, which can be linear or curved. A linear layout displays the coins in a straight line one after the other - we'll work with this since the method is small and straight forward.

My constructor looks like this:

```
public Coin(float xPos, float yPos, int numOfCoins, LayoutType layout) {
        setType(ObjectType.COIN);
        coinList = new ArrayList<Coin>(); // arraylist of coins
        setPos(xPos, yPos); // set starting position of coin(s)
        if (layout == LayoutType.LINEAR)) {
            linearLayout(); // display coins in a straight line
        } else if (layout == LayoutType.CURVE{
            curveLayout();
        }

}

```

And my `linearLayout()` method looks like this

```
public void linearLayout() {
        //draw numOfCoins amount of coins in a straight line
        for (int i = 0; i < numOfCoins; i++) {
            Coin coin = new Coin(xPos, yPos);
            coinList.add(coin);
            xPos += 50; // place coins 50 pixels apart
        }
}

```

I have a working animation class and a spritesheet for the coins - however, the way I have modelled my coins is in such a way that 1 coin object can contain `numOfCoins` amount of coins, so I can't just directly call the animation in the draw method.

The class' `draw()` method is in an abstract class `GameObject` which `Coin` extends. It looks like this:

```
public void draw(SpriteBatch batch) {
    // if the object is a coin iterate through the list of coins
    // and draw the sprites, if it isn't a coin, simply draw the objects sprite
    if (type == ObjectType.COIN) {
        for (Coin coin : getCoinList()) {
            coin.getCoinList().draw(batch);
        }
    } else {
        sprite.draw(batch);
    }
}

```

This draw() method is called in World.render().

How would I create an animation using my `Animator`class for each coin if I have 6 coins in a straight line for instance? I can't seem to find a way. Highly grateful for any help, thanks.

# Answer
Are all coins doing the same animation? You could make a method in the `Animation` class that takes a coin as an argument, then performs the animation on that coin. Then, on another class, you make a loop that traverses the coin list and calls the method in your `Animation` class, therefore animating each coin as you go through the list. You can also add delay between each coin animation.

By the way, I'm just curious, you have a `coinList` inside `Coin`, and everytime the constructor is called, you call `linearLayout, which adds`numOfCoin\` number of coins in the list. Isn't it adding unnecessary coins?
> 1 votes

---
Tags: java, 2d, android, libgdx, animation
---


title: Calculate intersect point / aim point

text:
# Question
Title: Calculate intersect point / aim point
I'm working on a simple game, and I need to calculate the position to aim.

Since my math days are a bit behind me, I put together a simple example to illustrate:

So given that I know the position of the two objects, and the velocity, how do I calculate the point at which they intersect (i.e. the point to aim for)?

EDIT: To clarify, the cannon is fired at time 0, there is no waiting.

# Answer
I was able to solve this using trig instead of vector math. Here's how it looks as a triangle.

Notice that since this is meant for a computer coordinate system, the \\$y+\\$ axis is down. Also the angles are as such: \\$x+ = 0°\\$, \\$y+ = 90°\\$, \\$y- = -90°\\$, and \\$x- = ±180°\\$

Additionally, we know that line B's angle is \\$∠B = -10°\\$.

The speeds don't matter since they can be expressed as a ratio \\$r = 120 / 25\\$. So \\$A\\$ can be expressed as \\$B * r\\$, as shown.

We can calculate the length and angle of \\$C\\$ as:

$$ \begin{align} C &= \sqrt{(b.x - a.x)^2 + (b.y - a.y)^2} &&\approx 10.05 \\ ∠C &= atan2(b.y - a.y, b.x - a.x) &&\approx 84.29° \end{align} $$ therefore:

\\$∠a = ∠C - ∠B ≈ 94.29°\\$

Now we have all we need to use the Law of Cosine, which states:

\\$A^2 = B^2 + C^2 - 2\*B\*C\*cos(a)\\$

Since we know that \\$A\\$ is a ratio of \\$B\\$, we can express it like so:

\\$(B\*r)^2 = B^2 + C^2 - 2\*B\*C\*cos(a)\\$

Solve for \\$B\\$ and we get:

\\$B = ± \frac{ \sqrt{ C^2 * (cos(a)^2 + r^2 -1 ) } - cos(a)\*C }{r^2 - 1} \approx 2.18\\$

Since time is not a factor in this equation, we get two results, depending on if we're forward in time or backwards. We'd have to check that the \\$B\\$ we get is in the right direction.

Finally, we now know enough to calculate what we want:

$$ \begin{align} c.x &= a.x + B * cos(∠B) &&\approx 4.14 \\ c.y &= a.y + B * sin(∠B) &&\approx 1.62 \end{align} $$

For bonus points, if we wanted the shooting angle \\$∠A\\$, we can get it like so:

\\$∠A = atan2(c.y - b.y, c.x - b.x) \approx -83.72°\\$
> 2 votes

# Answer
I tried to solve it following @david van brink comment.

P: intersection point (unknown)
S1: car's starting point(2,2 here)
S2: canon's starting point(3,12 here)
|v1|: car's velocity length (25 here)
|v2|: canon ball's velocity length (120 here)
a: angle between the car's velocity and the X-axis (10 degrees here... or Pi/18)
b: angle between the canon ball's velocity and the X-axis (unknown)

`(1): P.y = tan(a) * P.x + S1.x` (This is true because P should be a point on the car's path, so it is on a straight line y = a\*x + b)

`(2): Distance(P,S1) / Distance(P,S2) = 25/120` (This is true because, for example, if the canon ball had double the speed of the car, then, at any given time, the distance covered from the car is half the distance covered from the ball)\`

`(3): b = arctan((P.y - S2.y)/(P.x - S2.x))`

From `(1)` and `(2)` ==\> {

A = (1 + tan(a)^2) * (|v1|^2 * |v2|^2)

B = |v2|^2 * (2 * tan(a) * (S1.x - S1.y) - 2 * S1.x) +
|v1|^2 * (2 * tan(a) * (S2.x - S2.y) - 2 * S2.x)

C = |v2|^2 * (2 * S1.x^2 + S1.y^2 - 2 * S1.y * S1.x) -
|v1|^2 * (2 * S2.x^2 + S2.y^2 - 2 * S2.y * S2.x)

`(4): A * P.x^2 + B * P.x + C = 0`
}

By solving `(4)` ==\> you can find `P.x`,

From `P.x` and `(1)` ==\> you can find `P.y`

From `P.x` and `P.y` and `(3)` ==\> you can find `b`.
> 1 votes

# Answer
This is how I would pose the problem:

position equation: $$ \begin{align} P\_{dest} &= P\_{01} d\_1 t\_1 = P\_{02} d\_2 t\_2 \\ t\_1 &= P\_{dest} / (P\_{01} d\_1) \\ P\_{02} d\_2 t\_2 &= P\_{01} d\_1 P\_{dest} / (P\_{01} d\_1) \\ t\_2 &= (P\_{01} d\_1 P\_{dest} / (P\_{01} d\_1) ) / P\_{02} d\_2 \end{align} $$

movement equation: $$ \begin{align} P\_{01} + v\_1 d\_1 lapse\_1 &= P\_{dest} \\ P\_{02} + v\_2 d\_2 lapse\_2 &= P\_{dest} \end{align} $$

Relationship: $$ \begin{align} v\_1 d\_1 lapse\_1 = t\_1 \\ v\_2 d\_2 lapse\_2 = t\_2 \end{align} $$

Then continue to substitute terms into each other until I find what I need.

Considering your question I think what you need is \\$d\_2\\$. I guess the things you know are:

* \\$P\_{01}\\$, \\$d\_1\\$, \\$v\_1\\$
* \\$P\_{02}\\$, \\$v\_2\\$

So try to make an equation that exhibits \\$d\_2=\\$ *only stuff you know* from the set of equations in the drawing. That has to be possible.
> 0 votes

---
Tags: 2d, mathematics, physics
---


# Question
Title: Client code handling its own generics when returned by an engine
I'm writing a game engine in Java 8, and have prototype client code written in Groovy.

New Game objects can be created with a builder which defines everything which fills in the blanks. To simplify things, suppose the only thing the Game class needs is a mapping of keyboard inputs (which both the client and engine know about) to dynamic input events (which only the client knows about).

The input events are defined by the client, and are only ever dealt with by the client. The engine acts only to notify the client that an input has occurred which has been mapped to that input event. At that point, it then calls a method implemented by the client with that input event as the sole parameter.

My goal is to have the client code which receives the input event know at compile time the type of the event which is first provided by the client when the Game object is instantiated. My initial naive attempt at this was to turn all my engine code into generic type of `<T extends Enum<?>>` but this just made a mess of everything, and solved nothing since the client code, as far as I know, only knows it's dealing a generic enum when it gets a callback.

Is this what I'm attempting even possible? Am I heading down the road with enums and generics?

# Answer
Because of type erasure you lose the compile time type information of generics when transmitting data over network. If you need it on the receiving side again, you have to put the type information back yourself somehow.

It's impossible to say how you should do this, but typically it involves either enums or class names and some type casting.
> 2 votes

---
Tags: java, architecture
---


# Question
Title: 'The thing you want to instantiate is null' - unity error when instantiating
I have a Game Object called 'car' in my Assets folder. I have this code in C# unity to instantiate it.

```
GameObject car;

    void Start () {

        Vector3 position = new Vector3(5, 5, 5);

        GameObject newGameObject = Instantiate(car);

        newGameObject.transform.position = position;

    }

```

And I get this error - '**the thing you want to instantiate is null**'

What might be the problem ?

# Answer
> 1 votes
The `GameObject` car is not set to anything. That means it's `null`. This is exactly what the error message is telling you. Just because you happen to have a prefab named 'car' in your Assets folder doesn't mean you can name a variable `car` and expect Unity to know you're talking about the same thing.

See my answer to your other question to learn one way to instantiate a prefab.

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


# Question
Title: Moving skeletal animation blending logic to GPU: worth it?
We have a solid skeletal animation system in our engine. It allows to set up to three animations onto each bone and blend them seamlessly. The animation update (fetching animation matrix given current time) and blending (two slerps for the three matrices) is done on the CPU while the actuall skinning (vertex transforms) is done on the GPU. Each vertex in our engine can be affected by up to four bones.

I am now considering moving the aforementioned update and blend functionality onto the GPU. Our CPU is loaded much more than the GPU even though these two operations are already done in parallel. This is how it can be done:

1. At compile time, all the animation data for each skeletal model for each timestep is baked into textures.
2. The update and blend functionality is done on the GPU in a single Draw() call by instancing quads. One quad is required for each bone on the scene. Each quad will render 16 pixels - the resulting matrix. To compute this matrix, I will need to sample the animation texture from (1) 4\*12 = 48 times (to get three animation matrices for the current frame) and perform 2 slerps. I think I will be doing it in the vertex shader.
3. At the skinning phase, I will sample the texture, rendered at stage (2) 4\*16=64 times to get four matrices for the four bones, that can affect current vertex. It will be a GPU performance hit, but that is the main purpose of this process: to free up CPU cycles.

So my question is, has anyone ever tried this? Is it even worth thinking about? This system will take quite some time to implement and if there is some serious flaw in it, I would like to know about it. From my perspective it sounds good. At the same time I have never heard of anyone using such a system, which alerts me. Everywhere I read, the animation data is passed into the vertex shader as a huge array of matrices, which implies standard CPU update/blend system.

I wonder how games like StarCraft 2 do the update and blending. They have situations when there are tones of skeletal creatures on the screen (200 zerglings is standard, each has 2000 polygons, idk how many bones though...)?

UPDATE: I am working with XNA 4.0 that is DirectX 9, that is 224 uniforms in the shader.

# Answer
Why not just move the blending to the skinning phase?

You just need to add the base matrices and the interpolation qualifier to the uniforms (or a static texture for the matrices if you really want to); you have a *lot* of space for uniforms.

Also passing and slerping quaternions is cheaper than passing and slerping matrices. and applying a quaternion rotation to a vec4 is very straightforward.
> 1 votes

---
Tags: skeletal-animation, gpu, skinning
---


# Question
Title: What is the purpose of the canonical view volume?
I'm currently learning OpenGL and haven't been able to find an answer to this question.

After the projection matrix is applied to the view space, the view space is "normalized" so that all the points lie within the range \[-1, 1\]. This is generally referred to as the "canonical view volume" or "normalized device coordinates".

While I've found plenty of resources telling me about how this happens, I haven't seen anything about *why* it happens.

What is the purpose of this step?

# Answer
> 7 votes
The most important is that it converts yours points(vertices) from 3D world space to 2D screen space.

That means that after vertex is multiplied with this matrix X and Y coords are position on the screen (between \[-1, 1\]) and Z is the depth. Z is used for depth-buffer and identifies how far is vertex (or fragment) from your cameras near plane.

Projection means that vertices which are nearer to the near plane are further from the middle of the screen -\> triangle nearer to the camera appears to be bigger than one that is further. And this is based on yours field of view - you are entering it in some createProjectionMatrix function or createFrustum. It works that it shears and scales yours camera frustum and vertices in it into unit cube. Values that are greater than 1 and smaller than -1 are not displayed.

Also keeps pixel aspect ratio, so pixel can be sqaure. That is simple. It just shears camera frustum like this: more wider screen -\> more vertical shear and vice versa.

**Simple answer:**
It defines yours camera frustum and is good to:

* make objects which are near to you look bigger than objects that are far from you.
* keep pixel aspect ratio - Everybody likes square pixel right? :)

# Answer
> 5 votes
This answer is long after the fact, but since I found this on google maybe this will still help someone. I just want to clarify what JasonD and Notabene were saying: It is a lot easier to do clipping calculations (figure out what you should see and what you shouldn't see because of which way you are looking, how far away it is, ect.). Instead of checking if things intersect the planes on the borders of your view frustum, you simply compare the x,y,z of everything to xMax, xMin, yMax, ect. , since you simply have a cube. It is a little more complicated if you want to only have part of something showing, but the math is still better with a unit cube than with a frustum.

A couple things I found misleading in other answers:

-You aren't shearing the sides off of the view frustum, you are sort of warping it into a cube using homogeneous matrix transformations.

-We aren't converting to a 2D screen with this step. This step isn't necessary to do so. Theoretically we could do all our work without converting the frustum to a cube first, which would be more intuitive but harder math - but graphics is all about doing calculations really fast since there are a LOT of calculations per second for the average game/whatever.

More detail: It isn't necessarily a unit cube we are converting to, it just has to be a rectangular box for our max-min calculations to work out. In fact in class we used a box where the camera faces down the z-axis, z goes from 0 to 1, x goes from -1 to 1, and y goes from -1 to 1. In general in math 1, 0, and -1 are good numbers for making calculations easier, I assume that is why we don't go from -100 to 100 or something.

TLDR: It makes clipping easier.

Edit: bobobobo has the gist of it. Everything is triangles, generally :D.

Source: Taking a university graphics class

# Answer
> 2 votes
I believe this is because OpenGL can't make assumptions about how the image is to be displayed (aspect ratio or resolution, hardware details, etc). It renders and image into an intermediate form which the operating system or driver or whatever scales to the correct resolution/size.

# Answer
> 2 votes
I note an answer has already been accepted, but it's generally useful for clipping to have the view frustum transformed into a unit cube.

# Answer
> 1 votes
I've also been wondering this. There are a couple of things to consider.

First, yes, everything in the world gets transformed to that unit cube \[-1,1\] centered around the origin. If something isn't in that unit cube then it isn't going to be displayed.

The nice thing about this is now, you can cull triangles pretty easily. (If all 3 vertices of a triangle have `x > 1` or `x < -1` then that triangle can be culled).

# Answer
> 0 votes
I would recommend to check the lesson on perspective projection matrix on Scratchapixel

http://www.scratchapixel.com/lessons/3d-basic-rendering/perspective-and-orthographic-projection-matrix/build-basic-perspective-projection-matrix

It clearly explains that the why is to warp the view frustum space to a unit cube. Why? Essentially because the process of projecting 3D points on the canvas involved to convert them NDC space which is a space in which points on the screen are remapped in the range \[-1,1\] (assuming the screen is square). Now we also remap the point Z-coordinate to the range \[0,1\] (or sometimes \[-1,1\]) therefore in the end you end up with a cube. The fact is that when points are contained in a cube, it's easier to process them than when they are defined in the view frustrum (which is a strange space, a truncated pyramid). Another reason is that it sorts of bring all sort of projective transformation you can imagine in CG to the same space (the unit cube thingy). So regardless of whether you use a perspective or orthographic projection for example, you end up with a cube in the end, and from there you can apply the same transforms to remap the coordinates to their final position in the image (raster space).

Though maybe you focus too much on the why. The unit cube is really just the result of the process of the mathematics involved or used to project vertices onto a screen and then remap their coordinates to raster space.

---
Tags: opengl, mathematics
---


title: Isometric vehicle animation

text:
# Question
Title: Isometric vehicle animation
I am working on a medieval isometric RPG in which the player can ride on horses and in horse drawn carriages. The player's movement is not restricted to the common eight directions; he may move in whichever direction he points his joystick in. What is stumping me is the problem of animating this sucker. I'd rather not have my horse and carriage sliding along unnaturally at an angle to their animation's direction, but I would also like to keep my player movement system.

I have considered a snake-like algorithm where the carriage parts bend along a curve when they turn, but I am not sure this can be done with 2D artwork. I have also considered creating large numbers of animations for the horse and carriage, but this is too time intensive to be feasible.

Now maybe I'm off topic and maybe this question is going to get deleted, but I am wondering if anyone out there can either suggest an idea on this or point me to a game which has implemented thi kind of functionality before (with cars, carriages, or other kinds of vehicles).

# Answer
I guess you have two options:

1. Render more angles, 12 or 16. If you create your asset in a 3d program you can create it once and render many angles in no time. Only limit is the texture size. I guess 12 sprites are enough.
2. Splitting your sprite in two parts allows you two animate the curves more smoothly. However you still have the problem that your sprite moving/animation angle has a max error of 22.5° which is not that big. Of course you can combine the two points. To reduce the error you can use more sprites. The algorithm depends on you implementation of the game objects. I would make the front the part which you can control and the back part which gets pulled by the rear of the front. Then you should get two angles and you can render two sprites at different angles.
> 5 votes

# Answer
Well I am definetely no expert, But I have read somewhere, about someone rendering a 3D object and displaying it in 2D on the screen. This way you could even rotate the camera!!
> 1 votes

---
Tags: animation, isometric, rpg, vehicle
---


title: OpenGL streaming from multiple windows

text:
# Question
Title: OpenGL streaming from multiple windows
I am using GLUT library for my research/game.

In my game I have 25 windows created using `glutCreateWindow(title)`, and each of them have their own display callback registered using `glutDisplayFunc(Draw)`.

I am trying to stream the screen of each of the 25 windows on my computer to another client which will do some processing with all the screen capture of the 25 windows.

Currently I am capturing the screen of each of the 25 windows with:

```
glReadPixels(0,0,Xres,Yres,GL_RGB,GL_UNSIGNED_BYTE,pixels);

```

Just doing the call to `glReadPixels` for each of the 25 windows slows my fps down to 7 fps.

However I require the fps to be at least 25 FPS, is there any way I can improve the fps?

# Answer
I found a solution to this.

Conventional glReadPixels() blocks the pipeline and waits until all pixel data are transferred.Then, it returns control to the application.

Thus we can overcome this by making glReadPixels() asynchronous .

glReadPixels() with Pixel buffer object (PBO) can schedule asynchronous DMA transfer and returns immediately without stall.

Read more here : https://www.opengl.org/wiki/Pixel\_Buffer\_Object

For even better performance, you can even implement double or triple PBO layers.

I read through many sites and found that this site has the most detailed and easy to implement details: http://www.songho.ca/opengl/gl\_pbo.html
> 0 votes

---
Tags: opengl, frame-rate, screen-recording, streaming
---


title: Choosing Language on Mobile Game

text:
# Question
Title: Choosing Language on Mobile Game
Currently I'm trying to localize a mobile game into popular language.

Apart from technical stuff (like how to store string and including supporting fonts), I'm a bit confused about designing two things: choosing first language when they play game for the first time and changing between them

Currently, I already have several options about choosing first language:

1. Language is chosen programatically based on user's default language/font
2. Ask user on first time run to choose which language thay want
3. Just set default language to english

About changing language, is it necessary to give user the option to change language? (assuming that my localization team is really good without any flaw when localizing this mobile game)

# Answer
> 1 votes
Apart from technical issues, that's something you get to choose for yourself. There are lots of games/programs that use each of those approaches, so you have to ask yourself what gives a better UX for your users.

In my opinion:

1. Choose system language: This is my preferred choice. I dare say the vast majority of users use and expect this. Those who want a language different from the OS language are a minority, and are accustomed to changing their language in the settings menu.
2. Ask on first run: This was popular in the past when most people used the same english version of the OS (DOS anybody?). Also it's probably the easiest to implement. I don't think it's the best UX though.
3. Set default to english: Don't do this because a lot of people who could benefit from other languages would probably not even know the language is changeable. Remember that most users won't even see your settings menu. An exception could be highly technical apps, or apps that have incomplete/experimental translations, and english is a sensible default.

Also, try asking this at the UXSE instead.

# Answer
> 0 votes
You can ask for language in a new screen. And later the users can change the language when they want, i.e. in pause screen or in main menu. You are free to choice!

# Answer
> 0 votes
**There is no standard way of doing this. This is purely a marketing feature.**

The most logical way to do this would be to use the default language of the OS of the mobile device as all mobile devices have that feature. Don't ask the user.

Then in the options offer to change the language *if you want*. You could consider it a hassle, a wast of time and money as often the option will not be used.

---
Tags: game-design, mobile, localization
---


# Question
Title: Licensing and commercial game development
I am thinking about developing my game and have a few questions. I am going to use these softwares and libraries : OpenGL, Visual Studio Express, GLFW. I have publishing and selling my game in plans. So my question is: is it possible to do that with these softwares? What common licenses are there and how to understand them clearly? I haven't done much research about it but I think that people that had experience with this kind of stuff may help.

# Answer
If I have understood your question right, I believe you are asking if the tools you mentioned let you commercialize the games that you create using them.

In that case, the answer is yes. Their licenses and terms and conditions are very generous. Here's what they give you:

**When it comes to OpenGL (licenced under MIT License)**

From Wikipedia

> Copyright (c)
>
> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
>
> The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
>
> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

When it comes to **Visual Studio Express**, their terms and conditions lets you commercialize your software. From the product information page:

> Visual Studio Express products are available at no charge and may be used for commercial, production usage subject to the license terms provided with each product. For example, you can use Express for Windows to create apps that you can then submit for sale in the Windows Store.

**GLFW** From the GLFW licence page:

> Copyright © 2002-2006 Marcus Geelnard
>
> Copyright © 2006-2011 Camilla Berglund
>
> This software is provided ‘as-is’, without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
>
> Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
>
> This notice may not be removed or altered from any source distribution.

**See also**: Can I produce commercial code with Visual studio express editions? and Do you need to licence OpenGL?
> 6 votes

---
Tags: opengl, licensing, visual-studio, glfw, commercial
---


# Question
Title: How to import animations from one model to others
I have two models (one animation in each) which I got for free from Mixamo. I imported them in Unity and they look like this:

https://i.stack.imgur.com/iDZ7l.jpg

Justin@Idle and Justin@Walking.

As can be seen from the picture, they both contain only one animation (idle and walking). But in my scene I have a couple of other character models.

But I am unable to get these two animations (idle and walking) to work on any of those models at all. (I am pretty confident that they have the same skeleton, since they are coming from the same 'pack').

What are the steps I need to do in order to get these two animations to work on every character and I can trigger them by scripting in c#?

I figured out that I need to make the .fbx rig as 'Humanoid' I suppose, but since these .fbx files don't contain the animations the Animations tab does not contain anything.

This picture shows my situation: https://i.stack.imgur.com/2cLfh.jpg

I would like to write in my code something like this:

```
npcObj.GetComponent<Animation>().animation.Play("idle");

```

or

```
npcObj.GetComponent<Animation>().animation.Play("walking");

```

I tried adding the animations in an Animation component and calling them in script like this, but the model keeps having its T-pose.

Thanks to whoever can help me!

# Answer
> 1 votes
Essentially what you're looking for is Unity's Retargeting of Humanoid Animations. http://docs.unity3d.com/Manual/Retargeting.html

Basically as I understand it, as long as the rig you imported with the models/animations meets Unity's Avatar and muscle definition criteria for a humanoid character, then you should be able to use that rig and subsequent animations on other compatible models.

Additionally, you probably need to check if the free models you got from Mixamo are actually compatible with the Mecanim system in Unity. I know that some of the older Mixamo packs were actually incompatible and only worked in the older (before Unity4 I believe) Legacy animation system. If so, then you'll need to update their armatures etc in Blender or Max etc.

---
Tags: unity, animation, models
---


# Question
Title: Using collectable items to change a gameobject Unity
I’ve been working on a 2D platform side scroller. I’m rather new to Unity and C#. Basically what I’ve achieved so far is a character which can collect Logs throughout the game and those logs are stored in an inventory (a simple count variable). Those logs can then be used to increase the values of Campfires. This is where the problem starts, I’m trying to figure out how to check the currentValue of the campfire and show a different sprite animation of the fire. (As shown below)

**In short:**

> Player gathers log (count += 1) -\> if ( count \> 0 && Player collides with (or in range of) Campfire && presses E -\> Player is able to use log { call throw\_log\_animation; count -= 1; currentValue +=25%; call new fireAnimation; }
>
> if Fire = 100% -\> Player CANNOT use log. If Fire = 0% -\> Game Over.

Collectable items code:

```
using UnityEngine;
using System.Collections;

public class CollectableItems : MonoBehaviour {

    private int count;
    public GUIText countText;

    // Use this for initialization
    void Start () {
        count = 0;
        setCountText ();
    }

    // OnTriggerEnter 2D
    void OnTriggerEnter2D(Collider2D other) {
        // If gameObject comes in contact with player
        if (other.gameObject.tag == "WoodStumps") {
            other.gameObject.SetActive (false);
            count += 1;
            setCountText ();
        }

        // If player comes in contact with gameObject
        if (other.gameObject.tag == "CampFire") {
            if (count > 0) count -= 1;
            else gameObject.SendMessage("No logs");

            setCountText ();
        }

    }

    void setCountText() {
        countText.text = "Count: " + count.ToString();
    }
}

```

If anything is unclear, don’t hesitate to ask. I’m looking forward to your solutions and idea’s!

# Answer
> 1 votes
You've already got most of the setup. What you could do is just control the Campfire from the other collider inside the Collision method \[untested code\] :

```
// in CollectableItems.cs
    //...
       if (other.gameObject.tag == "CampFire") {
            if (count > 0) {
                var campfire = other.gameObject.GetComponent<CampFireController>();
                if(campfire.TryAddLog()) {
                    // remove log
                    count -= 1;
                    // increase character warmth variables etc
                }
            else {
                gameObject.SendMessage("No logs");
            }

            setCountText ();
        }
    //...

// in CampFireController.cs
public class CampFireController : MonoBehaviour {
    public bool HasFuel { get { return fuelCount > 0; } }
    public bool IsFull { get { return fuelCount >= fuelMax; } }
    public bool IsEmpty { get { return fuelCount == 0; } }

    private int fuelCount = 0f;
    private int fuelMax = 4f;

    void Start() {
        // assume 1 log from the player is consumed when creating a camp fire
        fuelCount = 0f;

        // try and burn fuel every 10 seconds
        InvokeRepeating("BurnFuel", 10f, 10f);
    }

    void Update() {

    }

    public bool TryAddLog() {
        if(! IsFull) {
            fuelCount ++;
            // change sprite fire size; increase
            return true; // we managed to add a log to the camp fire
        }
        return false; // couldn't add a log as we're full so fail out
    }

    private void BurnFuel() {
        if(HasFuel) {
            fuelCount --;
            // change sprite fire size; decrease
        } else if(IsEmpty) {
            // change sprite to no flames i.e. gone out
        }
    }
}

```

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


# Question
Title: Unity C# - My parameter 'campfireNew' does not exist (SetTrigger)
I'm trying to set a SetTrigger parameter to call a different sprite animation on a campfire. I tried this also with a boolean, yet again the same error. parameter 'campfireNew' does not exist. Anyone familiar with this issue?

```
using UnityEngine;
using System.Collections;

public class WoodBehaviour : MonoBehaviour {

    bool campfire = false;
    private int count;
    public GUIText countText;
    public int startingValue = 100; // The amount of value the fire starts the
                                    // game with.
    public int currentValue;        // The current value the fire has.
    //public Slider valueSlider;    // Reference to the UI's health bar.
    bool inTrigger = false;
    public int increaseValue = 25;  // The amount of health taken away per attack.

    Animator anim;                  // Reference to the Animator component.

    // Use this for initialization
    void Start () {

        count = 0;
        setCountText ();
        currentValue = startingValue;
        anim = GetComponent <Animator> ();
    }

    void Update () {

        if (inTrigger){

            if (Input.GetKeyDown(KeyCode.E) && count > 0){

                count -= 1;                                 // Minus one log
                currentValue += increaseValue;              // adds value
                anim.SetBool ("campfireNew", campfire);
                //  delay("200");
                setCountText ();                            // Updates HUD

                SendMessage ("PressedKey");

            }
        }
    }

    // OnTriggerEnter 2D
    void OnTriggerEnter2D(Collider2D other) {

        // If gameObject comes in contact with player
        if (other.gameObject.tag == "WoodStumps") {
            other.gameObject.SetActive (false);
            count += 1;
            setCountText ();
        }

        // If player comes in contact with gameObject
        if (other.gameObject.tag == "CampFire") {
            inTrigger = true;
        }

    }

    void OnTriggerExit2D(Collider2D other) {
        inTrigger = false;
    }

    void setCountText() {
        countText.text = "Count: " + count.ToString();
    }
}

```

# Answer
maybe you don't get the reference to the right animator, to TEST (or DEBUG) define it public `public Animator anim;` , run the game and watch in the inspector if it has referenced the right one.

If the animator you need is attached to the same object where you attached the script it should work, but if they are not attached to the same game object it doesn't.

So if you want to access an animator of the campfire with the tag "CampFire" inside the playerscript you can do either replace: `anim = GetComponent <Animator> ();` with `anim = GameObject.FindGameObjectWithTag("campfire").GetComponent<Animator>();`;

Or also in the function

```
void OnTriggerEnter2D(Collider2D other) {

    // If gameObject comes in contact with player
    if (other.gameObject.tag == "WoodStumps") {
        other.gameObject.SetActive (false);
        count += 1;
        setCountText ();
    }

    // If player comes in contact with gameObject
    if (other.gameObject.tag == "CampFire") {
        //INSERT THE FOLLOWING LINE
        anim = other.GetComponent<Animator>();

        inTrigger = true;
    }

}

```
> 2 votes

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


# Question
Title: libGDX's 2D particle editor launching incorrectly
What's going on? Here's my process:

I first right-click the referenced library for gdx-tools.jar in Eclipse:

I then search for the particle-editor class:

It opens successfully, but half of the buttons on the right are missing and the preview panel is missing altogether.

Any ideas?

# Answer
I fixed it by updating gdx-tools.jar.

Oops.
> -1 votes

---
Tags: java, libgdx, particles
---


# Question
Title: Effects of collisons: broken glass, damaged cars, how are they created?
My question is related in particular to achieving the effects of collision in game engine, how is this done?

I have searched a bit, read from the internet and went through a few tutorials, and saw that one way to create one of the effects, explosion, or something breaking is to create the model in pieces, and apply force (in a game engine such as Unity 3D) to make the pieces fly off. It seems to be a solution, but it doesn't address the problem of items that are vaporized in a big explosion, with so many pieces. How is this done? Basic methods and tricks etc would be helpful.

Secondly, the problem of things bending and getting damaged on impact, such as a car's front end destroyed when it hits a wall? How is this done? One thing that comes into my mind is to create each component of a car in a different state as an animation in 3Ds Max or Maya, and then in the engine, according to the collision, switch the model state in the time bar. Is this how it is done?

Finally, what about materials, such as net of a basketball net, or a soccer goal net for example? Effects of ball hitting it can be calculated and applied in a script, but how to make the net bend and stretch with it? Is it done through models or materials? Also what about a flag fluttering in the wind?

My questions are specific to game engines, particularly Unity3D. Some good links on the subject would also be helpful.

# Answer
> 6 votes
I've never used Unity so I can't tell you specifically about that, but I can give you some keywords to look for. Explosions and similar effects are done with particle systems. Particles include smoke and fire done with screen-facing quads, but small meshes that look like bits of twisted metal or shards of glass, etc. can be treated as particles as well, since there can be a lot of them and they usually disappear after a short time.

Damaging an object is usually done by swapping out different pieces of geometry, like you mentioned. There's no universal term for this, although they're often called breakables. Usually these different states are created by an artist ahead of time. There are some tools, such as Havok Destruction, that do real-time, dynamic shattering or deformation in the engine. This kind of thing is expensive in performance and tricky to make work well, though. It's an area of active research at present.

Bending and stretching nets, flags, etc. are the realm of cloth simulation. Many engines include this nowadays. Internally, it's done by making a finely subdivided mesh and applying a physics simulation that treats all the vertices as being attached to their neighbors by little springs.

# Answer
> 1 votes
I want to update this considering the new shader stages recently added. Someone more familiar can probably be more thorough, but:

> such as a car's front end destroyed when it hits a wall?

The new stages allow you to more-cheaply enhance low-poly models. You *could* generate an entire vehicle from a single cube's-worth of vertices (8). Given a relatively detailed mesh of a vehicle, add a "damage map" texture. When you collide with something, write the collision to the texture. While rendering, use the calculated values as a displacement map, warping the mesh on demand, tessellating where needed. I'm willing to bet that, by now, even the collision calculations could be "rendered" entirely on the GPU.

---
Tags: unity, collision-detection, physics, graphic-effects
---


# Question
Title: Is there any case to mix Android UI with LibGDX?
my question is about creating "non-playable" screens in games with the help of native android tools.

For example, I have an Android LibGDX game (singleplatform), what should I use to provide start screen, level selection screen etc?

Is it "right" to build all screens in LibGDX only (where I know nothing about UI) - skins, scene2d...?

Or is it ok to build all in Android UI (I'm pretty familiar with that, and it seems to me more easy and fast to develop), and only use separate LibGDX Activity/Fragment where the game actually begins?

What is the common approach?

Thank you in advance! :)

# Answer
**If you just want to create a "SettingsActivity" and a kind of main menu for your game : why not, you may save time indeed.**

You can start as much custom activities as you want from an Android LibGDX project. The libgdx launcher class usually generated in templates project is just an activity. So it's technically possible to start other activities and Android screens by editing the manifest, and creating an interface with the Android project where your custom Android code will be located, so that your core project will be able to start/stop activities.

**However, i won't recommend it if you have more ambitious "UI projects" for this game or further games :**

* As a player, i usually don't expect a native Android look and feel from a game UI.
* Scene2D & Skins allows to build very customizable UI that will be much easier to visually integrate into the game.
* And of course, that won't be cross-platform (And that means you won't be able to test everything on Desktop, which can really be a workflow breaker in my own experience.)

**For these reasons, using native UI is clearly not the right way.**
> 1 votes

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


# Question
Title: (Efficiently) Generate Unique Random Numbers
Sorry my terminology is somewhat limited so I'll have to use more words to explain what I mean.

In games that require critical hits, I've heard it's not good to generate a random number but instead one should randomly pick a number from a list of possibilities then exclude that number from the next picking. This way, the dev is given more control over the player's experience.

To do this, I've been thinking somewhere along the lines of generating a random number then excluding that number from the next generation. In C#, how can I exclude a number from a random number generation? I don't think that using a while loop to continually check for another number if the currently generated one is excluded is a very efficient method, especially when most of the numbers have been excluded. Is there a built-in method to do this or some clever way to implement it?

Not: I need upwards of 100 numbers to possibly generate so hard-coding it would be tedious.

# Answer
That sounds really odd to me. This might sound like a good idea if you've got some bad/biased RNG. Another possible use case would be some game with random loot where you'd like to guarantee your player to get some special drop once every x tries rather than having a very bad streak.

However, for your own use case this doesn't sound very useful at all, considering you'll still pick your random number, which influences the number you pick.

In short: If you want no duplicates in the results (e.g. pulling random cards from a deck), then use such an approach. But for pure randomness, e.g. critical hits, this sounds counter-intuitive, especially when you care about performance.

Either way, to implement something like this you could just use a container (again: I don't think this is a good idea):

```
Random rnd = new Random();

List<int> myList(100);
for (int i = 0; i < 100; ++i)
    myList.Item[i] = i; // Or set whatever numbers you need, like card IDs

// Now to pick a random element and remove it:
int random_index = rnd.Next(0, myList.Count);
int random_element = myList.Item[random_index];
myList.RemoveAt(random_index);

```
> 2 votes

# Answer
I can see why you would want to do that, if the random number was a key seed to a sequence, having the same number twice would create the same sequence.

You could create a table to use as your randoms at program start time, then check it for duplicates, and replace with another random till every number is unique.

If you add all the numbers to a map while generating, you also could tell if some number was already added earlier by the key already being in the map. Maps use binary trees for lookup so it would be pretty fast.

Although if pregenerating the table at start time, a second pass also at start time would be faster while doing lookups.

thinking about it, you could also put numbers 1 to 1000 in a table, then just scramble the order. then go from start to end, and you would have 1000 unique randoms, although you would have to re scramble every 1000 calls to keep from same sequence repeating.

Count from 0 to 1000 in that loop Add Count number before index at rand() % currentTableSize would also create a table of 0 to 1000 scrambled numbers. and table would have zero at end, zero terminated table :)
> 1 votes

---
Tags: c#, mathematics, random
---


# Question
Title: Unity2D: Automatic scaling of camera and sprites
I'm working on a point-and-click adventure game using Unity2D for mobile devices and possible PCs and I'm trying to wrap my head around supporting devices with different screen sizes and aspect ratios.

My background images are high quality and quite large (let's say 4096 x 3072), and I'm trying to scale them down to at least fit into the viewport. However, try as I may, the scaled image always seems to end up either too large for the viewport or much too small.

I'm using an ortographic camera that automatically adjusts its size based on the current screen size using the formula `(Screen.height / 2f) / 100`.

To scale down my Sprites, I'm using the following code:

```
float scaleY = background.renderer.bounds.size.y / Globals.camera.rect.height;
float inverseY = 1/scaleY;

background.transform.localScale = new Vector3 (inverseY , inverseY);

```

This results in a background that is way too small to work with. Removing the inverse only serves to make the background massive.

Help?

# Answer
> 1 votes
I think the orthographic size of your camera should depend on the size of your sprites (and possibly on the aspect ratio of the screen), but not on the size of the screen, so that you don't need to apply any scaling to your sprites.

As a reminder, the orthographic size of the camera is the half-height of the area (in Unity world) which will be rendered on the device's screen.

For instance, if your background is 4096x3072 and you set an orthographic size of (3072 / 2) / 100 = 15.36, then your background will cover the whole height of the screen, and for the width:

* on a narrow screen you won't see the full width of the background (it will be cropped on left and right)
* on a wide screen you'll have blank are on the left & right of the background (that is pillarboxing)

If you want your background to be always fully visible and be as big as possible, then you need to change the orthographic size on narrow screens to have letterboxing (blank area on top & bottom), as explained in this blog post:

http://2sa-studio.blogspot.com/2015/01/handling-aspect-ratio-in-unity2d.html.

This is achieved with the following script (which should be attached to your camera object), where `targetAspect` should be filled with the desired aspect ratio of your game area (i.e 4096 / 3072 in your case):

```
using UnityEngine;
using System.Collections;

public class AspectRatioScript : MonoBehaviour {

    public float targetAspect;

    void Start ()
    {
        float windowAspect = (float)Screen.width / (float)Screen.height;
        float scaleHeight = windowAspect / targetAspect;
        Camera camera = GetComponent<Camera>();

        if (scaleHeight < 1.0f)
        {
            camera.orthographicSize = camera.orthographicSize / scaleHeight;
        }
    }
}

```

# Answer
> 0 votes
Depending on exactly what you are trying to achieve, I might recommend not scaling anything (either the camera or your sprites) and instead just worry about the differing aspect ratios (eg. moving things to the edges of wider screens). Things will scale to fill the screen automatically; the graphics won't be pixel-perfect anymore, but with the high-resolution displays these days, that may not matter.

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


title: Character on spherical terrain

text:
# Question
Title: Character on spherical terrain
My game is played on a big spherical world. Made up of a big spherical mesh with sphere collider, with 'gravity' at it's center (gravity for objects is controlled trough scripts).

Now if I put a ball (spherical rigid-body) on there and push it, it will just go around as expected. But when I try to add an object with character-controller and move the character it will always stand as if the gravity is pointing up, and not at the center of the big sphere.

Since there is apparently no way to rotate the character-controller component (it's made for flat worlds) What are my options for controlling my characters on this spherical world?

# Answer
Looks like the options are ...

1. Implement your own version of the rigidbody script.
2. Make your world a whole lot bigger and rotate it under the player as they move rather than rotating the player round the world.
> 1 votes

# Answer
Don't use character controller, instead of it use rigidbody+capsuleCollider and then control rotation and forces with script as Wardy stated. Here is a video that may be helpful: Video
> 0 votes

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


# Question
Title: How do I get rid of this coloured border on my sprite?
I'm working on a 2D game in Unity. My triangle sprites display in-game with a line along one of the transparent sides:

Larger view here.

You might need to zoom somewhat. It's quite obvious on the leftmost triangle.

I'm unsure where this comes from. There is no border in the PNG file. As you can see in the screenshot, the border is also present in the preview.

Where does it come from? How do I get rid of it?

# Answer
> 0 votes
I've opened the sprite from my Assets folder into photoshop. there was no border. I cut away the offending borders (which made my sprite into a 69x69 instead of 70x70).

this seems to have solved it for now.

if anyone has a similar issue and finds a better solution, please do post.

# Answer
> 0 votes
This looks like texture wrapping.

Click on the texture, open the texture inspector, and set `Wrap Mode` to `Clamp`.

# Answer
> 0 votes
I had the same problem. I've made some experiments with different types of sprites (single and maps). I've tried to add transparent border to my sprite map in Photoshop, but it didn't work. Then I separated the sprites from my sprite map. It worked for me. It seems that the problem is with sprite maps.

---
Tags: 2d, unity, sprites, rendering
---


# Question
Title: 2D Physics: What happens with torque when center of mass changes?
Novice programmer and explorer of simple 2D physics, here.

I have a simple 2D object made up of two rigid bodies connected at a fixed joint.

The two rigid objects can rotate freely about that fixed joint, causing the center of mass and moment of inertia of the whole object to change(but not adding extra energy to the system).

If my 2d object is rotating about it's center of mass, and then the center of mass changes (because one of its components rotates), what happens with the torque?

Since my torque was applied at the initial center of mass, and now the center of mass has changed, it would seem that I could not just preserve the torque for the new object orientation?

One possibility in my head is that some of that initial torque will be converted to linear velocity, but I can't visualize this in any consistent way.

So does the torque value remain the same when center of mass changes or does it need to be recalculated?

What key information am I missing here?

If there's a simple enough answer that could be expressed in some python or pseudo code (in terms of what to do with the torque), that would be appreciated.

EDIT:

I'll try to be more clear. There's no friction there's no gravity, and no ability for either of these objects to collide with anything (they are in vacuum too). The two components themselves are connected at a joint but they are effectively rigid (in the sense that torque force does not cause them to change their orientation to joint). Linear velocity starts at nothing and we apply a one time (impulse?) torque through the center of mass. The whole object rotates in the expected way when all of the sudden one of the components of the object changes its orientation(without adding any additional forces to whole object). This changes the objects center of mass and moment of inertia. Since the only force applied to this object was torque, what happens in such a hypothetical situation? I'm mostly interested in how to apply the existing energy to the new orientation. Does the object gain linear velocity and lose torque? If so how do i calculate that.

(I suppose if I were spinning in outer space and stuck out my arm, that might be along the same line?)

# Answer
It seems to me that you haven't defined enough of what is happening in your system, to know how it should move.

I.e., I think you are missing the forces involved when one of the two component objects rotates itself. In real inertial physics, nothing moves without force being applied, but it sounds like your model for the component rotation may not include those forces. It also matters whether the joint is stiff or loose. It may help to think of each component as an object, as well as declaring what force is applied where when one of them tries to rotate itself relative to their connecting point. Are they pushing themselves with thrust from some place on themselves to rotate, or are they applying force to the joint? The point where the force is applied, and the direction of force, determines the effective torque arm. The friction at the joint determines what happens between the two objects as force is applied, and whether each object has inertia relative to the other or not.

Also, is there friction with the environment as these objects rotate, or are they floating in a vacuum?
> 1 votes

# Answer
If you are trying to deduce difference in force and how it effects a single object with a change to its center of gravity, making each component of that object, a single object and then using its force to calculate any strain or pressure would seem to be the way to do it.

If you have two weights on a bar, and they rotate around the center, and then you want to change that center point of rotation, it would seem that calculating different centrifugal forces for the two different masses moving(the weights) in now different circles(different center of gravity), would give you the pressure on there connecting point the bar.

The torque at a center of a car, is equal to the opposite forces applied from the front and back of the car.

the spinning and sticking out your arm is the ice skater question, you would slow down since some of the mass is traveling a greater distance, or something like that. But to calculate it, make your arm a separate object that then applies the force through the rigid connection. The force your arm would be applying would be its inertial force.
> 1 votes

---
Tags: 2d, physics, body, torque
---


title: Collision response callback

text:
# Question
Title: Collision response callback
First at all, I'm not asking how to handle or detect collision. I already have that.

My actual situation is, I have a system collision and I detect the collisions. Every collision detected is store as a message containing the two entities colliding with some information like type of collision or something. Later, all messages is processed.

I'm trying to figure out how to implement the reaction of the entities in every collision with that message. In the game a collision can trigger an action like talking with another, change the level, kill the character, store an object, not letting go...

I don't want to hard-code the calls and methods if possible (in my ideal world,I can define even the behaviour in an xml an read from that!). My first approach is a class where I store a list of possible actions/callback functions and attach it to the entity as a component. When a collision succed, I go to the entity and depending of the collision, execute the correspond callback.

Still I don't know how to determine the callback to execute or where I must code the behaviour. Any ideas? What you think about this approach?

By the way, I'm building everything from scratch, with c++ and SFML and following the entity system approach, for educational purpose.

# Answer
> 0 votes
I'm currently on a similar development path, though not explicitly entity-based. Can't say if this is a "typical" approach, but so far seems to work. I'm managing a list of "volumes", and detecting when certain ones intersect others. (Sometimes for physics, sometimes for other kinds of triggers, like you describe.)

```
Volume *v = new Volume(dimensions and stuff)
v->setKind(23); // in case others are interested
v->canBeTouchedBy(42); // only other volumes kind 42 will be "noticed" by v
v->addGotTouchListener(volumeListener) // call me

```

And then a listener gets messages like

```
void VolumeListener::gotTouch(TouchedMessage m) {...}

class TouchedMessage {
  public:
    Volume *touchee;
    Volume *toucher;
    EMeVolumeIntersection intersection; // enum, "inside" or "partial" &c
}

```

VolumeListener is an interface with just the 1 required method. An implementation of VolumeListener can carry enough context to know what it should do for the particular kind of intersection.

I've paraphrased the code above a little; actually it can mix and match multiple listeners with particular "touched-by" kinds. And there's listeners for "got touch" and "did touch", so you can do the triggering in either direction. And one could carry additional information on the TouchedMessage, for example.

But that's the general idea I used.

---
Tags: collision-detection, entity-system, c++, callbacks
---


# Question
Title: How do I ADD gravitation to a rotation matrix?
I have ported the Matlab script from https://instruct1.cit.cornell.edu/courses/bionb441/LSystem/ to POV-Ray and everything works fine (although I'm not quite sure why). To navigate a "turtle" through space, it utilizes a 3D rotation matrix (roll/pitch/yaw).

Now I would like to add a "tropism" command to simulate gravity pulling on the elements of an L-System, similar to how Laurens Laprés LParser does, and this is where I'm stuck.

This sounds trivial maybe, but I've been hitting walls for the past week, google and dissecting Lparser source code didn't help a bit:

What operation must be performed to "add" a gravity vector to the rotation matrix, iow: how do I easily rotate x degrees towards (0, -1, 0)?

---If it is of any help, this is a simplified example of how my script performs a YAW of dA radians. The columns of the matrix are stored in three vectors hT, lT, uT. For each, macro Rup(Vector, Angle) is called and returns the new vector (column of the matrix).

Corresponding macros Rlp & Rhp for pitch and roll exist, of course. vdot(A, B) is a POV Ray function and returns the dot product of A and B.

```
#if (cmdT = "+")
            #declare hT=Rup(hT, dA);
            #declare lT=Rup(lT, dA);
            #declare uT=Rup(uT, dA);

```

---

```
#macro Rup(RotVec, Angle)
    #local RotX=vdot(RotVec, < cos(Angle),  sin(Angle),      0>);
    #local RotY=vdot(RotVec, <-sin(Angle),  cos(Angle),      0>);
    #local RotZ=vdot(RotVec, < 0,           0,               1>);
    <RotX, RotY, RotZ>
#end

```

It works perfectly, but I don't know why so I don't know what to do to add gravitation. Thanks in advance!

# Answer
Sounds like your talking about inertial force, if right go further right, that sounds like interia.

Record previous movement use that as inertia value. If rocket adds rotation of x, it will same rotation for every iteration of x time.

If you are talking about gravity, isn't that just a translation of the object some distance based on current speed * time since last computation, and where the speed is increased each tick by the formula of acceleration of gravity?

If your talking about rotating like a falling building, then part of the vector is canceled at first by the reverse force of the 'structure' holding it up(why non leaning buildings don't fall) once you find the pivot point, the force of the building holding up the weight, and the direction of gravity are added, and they move the point outward. If at 15 degree tilt, most of the force of rigidity counters most of the gravity, but some continues to push it outward. As it gets further out, the rigidity is at a different angle, and more of that force is pushing outward.

But I might not know at all what your talking about. Sounds like your trying to deduce gravity of an object that has some ridgid structure as another force.
> 1 votes

---
Tags: matrix, rotation, angles
---


# Question
Title: How do I resolve a collision of a circle with two rectangle corners?
I'm writing a simple non-physical one-circle-to-many-rectangles collision detector/resolver.

For collision detection, I'm using a very common algorithm, and it's working pretty well.

For collision resolving, once a collision is detected, I calculate the penetration vector, and reactively move the circle in the opposite direction. Once again, it is working pretty well.

However, when there are two adjacent colliders, and the circle is moving right in the place where the two colliders meet, the situation is more complex. This is a screenshot of the situation:

The white rectangles are the rectangle colliders (walls), the yellow circle is the circle collider (player), and the magenta lines are the vectors from the center of the circle to the closest point in each collider.

The problem happens when I get a collision on more than one rectangle. As you can see in the picture above, the top rectangle will have a penetration vector which is not in the direction of the normal of the entire surface, and as such will create artifacts as the circle slides through the wall, depending on how I handle it.

There are many solutions I have tried, but they all create artifacts. In particular, using any algorithm to pick only one collision and solving only for that one, may yield different solutions depending on the order in which they are evaluated, especially on cases where both collisions must clearly be chosen, like the following one:

Just for reference, these diagrams are meant to show a top-down, not a side view of the playing field.

Is there a known way to resolve such a collision correctly?

# Answer
Figuring out the correct solution to multiple collisions between overlapping (or perfectly aligned rectangles) is not trivial, and most solutions will have problems. I'm not even sure if there is an actual correct solution.

Reading this question made me think that the problem could be solved by not letting the problem exist in the first place! "The problem" being "two parallel overlapping collisions occur at the same time".

It turns out that a line segment is a special case of a rectangle, whose width happens to be 0. This means that if I have a rectangle collider, I also get a line segment collider for free (certainly, a collider optimized for line segments *can* be written too)

So instead of modeling the colliders as two almost overlapping rectangles, I model it as six line segments, where this problem does not even exist!

With line segment colliders, I also get arbitrary polygon collisions for free!

For non-overlapping rectangles, as in the second image in my question, my current solver, which iteratively calculates weighted averages of all the collisions works just fine.
> 3 votes

# Answer
I admit I've never successfully written a collision resolver, but I have a suggestion.

Your problem is that you have two valid contacts that resolve a collision between the circle and a rectangle. On their own, each contact will solve the collision, but when there are two contact occurring in the same cycle you will have to pick one. You can't apply both because that would result in the circle popping away from the surface, and picking one arbitrarily (such as the first contact to be processed) will give unexpected results.

In this situation, one of the contact vectors will remove the circle from both rectangles while the other will not. The corner contact will push the circle out of the top rectangle but will leave a small overlap with the bottom rectangle.

What you need is a contact selection / combination system. The only idea that comes to mind would be to try each contact resolution and re-check with the objects that were collided with. If one of the contacts solves the collision better than the other, then you use that contact.

I can also imagine, if for example the circle was crushed between two rectangles, that the best resolution would be to somehow combine the two vectors by weighting them relative to their penetration distance. This would most likely apply when more than one contact ties for solving the problem. That is, if the first contact resolves collision on one object but continues collision with the other object and the second contact does the opposite, you can see that both contacts leave one collision and thus tie for first place.

These are just my thoughts, there may be articles that have better solutions but I figured I'd try to help.
> 2 votes

# Answer
if you added a square collision bounding box, and had both a circle and a square as a bounding box, you could find that situation before it occurred.

The square would work like whiskers on a cat, and only if the circle could always fit through the opening, would it pass the collision test, and it would occur before any part of the circle sunk into the gap.

If that is the question you are asking.
> 0 votes

---
Tags: collision-detection, collision-resolution, aabb
---