# Question
Title: How to randomly place rectangle inside a larger bounding rectangle without intersecting other rectangles inside
Let us consider the case: there is an overall bounding rectangle (call this **Rb**) which contains a number of rectangles within it (call this set **SRo**). Now I would like to randomly position a new rectangle with known bounds (call this **Rn**) within the bounds of **Rb** without intersecting any of the rectangles in the set **SRo**

My current approach is rather brute force:

1. Generate random x-y coordinates for new rectangle
2. Check Rb contains Rn if it is placed at intended coordinates
3. Check Rn does not intersect any of rectangles inside set SRo

Anyone got any better idea?

# Answer
> 2 votes
Recursive subdivision is one simple and guaranteed finite-time solution, though it tends to look a little... non-uniform. The end result is reminiscent a bit of a mondrian painting and doesn't look exactly like random scattered rectangles. If that's still good enough for you, the algorithm is:

```
makeRects(x, y, width, height)
    if shouldSubdivide(width * height) then
        // pick which way to split it, tend towards making
        // the resulting pieces closer to square
        if random(width + height) < width then
            // split vertically
            var split = random(width)
            makeRects(x, y, split, height)
            makeRects(x + split, y, width - split, height)
        else
            // split horizontally
            var split = random(height)
            makeRects(x, y, width, split)
            makeRects(x, y + split, width, height - split)
        end
    else
        // not splitting the box, so just draw a rectangle inside it
        randomRect(x, y, width, height)
    end
end

// randomly inset the rect within the given bounds
randomRect(x, y, width, height)
    var insetWidth = random(width)
    var insetHeight = random(height)
    var insetX = random(width - insetWidth)
    var insetY = random(height - insetHeight)
    placeRect(x, y, width, height)
end

// determine if a rect of the given area should be
// subdivided, or if its small enough that we should
// stop here
shouldSubdivide(area)
    // return true or false. the smaller the area, the more
    // likely to be false. tune to taste...
end

random(max)
    // generate random value between 0 and max...
end

placeRect(x, y, width, height)
    // do whatever you want here to place the rect...
end

```

# Answer
> 2 votes
This sounds similar to a collision-detection problem. Look at "spacial partitioning" to sub-divide **Rb**, and find the set of open spaces in which **Rn** would fit. Randomly select one of those spaces, and place **Rn** randomly within it.

# Answer
> 2 votes
If don't run that algorithm too often (eg. just at startup-time) and there aren't thousands of rectangles, I'd probably just stick with the brute-force approach.

You could already eliminate a lot of unnecessary trial/error attempts, by combining step 1 and 2 into one step. To do this, just make sure you generate random `x` and `y` coordinates that are guaranteed to be inside **Rb**.

Example in pseudo-code, assumes that random() returns a value from 0-1 and that y-axis points down (screen-space).

```
y = Rb.minY + (random() * (Rb.height - Rn.height))
x = Rb.minX + (random() * (Rb.width - Rn.width))

```

Then check the rectangle position against all the already placed rectangles. If it intersects another rectangle, restart at *step 1*.

Depending on the generated random-values, this approach could need a lot of tries to be successful though. An optimization would be to divide your containing rectangle (Rb) into sections and increase a counter for each section that intersects a placed rectangle. Then pick random coordinates from sections with a low "rectangle-count" in *step 1*.

If you try to place a lot of rectangles into **Rb** (so that a big part of the area of **Rb** is covered), the brute-force approach is a very bad choice, since there's a very high probability that it will fail (endless loop).

Maybe also have a look at this answer over at stackoverflow for another approach.

# Answer
> 0 votes
Sounds like a fair implementation, there is no simple trick for avoiding doing a fair amount of checking. If you have got a performance problem then show us your code, otherwise just stick with it.

# Answer
> 0 votes
Depending on the layout of rectangles already inside, if you find that brute-force is taking too many iterations (i.e. that there are too few valid spaces to put a new rectangle after some point in time), an alternative might be to iterate through the entire bounding box, making a list of all valid positions where the new smaller box can go. Then, choose a random element from that list. Worst-case O(x\*y) time, which is at least better than the random worst-case O(infinity).

# Answer
> 0 votes
I used a greedy approach:

* Rectangularize the overall (global) rectangle: create a grid from the sorted x & sorted y coordinates of all rectangles so far. So that will give you an irregular (but rectangular) grid.
* For each grid cell calculate the area, this gives you a matrix of areas.
* Use Kadanes 2D algorithm to find the sub matrix that gives you the maximum area (= the largest free rectangle)
* Place a random rectangle in that free space
* Repeat

This requires a conversion from your original coordinate space to/from the grid space but straightforward to do.

(Note that running Kadene directly on the original, global rectangle takes to long. Going via a grid approximation is plenty fast for my application)

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


# Question
Title: How to efficiently implement Dijkstra's path finding algorithm?
As per this answer: How to devise an algorithm for a person being on a walk? I tried to implement a simple path finding algorithm.

The map is 60x60 tiles total, and walkable tiles are even fewer:

(The reddish tiles are walkable and have weight of 1 (road), the greenish tiles have weight of 2 (grass), the white tiles are unwalkable)

I hoped that for such a small map there shouldn't be any performance issues. I was wrong. The game is supposed to run at 60fps. With the profiler enabled path finding can take up to 50ms! This means a few frames. Even with the profiler disabled the jitter is very visible. In this case I believe the algorithm would be unusable on any larger map. What am I doing wrong?

Here is the code for one character (The engine: RPG Maker MV):

```
GZKM.P1MomWalkMovement = function() {
    var getTileWeight = function(tagId) {
        return 1+((tagId&0x10)>>1)
    }

    $gameVariables._data[3] = $gameVariables._data[3] || {}
    var state = ($gameVariables._data[3].P1MomWalkMovement = $gameVariables._data[3].P1MomWalkMovement || {})
    state.goal = state.goal || null

    var findgoal = function() {
        var arr = []
        for(var x = 0; x < $gameMap.width(); x++) for(var y = 0; y < $gameMap.height(); y++) if($gameMap.regionId(x,y)&0x1) arr.push({x:x,y:y})
        state.goal = arr[Math.floor(Math.random()*arr.length)]
    }

    var setMomMovement = function() {
        var mom = this;

        var evs = []
        for(var x = 0; x < $gameMap.width(); x++) {
            evs[x] = []
            for(var y = 0; y < $gameMap.height(); y++) {
                evs[x][y] = []
            }
        }
        $gameMap.events().filter(function(ev){return ev.isNormalPriority() && !ev.isThrough()}).forEach(function(ev){evs[ev.x][ev.y].push(ev)})

        // Optimization attempt. RPGMaker's default checks for passability seem to be linear in the number of all events on map per tile.
        // I tried to bring this down to O(1) per tile.
        // No, I didn't profile this, b/c I don't have many events yet - but
        // I plan to have more, so I wanted to be on a safe side.
        var isCollidedWithEventsOld = Game_CharacterBase.prototype.isCollidedWithEvents;
        Game_CharacterBase.prototype.isCollidedWithEvents = function(x, y) {
            return evs[x][y].length
        }

        var h = new GZKM.Heap()
        var map = []
        for(var x = 0; x < $gameMap.width(); x++) for(var y = 0; y < $gameMap.height(); y++) if($gameMap.regionId(x,y)&0x1) if(x != mom.x || y != mom.y)
            map[[x,y]] = h.push(Infinity, {x:x,y:y})
        map[[mom.x, mom.y]] = h.push(0, {x:mom.x, y:mom.y})

        var curr; while((curr = h.pop()) !== undefined && curr.priority != Infinity && !(curr.elt.x == state.goal.x && curr.elt.y == state.goal.y)) {
            for(var d = 2; d <= 8; d+=2) { // directions
                var nx = $gameMap.roundXWithDirection(curr.elt.x, d)
                var ny = $gameMap.roundYWithDirection(curr.elt.y, d)
                if([nx,ny] in map && mom.canPass(curr.elt.x, curr.elt.y, d)) {
                    var candPriority = curr.priority + getTileWeight($gameMap.regionId(curr.elt.x,curr.elt.y))
                    if(candPriority < map[[nx,ny]].priority) {
                        h.reprioritize(map[[nx,ny]], candPriority)
                        map[[nx,ny]].elt.prev = curr
                    }
                }
            }
        }

        Game_CharacterBase.prototype.isCollidedWithEvents = isCollidedWithEventsOld;

        if(!('prev' in map[[state.goal.x, state.goal.y]].elt))
            state.goal = null
        else {
            var t = map[[state.goal.x, state.goal.y]]
            while(!(t.elt.prev.elt.x == mom.x && t.elt.prev.elt.y == mom.y))
                 t = t.elt.prev
            var dir;
            if(t.elt.x == mom.x+1) dir = 6
            else if(t.elt.x == mom.x-1) dir = 4
            else if(t.elt.y == mom.y+1) dir = 2
            else if(t.elt.y == mom.y-1) dir = 8
            this.moveStraight(dir)
        }

    }.bind(this)

    if(state.goal === null) findgoal()

    setMomMovement()
}

```

My heap implementation is here: https://codereview.stackexchange.com/questions/177124/binary-heap-priority-queue-implementation-in-javascript

What am I doing wrong? How to fix the code and remove the jitter?

Edit: Sorry, I forgot to tell you. According to the profiler the game spends an unacceptably high amount of time in `setMomMovement`. 1/2 - 1/3 of this time is the function's self time, the rest is mainly `Game_CharacterBase.canPass` (RPG Maker's function... will I have to try to optimize it even more?) Around 1-2 ms is spent in my heap implementation:

# Answer
> 3 votes
A few things jump out to me:

1. ~~Your goal selection can choose any tile as a goal, even ones that are not walkable.~~

(Oops, this is not the case, I'd just misread the method. I'll leave the remainder of this point in for others' reference)

You can terminate Dijkstra's Algorithm early when it reaches the goal, but if the goal is unreachable then it has no choice but to explore the entire reachable area trying to find some way in. Ensuring the goal is reachable should avoid this worst-case search most of the time.
2. It's been a while since I used RPGMaker (it wasn't using js back then), but it looks like you re-plan the entire path every time you need to take one step, take that step, then throw out the rest of the path and re-plan on the next update. Am I reading this right?

I understand that maintaining complex state from frame to frame is somewhat challenging in scripting environments like this, but it could be well worth the investment to cache this path so it can be re-used until it needs to be invalidated.

Even without threads, you can spread this re-planning work over multiple frames to avoid any periodic hitches whenever a new path is needed.
3. The same goes for your data structures like the passability map and heap. Re-allocating (and re-filling the passability) frequently can be a big time sink. Especially since your profiling shows gathering the passability information is one of your biggest time sinks.

Investing in a way to cache and re-use these structures instead of always re-creating them from scratch could be a big win, and might even let you have multiple agents sharing this pathfinding investment together, so you get more gameplay bang for your programming buck.
4. You can add a heuristic estimate to your Dijkstra implementation to turn it into A\*, prioritizing the direct route to the goal and spending less time exploring less-promising side branches (provided the goal is reachable)

The heuristic needn't be complicated; even a simple Manhattan distance heuristic will help.

---
Tags: javascript, performance, path-finding, rpg-maker
---


# Question
Title: Draw/"rasterize" irregular circle onto a 2D grid
I'm using the midpoint circle algorithm to choose cells on a 2D grid which outline a circle. However, I need to incorporate some random noise so that I get an irregular circle, and this method won't work anymore given how it works. Another stack exchange answer describes an equation (the "pink noise" example) I'd like to try but I'm not sure on the best approach to implement it.

I can replicate the equation via code, but I'll need to start choosing grid cells/coordinates differently and I'm not sure the best solution.

How can I "rasterize" an irregular circle like this?

# Answer
You can pretty closely simulate this with Bresenham's line algorithm. Let's say we have a function called `line(x1, y1, x2, y2)` which draws a line between `(x1, y1)` and `(x2, y2)` and the noise function:

```
private double PinkNoise(double theta)
{
    return 1 + 0.25 * (
        0.883 * Math.Sin(theta + 2 * Math.PI * 0.468) +
        0.159 / 2 * Math.Sin(2 * theta + 2 * Math.PI * 0.9) +
        0.828 / 3 * Math.Sin(3 * theta + 2 * Math.PI * 0.464) +
        0.021 / 4 * Math.Sin(4 * theta + 2 * Math.PI * 0.388) +
        0.754 / 5 * Math.Sin(5 * theta + 2 * Math.PI * 0.443)
    );
}

```

Then rasterizing this shape simply becomes iterating between 0 and 2pi, each time getting the radius for that angle and getting the to and from positions for the line function using trigonometr (`x = cos(theta), y = sin(theta)`)
> 1 votes

---
Tags: unity, c#, mathematics, grid
---


# Question
Title: Collision detection: a bunch of special cases?
I'm writing a simple physics engine in 2D. My first goal is to get collision detection working. I know that my objects will eventually be made up of primitive shapes, but I was wondering - would a collision detection library be composed of a bunch of special case functions, like "rayAndLine", "rectangleRectangle", "rectangleCircle" etc, or is there a common, underlying framework for collision detection that works regardless of which primitives are used to make the shape?

# Answer
Getting collision detection working is a great first goal for your 2D physics engine. It's good that you've decided that for now you're specifically working in 2D, as not every rule in 2D works in 3D, despite the amount of n-dimension related algorithms, at some point you have to specialize them (do a more specific variant like how cross product only satisfies the Jacobi identity in 3D).

Your question is inherently about architecture and framework design not about 2D physics, so the concern of what your building should be separate in your mind for how those pieces are used. Essentially, you need to separate the mentality of building the engine/library/framework from it's usage in another project.

**Architecting solving engines:** With any mathematics engine, we essentially want to put values into some function, and we expect the values that come out to be useful for making an interesting simulation.

The core elements of this process should be as abstract as possible while the atomic elements (smallest useful pieces of data/methods) should be specific to individual purposes and be useful to compose together. In our case nearly the only useful atomic is a 2D vector, which should be a single class of object which allows expression of an (x,y) structure, and has methods for all basic math operations that are useful for vector computations in 2D. Addition, subtraction, normalization, normal (perpendicular), cross product, dot product, magnitude/length, and whatever else you encounter that is specifically inherent to vector -\> vector operations or vector -\> real number operations. If you're using a class based language, a simple `class Vector` with each of these as a member function or operator overload would do very well.

After all atomic types are constructed, then you would compose their algorithms into another layer on top of our atomic type `Vector`. My go to's would be a `Line` and a `Curve`. We'll decide here that a `Curve` is out of scope for this and requires much specialization (the concept you refer to above as creating many special case functions). From `Vector` I would also compose a `Rectangle` as a 4 `Vector` primitive, compose `Circle` from vector using a `Vector` and a `radius`, and then I would compose a `Polygon` from `Vector` as well. `Polygon` should be made from `Vector` and not `Line` here because each line would share a duplicate point with the last line in the polygon.

Now you have shapes, but we don't know what to do with them.

**Collision Detection** Collision detection is not an exact science and there's not one single perfect algorithm (or any). There's many methods which can be used to achieve a variety of quality of effects or even have more accuracy than others. Basically though, it can be separated into a few different levels of concern and thus a few different processes.

**Broad phase collision** detection is the act of sectioning areas where we care about what might/could/does collide, and separate them for the narrow phase process. In 2D I would typically recommend using a quad tree for this. For that we'll need our `Rectangle` we built earlier and to provide it with a AABB collision detection. This stands for Axis Aligned Bounding Box and we'll use it to determin that for a non-rotating box `A` that no part of box `B` exists within `A`. It follows from the assumption that no part of `B` can exist within `A` that a collision exists if they do intersect.

A quad tree is a recursive process where you determine a maximum depth, or allow your object quantity to prevent infinite recursion depth instead. It groups physics bodies into 4 regions (hence the name) and should allow you to access each quad separately. You then would enter into each of those four quads, and perform the same process which I won't outline here for brevity but is available here: https://gamedevelopment.tutsplus.com/tutorials/quick-tip-use-quadtrees-to-detect-likely-collisions-in-2d-space--gamedev-374

**Narrow phase collision** is the process of going through your groups of shapes that we've already determined will/might/do collide and performing a more discrete collision check, at this point in time, we begin caring whether the objects are rotating or not (I won't cover this, when you get passed these collision phases look into detecting collision with angular momentum) and what shape their collision body actually is. To perform this part of the collision you would specialize your methods as you have described above (making specific functions for AABBvsCircle, OBBvsCircle, CirclevsCircle, PolygonvsPoint, PolygonvsCircle, PointvsCircle, etc.) However, these methods themselves can also be done in a layered manner as above. The key is to know what complexity of operations that you need at a given time to decide if you can use the most general form like the Separating Axis Theorem would be a great place to start for your narrow phase detection.

Your primitive separation checks are the discrete, specialized collision detection methods or general ones like SAT depending on use case and should all simply return either a true/false value, or return a relational object such as a `Manifold`, `Joint`, `CollisionObject` etc. which would have a connection with the two shapes found to be colliding, and any information about them necessary for resolving the collision, like how deep they're colliding or at what speed (what data you need in your manifold depends on what resolution method you use). That object you then pass to a `Solver` which should abstract away the differences between all of the different shapes that could collide, by only accepting a `Manifold` and not accepting any particular information about the shapes.

**Summary** The `Solver` will take the `Manifold` produced by colliding some primitive `A` with some primitive `B`, using first broad phase grouping (all vs world) and then narrow phase detection (A vs B) and if shapes are non-polygon must be specialized, the `Solver` then produces either new `Vector`s for the collided shapes positions and velocities, or an object which the `PhysicsEnvironment` or `World` can then use to resolve collision on it's children, then finally update the `QuadTree` and repeat this process on the next frame. If both colliding shapes are polygons then specialization should only be done with concerns to increased performance, otherwise simply using Separating Axis Theorem
> 9 votes

---
Tags: collision-detection
---


# Question
Title: How can I balance the traffic load of my agents over multiple paths?
I am looking for a way to distribute the load of the agents over multiple paths. Ideally, the calculation would be executed multiple times a tick.

One use case would be for traffic balancing for a set of vehicles going from point A to B. When a road gets congested, the AI would know to change path to get to the location more efficiently. Best way to visualize this is the traffic issue in every simcity-like game.

The worst case I can think of for now is to just perform A\* with a modifier attached to the cost function. I can think of ways to optimize this but it will eventually stack up.

Are there better alternatives?

# Answer
> 2 votes
Load Balancing is used confusingly here, but yes, there are path finding algorithms that consider congestion.

This answer briefly introduces Continuum Crowds algorithm that will avoid congestion, and will even prefer paths that "go with the flow" over going "against the flow."

It does not just solve how to get from A to B, as A-Star does. Instead it solves how to go from anywhere on the map, to B. The agent then just follows a gradient, which is dynamically updated as congestion changes: if a door suddenly opens, agents will change their course if it benefits them, until the doorway gets flooded, and they adapt again.

Look at the videos linked by the stackexchange answer I mentioned.

Note that for small crowd sizes, Continuum Crowds is a lot more expensive. Yet for huge crowd sizes, Continuum Crowds is much more efficient than doing many A\* paths.

---
Tags: path-finding
---


# Question
Title: Can you use a public instance variable of one class within another class(A) in c++?
A simple hypothetical example:

### `A.h`

```
using namespace std;

class A {
public:
    int m_variable = 5;
}

```

### `B.cpp`

```
include iostream>

using namespace std;

void B::method() {
    // Why do get an error stating 'invalid use of non-static data member on this line?
    int x = (A::m_variable) * 2;
    cout << x << endl;
}

```

# Answer
> 0 votes
As you've written it, no. But it is possible if you write it differently. There are a couple possible ways to do this. If you have a definition of the class `B` like this:

```
class B : public A {
    // ... whatever
};

```

In this case, `B` is an `A`, so `B` inherits all of `A`'s member variables. Since `A` declared `m_variable` as public, `B` can set it however it wishes.

Another possibility is if `B` is declared like this:

```
class B {
    // ... whatever
    private:
        A someVar;
};

```

In this case, `B` has an `A`. So `B` can access all of `A`'s public member variables. You would have to write the line in question like this:

```
int x = someVar.m_variable * 2;

```

A third option is if `A` declares `m_variable` as `static` and `public`. In this case all instances of `A` share the same copy of the `static` variable. You would have to declare `A` like this:

```
class A {
public:
    static int m_variable;
};

```

In this case, `B`'s code would work exactly as you have written it. You would access the variable via `A::m_variable`.

In your example, you're reading the variable, which is fine. Note that directly changing a `public` variable in another class would be a maintenance headache.

---
Tags: c++
---


title: Using 10 materials for one Model?

text:
# Question
Title: Using 10 materials for one Model?
I made more than 10 robots. all of them had not less than 4 materials, and some had 12 materials. I can't go back and fix this. How this will effect on the game performance later ?

# Answer
It's most likely that for every material the pipeline needs to change state and validate a lot of stuff. Which means you'd end up with a shaderpass for each material.

Depending on the scope of your game and the target you could get away with it. But if you start noticing performance issues it's best you reduce the number of materials. The fewer the better anyway.

If your materials just hold different textures : put all of those textures into one texture ( you'd have to move uv mapping though ). You could potentially reduce the materials to one this way.

If your materials take on different shaders, see if you can get the same effect with fewer shaders that takes several sampler uniforms to which you can pass different textures.
> 2 votes

---
Tags: unity, performance, materials
---


# Question
Title: Unity 2D How to prevent character from double jump
```
  private Transform m_GroundCheck;    // A position marking where to check if the player is grounded.
    const float k_GroundedRadius = .2f; // Radius of the overlap circle to determine if grounded
    private bool m_Grounded;            // Whether or not the player is grounded.
    private bool wasGrounded;
    [SerializeField] private float timeToNotGrounded = 0.3f;
    private float timeToNotGroundedTimer;
    private Transform m_CeilingCheck;   // A position marking where to check for ceilings
    const float k_CeilingRadius = .01f; // Radius of the overlap circle to determine if the player can stand up
    private Animator m_Anim;            // Reference to the player's animator component.
    private Rigidbody2D m_Rigidbody2D;
    private bool m_FacingRight = true;  // For determining which way the player is currently facing.

    private void Awake()
    {
        // Setting up references.
        m_GroundCheck = transform.Find("GroundCheck");
        m_CeilingCheck = transform.Find("CeilingCheck");
        m_Anim = GetComponent<Animator>();
        m_Rigidbody2D = GetComponent<Rigidbody2D>();
        timeToNotGroundedTimer = timeToNotGrounded;
    }

    private void FixedUpdate()
    {
        wasGrounded = false;
        // The player is grounded if a circlecast to the groundcheck position hits anything designated as ground
        // This can be done using layers instead but Sample Assets will not overwrite your project settings.
        Collider2D[] colliders = Physics2D.OverlapCircleAll(m_GroundCheck.position, k_GroundedRadius, m_WhatIsGround);
        for (int i = 0; i < colliders.Length; i++)
        {
            if (colliders [i].gameObject != gameObject)
            {
                m_Grounded = true;
                wasGrounded = true;
                timeToNotGroundedTimer = timeToNotGrounded;
            }
        }

        if (!wasGrounded)
        {
            timeToNotGroundedTimer -= Time.fixedDeltaTime;
            if (timeToNotGroundedTimer <= 0)
            {
                Debug.Log ("HAHAHAHA");
                m_Grounded = false;
            }
        }
        m_Anim.SetBool("Ground", m_Grounded);

        // Set the vertical animation
        m_Anim.SetFloat("vSpeed", m_Rigidbody2D.velocity.y);
    }

    public void Move(float move, bool crouch, bool jump)
    {
        // If crouching, check to see if the character can stand up
        if (!crouch && m_Anim.GetBool("Crouch"))
        {
            // If the character has a ceiling preventing them from standing up, keep them crouching
            if (Physics2D.OverlapCircle(m_CeilingCheck.position, k_CeilingRadius, m_WhatIsGround))
            {
                crouch = true;
            }
        }

        // Set whether or not the character is crouching in the animator
        m_Anim.SetBool("Crouch", crouch);

        //only control the player if grounded or airControl is turned on
        if (m_Grounded || m_AirControl)
        {
            // Reduce the speed if crouching by the crouchSpeed multiplier
            move = (crouch ? move*m_CrouchSpeed : move);

            // The Speed animator parameter is set to the absolute value of the horizontal input.
            m_Anim.SetFloat("Speed", Mathf.Abs(move));

            // Move the character
            m_Rigidbody2D.velocity = new Vector2(move*m_MaxSpeed, m_Rigidbody2D.velocity.y);

            // If the input is moving the player right and the player is facing left...
            if (move > 0 && !m_FacingRight)
            {
                // ... flip the player.
                Flip();
            }
                // Otherwise if the input is moving the player left and the player is facing right...
            else if (move < 0 && m_FacingRight)
            {
                // ... flip the player.
                Flip();
            }
        }
        if(jump) Debug.Log (m_Grounded);
        // If the player should jump...
        if (m_Grounded && jump && m_Anim.GetBool("Ground"))
        {
            // Add a vertical force to the player.
            wasGrounded = false;
            m_Grounded = false;
            m_Anim.SetBool("Ground", false);
            m_Rigidbody2D.velocity = new Vector2 (m_Rigidbody2D.velocity.x, 0);
            m_Rigidbody2D.AddForce(new Vector2(0f, m_JumpForce));
        }
    }

```

Hi Guys! :D I modified a bit PlatformerCharacter script from Standard Assets from Unity to make it possible to jump in mid air, like here : http://devmag.org.za/2011/01/18/11-tips-for-making-a-fun-platformer/ in point 4. I think everything is okey in code, but my character is double jumping and I can't realize why.

# Answer
> 0 votes
its a question that been asked a lot. if you search in internet you can find some good aproches but I count some of them here

1) make a trigger under legs of you character. define a Boolean onground variable ontriggerenter function it sets true and on ontriggerexit set it as false. so make character be able to jump only when grounded is true. you can set a layer or tag to make it only detect ground (I use this most of the times.)

2) use raycasting. raycast -transform.up with character length. when raycast is more than character length so it cant jump

3) if you use animation for jumping instead of physics like addforce you can set onground false when jump button pressed. on end of animation set it true.

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


# Question
Title: Why doesn't my character's outfit animate with the character model?
I'm very new to Unity. I'm messing around, just trying to get my bearings, but I'm having trouble getting a character model to animate with the clothes correctly. This is the asset that I'm using.

I've created a ThirdPersonController, and dropped my model into it. When I hit play, the base character moves and is animated, but the clothes stay in the default position.

The ReadMe for the asset says:

> Attaching clothing(Classes): Add the "AttachToBody" script to the clothing, the cloths must be inside the character to work.

I believe I have done this but I could be wrong. I have an error in Unity which says

> Wrong parent body

Which I can see in the code for the AttachToBody.cs

```
    if (bodyBones == null)
    {
        Debug.LogError ("Wrong parent body.");
        return;
    }

```

Could somebody help me out and tell me where I'm going wrong please?

I've attached a screenshot for reference (you'll need to open in a new tab to see the hierarchy properly).

Here is the full AttachToBody.cs script

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

/**
 * This matches the cloth movement to a character, the clothing must be inside the character.
 **/
public class AttachToBody : MonoBehaviour
{

    void Start ()
    {
        int i = 0;
        Transform rootParent = transform.root.transform;
        GameObject target;
        Transform[] bodyBones = null;
        for (i = 0; i < rootParent.GetChildCount (); i++)
        {
            target = rootParent.GetChild (i).gameObject;
            if (target.GetComponent<SkinnedMeshRenderer> () != null)
            {
                bodyBones = target.GetComponent<SkinnedMeshRenderer> ().bones;
                break;
            }
        }

        if (bodyBones == null)
        {
            Debug.LogError ("Wrong parent body.");
            return;
        }

        GameObject Attachment;

        for(i = 0; i < transform.GetChildCount(); i++)
        {
            Attachment = transform.GetChild(i).gameObject;
            if (Attachment.GetComponent<SkinnedMeshRenderer> () != null)
            {
                Attachment.GetComponent<SkinnedMeshRenderer> ().bones = bodyBones;
            }
        }
    }
}

```

So I can determine that the following line is null, but I'm not really sure what `target` is or where to go from there.

```
target.GetComponent<SkinnedMeshRenderer> () != null

```

Why doesn't my character's outfit animate with the character model?

# Answer
The relevant portion of the code is here:

```
int i;
Transform rootParent = transform.root.transform;
GameObject target;
Transform[] bodyBones = null;
for (i = 0; i < rootParent.GetChildCount (); i++)
{
    target = rootParent.GetChild (i).gameObject;
    if (target.GetComponent<SkinnedMeshRenderer> () != null)
    {
        bodyBones = target.GetComponent<SkinnedMeshRenderer> ().bones;
        break;
    }
}

```

This says it's expecting your transform hierarchy to look something like this:

* **Character root object** (this should not be parented under any other scene object)
    + Some number of child objects (sound emitters, colliders, etc)
    + **Character visual** (the GameObject with the `SkinnedMeshRenderer` component)
    + Maybe more child objects
        - Maybe some grand children
            * **Clothing object** (the one running the `AttachToBody` script)

ie. The character's skinned mesh must be a direct child of the clothing object's most distant ancestor.

Myself, I'd usually use a different style, replacing the above code with the following:

```
Transform[] bodyBones = null;
var skinnedMesh = transform.parent.GetComponentInChildren<SkinnedMeshRenderer();
if(skinnedMesh != null)
    bodyBones = skinnedMesh.bones;

```

With this, your clothing item can be:

* a direct child of the Skinned Mesh
* a sibling of the Skinned Mesh under a common direct parent
* an aunt / great aunt of the Skinned Mesh, where the direct parent of the clothing item is a grandparent or great grandparent of the Skinned Mesh

Using the clothing item's direct parent rather than its root gives you more flexibility if you want to use empty GameObjects as folders to organize your scene, or bundle together content that needs to be enabled/disabled/moved/searched as a group.
> 2 votes

# Answer
For those interested in the steps I took to fix this, here is what I did based on DMGregory's answer.

To start with, I created an entirely new character from the same asset. The hierarchy is:

```
ThirdPersonController
|--  PlayerModel
|----    CharArmature
|------      CharBaseM
|----    WarriorMale
|------       CharArmature
|--------       etc...
|------      TSM_NonSym
|------      TSM_Sym
|----    Camera

```

I created a new script to use instead of the included `AttachToBody.cs` script, as DMGregory suggested and attached this to `ThirdPersonController.PlayerModel.WarriorMale` on the `WarriorMale` object. The new script is below.

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

/**
 * This matches the cloth movement to a character, the clothing must be inside the character.
 **/
public class AttachToMesh : MonoBehaviour
{

    void Start()
    {
        int i = 0;
        Transform rootParent = transform.root.transform;
        GameObject target;
        Transform[] bodyBones = null;
        var skinnedMesh = transform.parent.GetComponentInChildren<SkinnedMeshRenderer>();
        if (skinnedMesh != null)
        {
            bodyBones = skinnedMesh.bones;
        }

        if (bodyBones == null)
        {
            Debug.LogError("Wrong parent body.");
            return;
        }

        GameObject Attachment;

        for (i = 0; i < transform.GetChildCount(); i++)
        {
            Attachment = transform.GetChild(i).gameObject;
            if (Attachment.GetComponent<SkinnedMeshRenderer>() != null)
            {
                Attachment.GetComponent<SkinnedMeshRenderer>().bones = bodyBones;
            }

        }
    }
}

```

Which caused the clothes to animate with the player model. I double checked the original script in this position (and descendants) in the hierarchy and was still unable to get it to animate, but when I used the new `AttachToMesh.cs` script, it worked perfectly, as can be seen in the screenshot below of the idle animation of my player model, rather than the default T-Shape pose.
> 0 votes

---
Tags: unity, animation, third-person-view
---


# Question
Title: How can I get the force of a collision in Love2D?
Is it possible to get the force of a collision between two objects in Love2D/Box2D? If so, how?

# Answer
> 2 votes
You have access to the b2ContactImpulse in the PostSolve callback on the b2ContactListener. The normalImpulses field on b2ContactImpulse holds an impulse applied to both bodies in the direction of the contact normal.

An impulse is calculated as a change in velocity times the mass of the object, so the normalImpulses well describes how hard the two fixtures hit each other. Given the same relative velocity between two fixtures, the greater the sum of the masses of the fixtures, the greater the normalImpulses.

An impulse is equal to a force acting on an object over a period of time, so if you need to calculate the actual force, you can divide the impulse by the frame time you passed to the Step function and you should get a reasonable assessment of the actual force acting on the two objects, though since i don't understand the inner workings of Box2D, i don't know how accurate this assessment is. If you're just interested in gauging the force of impact, not in the strict physics sense, then using an impulse is just as effective.

# Answer
> 2 votes
World:setCallbacks( beginContact, endContact, preSolve, postSolve ) may solve your problem.

The postSolve function receive two fixtures and a Contact object (https://love2d.org/wiki/Contact).

A very good article: https://love2d.org/wiki/Tutorial:PhysicsCollisionCallbacks

# Answer
> 0 votes
You can use **normalimpulse** in **postSolve()** callback.

Here's the example:

```
force = ""
function love.load()
    world = love.physics.newWorld(0, 200, true)
        world:setCallbacks(beginContact, endContact, preSolve, postSolve)

    ball = {}
        ball.b = love.physics.newBody(world, 400,200, "dynamic")
        ball.b:setMass(10)
        ball.s = love.physics.newCircleShape(50)
        ball.f = love.physics.newFixture(ball.b, ball.s)
        ball.f:setRestitution(0.4)    -- make it bouncy
        ball.f:setUserData("Ball")
    static = {}
        static.b = love.physics.newBody(world, 400,400, "static")
        static.s = love.physics.newRectangleShape(200,50)
        static.f = love.physics.newFixture(static.b, static.s)
        static.f:setUserData("Block")

    text       = ""   -- we'll use this to put info text on the screen later
    persisting = 0    -- we'll use this to store the state of repeated callback calls
end

function love.update(dt)
    world:update(dt)

    if love.keyboard.isDown("right") then
        ball.b:applyForce(1000, 0)
    elseif love.keyboard.isDown("left") then
        ball.b:applyForce(-1000, 0)
    end
    if love.keyboard.isDown("up") then
        ball.b:applyForce(0, -5000)
    elseif love.keyboard.isDown("down") then
        ball.b:applyForce(0, 1000)
    end

    if string.len(text) > 768 then    -- cleanup when 'text' gets too long
        text = ""
    end
end

function love.draw()
    love.graphics.circle("line", ball.b:getX(),ball.b:getY(), ball.s:getRadius(), 20)
    love.graphics.polygon("line", static.b:getWorldPoints(static.s:getPoints()))

    love.graphics.print(text, 10, 10)

    love.graphics.print(force, 100, 400)
end

function beginContact(a, b, coll)
    x,y = coll:getNormal()
    text = text.."\n"..a:getUserData().." colliding with "..b:getUserData().." with a vector normal of: "..x..", "..y
end

function endContact(a, b, coll)
    persisting = 0
    text = text.."\n"..a:getUserData().." uncolliding with "..b:getUserData()
end

function preSolve(a, b, coll)
    if persisting == 0 then    -- only say when they first start touching
        text = text.."\n"..a:getUserData().." touching "..b:getUserData()
    elseif persisting < 20 then    -- then just start counting
        text = text.." "..persisting
    end
    persisting = persisting + 1    -- keep track of how many updates they've been touching for
end

function postSolve(a, b, coll, normalimpulse, tangentimpulse)
    force = normalimpulse
end

```

---
Tags: physics, box2d, love2d
---


# Question
Title: Collision detection without classes, in Pygame
I am writing a game in Pygame and want to get collision detection working. The aim is that when an object hits another, the target object disappears. I want to avoid having classes for now, to keep things simple. This makes it difficult to get collision detection working, because the `Rect` method in Pygame assumes classes.

The logic I want to achieve is:

```
if object hits a target object
    target object disappears

```

What's the minimal code I'd need to achieve this?

# Answer
I think you mean you don't want to create your own classes such as:

```
class Player(pygame.sprite.Sprite):
    def __init__(self, rect, image):
        pygame.sprite.Sprite.__init__(self)
        self.rect = rect
        self.image = image

```

Which is doable, but not a very good practice. With that in mind, here's how you do it.

Create a player sprite:

```
player = pygame.sprite.Sprite()
# size is 40x40, position is 0, 0
player.rect = pygame.Rect(0, 0, 40, 40)

# image is 40x40 grey block
player.image = pygame.Surface((40, 40))
player.image.fill((60, 60, 60))

```

Then add a block sprite that the player can collect:

```
blocks = pygame.sprite.Sprite()
# size is 20x20, position is 300, 300
block.rect = pygame.Rect(300, 300, 20, 20)

# image is 20x20 green block
block.image = pygame.Surface((20, 20))
block.image.fill((60, 200, 60))

```

With two sprites, pygame.sprite.collide\_rect() can be used for collision detection:

```
if pygame.sprite.collide_rect(player, block):
    # move block to a new position
    block.rect.x = random.randint(20, 480)
    block.rect.y = random.randint(20, 480)
    print "You ate a block!"

```

The sprites can be drawn on the screen like this:

```
# topleft is the position of the top left corner of the sprite
screen.blit(block.image, block.rect.topleft)
screen.blit(player.image, player.rect.topleft)

```

Here's a fully working example.
> 2 votes

# Answer
Another approach (If you don't want to use sprite for whatever reasons) is to write your own collision detection logic. The logic will basically check if difference in x and y co-ordinates of each rect objects is within the delta. The delta is width and height of one of the objects capturing collision.

```
from math import fabs
def has_collided_with(rect1,rect2):
    deltay = fabs(rect1.centery - rect2.centery)
    deltax = fabs(rect1.centerx - rect2.centerx)
    return deltay < rect2.height and deltax < rect2.width

```
> 0 votes

---
Tags: collision-detection, python, pygame
---


# Question
Title: How can I express the result of a percentage so that it is easy to understand by the user?
I'm a professional game developer who has worked on a number of large titles but went indie a few years ago. I'm about to release my 3rd game, a real-time strategy game with a few RPG elements.

My problem is this: what is the best way to express the result of a percentage chance to a player? What I mean is, if the user has a 15% chance of succeeding at something, and the game engine uses a random number generator to generate a percentage, how would the result be shown to the user so that it is easy to understand?

The challenge I have is that if the player has a 15% of achieving something, if the random number generator generates a number between 1-15 (say, 4), then the player succeeds. But expressing this as, say, 4% / 15% just doesn't look right as conversely a lower number means success, where most players are used to "higher numbers = better".

I have thought about inverting the equation and expressing it some way as a chance of failure. So in the above example the player would have an 85% chance to fail, where the 4% would be converted to 96% and the result could be expressed as 96% / 85%, which "looks" more correct. But I just don't like the idea of expressing everything as a chance of failure, rather than a chance of success.

I have also thought of simply expressing the success chance (85%) and not showing the player the result of the random number generator, but I feel that most players would want to see the numerical result rather than simply the victory/failure condition.

I'm at a real loss here and would love to hear the views of players and other game developers alike. Even better if someone can point me to an example of a game which has solved this problem!

# Answer
> 2 votes
You can strip extra information and display everything in uniform fashion.

How about sci-fi d100 dice for everything?

> You need to roll more than 85. You have rolled .
> You need to roll more than 85. You have rolled ..
> You need to roll more than 85. You have rolled 4. Bad luck ..
>
> You need to roll more than 85. You have rolled .
> You need to roll more than 85. You have rolled ..
> You need to roll more than 85. You have rolled 86. Congratulations!

* This way player can quickly get used to seeing numbers he needs to roll.
* The dice reinforces the feeling of randomness of the result.

You don't say much about visual part of the problem - where in UI this is, how much space does it use, etc., so mockup can not be easily made.

---

Just in case - d100 dices do exist:

# Answer
> 0 votes
This can be expressed in terms of the Dungeons and Dragons mechanic, where the player must roll above a specified target number on a 20-sided die to succeed in a task. Various modifiers can be applied to the roll to simulate factors such as ease or difficulty, skill levels, environmental factors, etc.

For the specific example of 15% chance of success, this can be simulated by needing to roll above 20 but with a +3 modifier.

Advantages of this scheme include:

* Higher numbers are always better.
* A positive modifier increases the chance of a positive result.
* The degree to which 20 is exceeded can be used to simulate a degree of success.
* It's a known, proven system that players may even be familiar with.

# Answer
> 0 votes
Whilst this may only affect some uses, perhaps it would be possible to indicate the randomly generated number as a "resistance score".

To use your example:

1. The player has a 15% chance of success when performing some action on some target.
2. The target resists, because inertia, evasion, difficulty, etc.
3. You display this resistance attempt to the player.
4. The player's action succeeds when the target fails to resist.

# Answer
> 0 votes
Thanks for the replies. It seems there is no simple, straightforward way to present this information. I could possibly solve it by being more verbose in-game, but this is very awkward. Using my 4% / 15% example above it would look like:

*You have a 15% chance of success, so you need to score 85 or above to succeed. You score 96 - success!*

This makes sense to the new player but is way beyond a simple numerical display and I'm sure would get annoying for experienced players.

My solution, unfortunately, is to simply display the probability (e.g. 15%) and only show the player the outcome (success or failure) rather than the numerical result. My inspiration for this is Fallout 3, which shows the % chance of hitting a particular body part of a foe, but then only graphically displays the result of the action - it never gives you a numerical result. Sometimes, maybe, less is more :)

---
Tags: user-experience
---


# Question
Title: Why is clicking too fast giving me a missingReferenceException in Unity?
I made a small method that will quickly give the player a "flashlike" display when a sheep is killed. However clicking too fast will trigger a missingReferenceException. Because it registers the raycast a second time. Is this due to the delay on the `DestroyObject()` or something else?

```
private IEnumerator startFlashing(GameObject sheep)
{
    sheep.gameObject.GetComponent<Rigidbody>().freezeRotation = true;
    sheep.gameObject.GetComponent<Rigidbody>().velocity = Vector3.zero;
    sheep.SetActive(false);
    yield return new WaitForSeconds(theTimeBetweenFlashes);
    sheep.SetActive(true);
    DestroyObject(sheep.gameObject, 0.1f);
}

```

# Answer
> 1 votes
With the support of @DMGregory, I will post my comment as an answer :

When calling `DestroyObject` (which surely calls `Destroy`), the `sheep` object and its components (rigidbody) will turn to `true` a flag saying "I will be destroyed".

When you retrieve the Rigidbody using `GetComponent`, the function checks this flags and warns you with the message.

I advise you to define a boolean you set to `false` in the `DestroyObject` function indicating your sheep can't be clicked anymore :

```
private bool destroyInProgress = false ;

private IEnumerator startFlashing(GameObject sheep)
{
    if( destroyInProgress ) yield break ;

    sheep.gameObject.GetComponent<Rigidbody>().freezeRotation = true;
    sheep.gameObject.GetComponent<Rigidbody>().velocity = Vector3.zero;
    sheep.SetActive(false);
    yield return new WaitForSeconds(theTimeBetweenFlashes);
    sheep.SetActive(true);
    DestroyObject(sheep.gameObject, 0.1f);
    destroyInProgress = true ;
}

```

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


title: opengl does not draw points and line?

text:
# Question
Title: opengl does not draw points and line?
I'm learning OpenGL to build small games.

However, my program seems not plotting points and lines using `GL_LINE` and `GL_POINT`, but polygons are ok.

I found that there seems to be several ways to initialize opengl "context" but I don't really understand that. I was wondering whether it's the way I setup opengl context wrong?

```
#include <GL/glut.h>  // GLUT, include glu.h and gl.h

/* Global variables */
char title[] = "3D Shapes";

/* Initialize OpenGL Graphics */
void initGL() {
    glClearColor(0.0f, 0.0f, 0.0f, 1.0f); // Set background color to black and opaque
    glClearDepth(1.0f);                   // Set background depth to farthest
    glEnable(GL_DEPTH_TEST);   // Enable depth testing for z-culling
    glDepthFunc(GL_LEQUAL);    // Set the type of depth-test
    glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);  // Nice perspective corrections
}

/* Handler for window-repaint event. Called back when the window first appears and
whenever the window needs to be re-painted. */
void display() {
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Clear color and depth buffers
    glMatrixMode(GL_MODELVIEW);     // To operate on model-view matrix

                                    // Render a color-cube consisting of 6 quads with different colors
    glLoadIdentity();                 // Reset the model-view matrix
    glTranslatef(1.5f, 0.0f, -7.0f);  // Move right and into the screen
    gluLookAt(0.0, 0.0, 3.0, 0.0, 0.0, -10.0, 0.0, 1.0, 0.0);

    glBegin(GL_QUADS);                // Begin drawing the color cube with 6 quads
                                      // Top face (y = 1.0f)
                                      // Define vertices in counter-clockwise (CCW) order with normal pointing out
    glColor3f(0.0f, 1.0f, 0.0f);     // Green
    glVertex3f(1.0f, 1.0f, -1.0f);
    glVertex3f(-1.0f, 1.0f, -1.0f);
    glVertex3f(-1.0f, 1.0f, 1.0f);
    glVertex3f(1.0f, 1.0f, 1.0f);

    // Bottom face (y = -1.0f)
    glColor3f(1.0f, 0.5f, 0.0f);     // Orange
    glVertex3f(1.0f, -1.0f, 1.0f);
    glVertex3f(-1.0f, -1.0f, 1.0f);
    glVertex3f(-1.0f, -1.0f, -1.0f);
    glVertex3f(1.0f, -1.0f, -1.0f);

    // Front face  (z = 1.0f)
    glColor3f(1.0f, 0.0f, 0.0f);     // Red
    glVertex3f(1.0f, 1.0f, 1.0f);
    glVertex3f(-1.0f, 1.0f, 1.0f);
    glVertex3f(-1.0f, -1.0f, 1.0f);
    glVertex3f(1.0f, -1.0f, 1.0f);

    // Back face (z = -1.0f)
    glColor3f(1.0f, 1.0f, 0.0f);     // Yellow
    glVertex3f(1.0f, -1.0f, -1.0f);
    glVertex3f(-1.0f, -1.0f, -1.0f);
    glVertex3f(-1.0f, 1.0f, -1.0f);
    glVertex3f(1.0f, 1.0f, -1.0f);

    // Left face (x = -1.0f)
    glColor3f(0.0f, 0.0f, 1.0f);     // Blue
    glVertex3f(-1.0f, 1.0f, 1.0f);
    glVertex3f(-1.0f, 1.0f, -1.0f);
    glVertex3f(-1.0f, -1.0f, -1.0f);
    glVertex3f(-1.0f, -1.0f, 1.0f);

    // Right face (x = 1.0f)
    glColor3f(1.0f, 0.0f, 1.0f);     // Magenta
    glVertex3f(1.0f, 1.0f, -1.0f);
    glVertex3f(1.0f, 1.0f, 1.0f);
    glVertex3f(1.0f, -1.0f, 1.0f);
    glVertex3f(1.0f, -1.0f, -1.0f);
    glEnd();  // End of drawing color-cube

    glLoadIdentity();
    glLineWidth(2.5);
    glColor3f(1.0, 0.0, 0.0);
    glBegin(GL_LINES);
    glVertex3f(0.0, 0.0, 0.0);
    glVertex3f(15, 0, 0);
    glEnd();

    glLoadIdentity();
    glPointSize(3.0);
    glTranslatef(-5.0, 0.0, 0.0);
    glBegin(GL_POINTS);
    glVertex3f(0.0, 0.0, 0.0);
    glEnd();

    glFlush();
}

/* Handler for window re-size event. Called back when the window first appears and
whenever the window is re-sized with its new width and height */
void reshape(GLsizei width, GLsizei height) {  // GLsizei for non-negative integer
                                               // Compute aspect ratio of the new window
    if (height == 0) height = 1;                // To prevent divide by 0
    GLfloat aspect = (GLfloat)width / (GLfloat)height;

    // Set the viewport to cover the new window
    glViewport(0, 0, width, height);

    // Set the aspect ratio of the clipping volume to match the viewport
    glMatrixMode(GL_PROJECTION);  // To operate on the Projection matrix
    glLoadIdentity();             // Reset
                                  // Enable perspective projection with fovy, aspect, zNear and zFar
    gluPerspective(45.0f, aspect, 0.1f, 100.0f);
}

/* Main function: GLUT runs as a console application starting at main() */
int main(int argc, char** argv) {
    glutInit(&argc, argv);            // Initialize GLUT
    glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB | GLUT_DEPTH); // Enable double buffered mode
    glutInitWindowSize(640, 480);   // Set the window's initial width & height
    glutInitWindowPosition(50, 50); // Position the window's initial top-left corner
    glutCreateWindow(title);          // Create window with the given title
    glutDisplayFunc(display);       // Register callback handler for window re-paint event
    glutReshapeFunc(reshape);       // Register callback handler for window re-size event
    initGL();                       // Our own OpenGL initialization
    glutMainLoop();                 // Enter the infinite event-processing loop
    return 0;
}

```

# Answer
You're drawing your points and lines with Z = 0, but your view frustum range (set by gluPerspective) sets zNear to 0.1 and zFar to 100. So therefore your points and lines are discarded by the near clipping plane. OpenGL is just doing what you've told it to do.

To resolve: **don't set your near clipping plane to 0**: This will cause a division by 0 in your vertex transformations and mess everything up. Instead, push your points and lines in a little.

Incidentally: your context creation is mostly fine, but I would typically advise using GLUT\_DOUBLE instead of GLUT\_SINGLE and glutSwapBuffers instead of glFlush - single buffered contexts made sense in 1993 when not all hardware supported double-buffering, but nowadays the opposite is true and it's single-buffer that is going to be poorly supported.
> 5 votes

---
Tags: opengl
---


# Question
Title: What is the default audio bitrate in Unreal 4?
Maybe I'm just googling the wrong thing but what's Unreal's default audio sample rate? 44.1kHz or 48kHz? Silly simple question but thanks for helping out!

# Answer
> Unreal Engine 4 currently supports importing uncompressed little endian 16 bit wave files at any sample rate (see the chart below). For best results, it is recommended that sample rates of 44100 Hz or 22050 Hz be used.

Here is the link to the documentation if you'd like to read more: https://docs.unrealengine.com/latest/INT/Engine/Audio/Overview/index.html
> 3 votes

---
Tags: unreal-4, audio, sound, sound-effects
---


# Question
Title: How to rotate a local position offset based on a direction vector?
I'm trying to fire three raycasts in the direction of movement, from offset starting points. I'm having trouble calculating the start positions of the rays based on the direction.

As you can see in the animation, the three parallel lines in the middle overlap when moving upwards using the code below, but I want them to remain evenly spaced.

**I cannot use transform.right (up/etc)** etc because the transform is always facing the same direction by design. Instead I am using the currentDirection which is the normalized last movement velocity.

I want the lines to always be evenly spaced based on the direction the object is moving without rotating the actual transform - the problem is I don't know the math behind it and have spent last several hours trying to figure it out.

Current code:

```
Debug.DrawRay(this.transform.position, currentDirection * (avoidObjectsScanDistance + 0.05f), Color.blue, 0.09f);
Debug.DrawRay(this.transform.position + new Vector3(0, 0.1f, 0), currentDirection * (avoidObjectsScanDistance + 0.05f), Color.magenta, 0.09f);
Debug.DrawRay(this.transform.position + new Vector3(0, -0.1f, 0), currentDirection * (avoidObjectsScanDistance + 0.05f), Color.blue, 0.09f);

```

I've tried to get the position based on direction by using

```
var drawRayTopPos = currentDirection * localpos + position;

```

# Answer
> 1 votes
Since it looks like you're working in the 2D x/y plane here, you can use a cute little trick:

```
Vector3 perp = new Vector3(-currentDirection.y, currentDirection.x, 0);

```

This gives you a vector perpendicular to `currentDirection` (rotated 90 degrees about the z axis) without any trigonometric functions or quaternions required. :)

Now your three offsets can be:

```
Vector3 raySpan = currentDirection * (avoidObjectsScanDistance + 0.05f);

Debug.DrawRay(this.transform.position,
        raySpan, Color.blue, 0.09f);
Debug.DrawRay(this.transform.position + 0.1f * perp,
        raySpan, Color.blue, 0.09f);
Debug.DrawRay(this.transform.position - 0.1f * perp,
        raySpan, Color.blue, 0.09f);

```

Nice and compact. :)

In more general contexts, you can use the `Quaternion.LookRotation` method to form a quaternion that aligns forward in a particular direction, without needing to explicitly compute the angle yourself.

# Answer
> 0 votes
Answer:

```
  //find angle of direction
  float angle = Mathf.Atan2(currentDirection.y, currentDirection.x) * Mathf.Rad2Deg;
  //convert angle to rotation
  Quaternion rot = Quaternion.AngleAxis(angle, Vector3.forward);

  Debug.DrawRay(TransformPoint(transform.localPosition,
    new Vector3(0,0.3f,0), rot, 1),
    Quaternion.AngleAxis(angle, Vector3.forward) * Vector3.right,
    Color.magenta,
    0.1f);

  Debug.DrawRay(TransformPoint(transform.localPosition,
    new Vector3(0, -0.3f, 0), rot, 1),
    Quaternion.AngleAxis(angle, Vector3.forward) * Vector3.right,
    Color.magenta,
    0.1f);

//convert local to world position including rotation
Vector2 TransformPoint(Vector3 referencePoint, Vector3 p, Quaternion rot,
float scale)
{
    return referencePoint + ((rot * p) * scale);
}

```

---
Tags: unity, c#, rotation, geometry, direction
---


title: Cave lighting in Unity

text:
# Question
Title: Cave lighting in Unity
I have a cave that is inside a mountain (one mesh) that I created in Blender. I would like to make the cave quite dark inside so that either the player can light it up, or it is lit up with things such as crystals. Because I have ambient light through the scene, it's proven to be quite awkward to make it dark, and removing the ambient light kinda destroys the look.

I then played around with having a separate material for inside the cave so that I can make it darker, which kinda worked, but then I noticed a big issue with shadows.

The following images is from inside the cave far from the entrance.

The first image is with the default settings for shadow distance (in this case it was 70 in the quality settings). As you can see in the image, the shadow doesn't fill the cave because of the distance.

Second image is with the shadow distance turned up to make sure the cave is in darkness (not pitch black though, due to ambient lighting), this took the setting from 70 to around 500.

The problem with setting the distance so high, is that it causes artifacts on geometry outside the cave, which look nasty.

What's the best way to make a cave dark (doesn't need to be pitch black) without removing ambient lighting for the whole scene?

I was looking at similar art styles to what I am working on, and Grow Home (Unity) is basically where I am heading. They have caves which would be acceptable for what I need, but am not sure how they done it. As far as I know, they have dynamic lighting, as I believe there is a day / night cycle, so I don't think anything is baked.

# Answer
> 4 votes
Some information on the Grow Home/Grow Up art direction here if you're still interested :)

We relied *very* heavily on our custom Fresnel shader for... well... the entire look of the game. But it was especially important for the lighting of cave interiors. We pretty much only had one directional light in the whole game from the sun, but you're not seeing any of that here. The 'lighting' that you see in the screenshot above all comes from the Fresnel effect, which reflects the colour of the sky dome on all acute angled polys, giving you that rim-lighting effect everywhere you look.

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


# Question
Title: Relative angle in degrees between 2 lines
Could anybody help to solve this? Relative angle between 2 rays(lines) which starts from same point. They could point anywhere 360 clockwise, but angle should be always relative (just inside angle).

# Answer
Did you try even a cursory search for this? It's pretty standard vector math:

```
v1 = normalize(end1X - startX, end1Y - startY);
v2 = normalize(end2X - startX, end2Y - startY);

angle = acos(dot(v1, v2)) * 180.0/pi;

```

This will always give a value from 0 to 180, giving you the smallest positive angle clockwise or counter-clockwise.

In 2D, you can fix a rotation direction like so:

```
v1perp = (-v1.y, v1.x);

if(dot(v2, v1perp) > 0)
    angle = 360.0 - angle;

```

This will give a clockwise angle in the range 0...180 if v2 points to the right of v1, or 180...360 if v2 is pointing to the left of v1.
> 3 votes

# Answer
**The angle between two lines is the angle between direction vectors of the lines.**

Here's a formula:

You need to remove the `Z param` from the equation and then calculate your angle from the `cosine`.
> 0 votes

---
Tags: vector, angles
---


# Question
Title: Is this a good way of separating graphics from game logic?
My current architecture for me game engine looks like this, though it is not accurate:

Everything graphics related is done in by `GraphicsEngine`, and through its components, like `Material`, `Mesh`, etc). My problem is that I want to store the pointers in `RenderData`, but I have to include the `Mesh`, `Material` etc header files, which have included `glew`.

I currently change an objects material using `GetRenderer().SetMaterial("xyz")`, which sets a string in the `renderData`, to be processed by the graphics engine; then the correct pointer will be set, if it exists. This is not so modular, because the scene has graphics related files included, like `glew`. This is a problem.

My only solution is to store indices in `RenderData`. There wont be a material pointer, but instead, an index where the material is in the `GraphicsEngine`s material store. This way, `RenderData` is just a "blind" integer and string store, in which the Renderer egy the `GraphicsEngine` works.

Is this a good solution?

---

Meshes have `VertexData` members (position, normal, texture). When I call `GraphicEngine.CreateMesh()`, passing the `MeshName` and `FileName`, where should the file processing go? I use Tiny Obj Loader, and I don't know where I should include it, and call its function.

I call the function from inside `GraphicsEngine`, then I transform the returned structures to my Mesh's structure, which I pass to the Mesh's constructor. The initialised list will assign it to the corresponding member variable. Inside `Mesh`, I pass the `FileName` to the `Mesh` constructor, and let it handle it all by itself. I think the first solution is better, but I don't really know why.

Maybe using `GraphicsEngine` to "create" assets is better than `GraphicsEngine` commanding assets to "be created"; but this is just a personal feeling. Which solution is better?

# Answer
> 2 votes
A solution is only perfect if it does everything you want it to do. If you've ever made a game before, then you'll realize that nothing is perfect based on this statement, because nothing satisfies all your needs.

Now that that's out of the way, let's speak about your current approach and a different approach to solve some of your problems.

If I understand your solution correctly, then it succesfully provides a layer of abstraction over the rendering library. If this means, that you only need to include some OpenGL headers to communicate with the library, then it's fine. Gameplay programmers aren't completely incompetent, they know how to include a simple header, even if they don't know what it's used for (and even if they don't, the IDE can do that). Some rendering engines (like LibGDX) still make the programmer use OpenGL functions to do some things (like clearing the screen). However, if you're able to abstract every piece of OpenGL and anything related to rendering away from the core library, then that'd be even better.

Here comes in the event pattern. Instead of relying on components, this pattern uses completely separate objects managed by a core class and the communication is handled by messaging.

When you for instance need to render something from the core gameplay object, then instead of telling the renderer directly to do it, you just create a small data structures containing the request, put them it a container and let the other objects read it. The renderer should take this message out and complete the request. It's similar to a bulletin board. Someone posts their request, someone else finds it, takes it and completes it.

There are multiple pros to this pattern. First of all, it's completely modular. Nothing should break if you add or remove an event reader. This way if the renderer fails, then the event handler manager class can save the players progress and turn the game off safely, instead of it pulling the whole game with itself. You can also change the components if you for example change your mind and start using DirectX instead of OpenGL.

There is one big con I can think of, and that is flexibility. If you want to make every single operation possible through messaging, then you'll need to create a protocol. For example, the rendering part should take every event, that has the headers "render", "change\_material" and so on.

# Answer
> 1 votes
Indices is a good way to solve the problem as long as the `Scene` does not have to change any of the data, in which it can become quite tedious, I would even suggest actually moving the `RenderData` object to the `GraphicsEngine` and just keep an index to it in the `Object` instead.

One reason why it is good to use indices, is that you can handle memory more efficiently because it is easier, for example, to put the meshes after each other in memory which means access to them gets quicker, also you can move the data around in memory more easily. Another reason why indices are a good idea is that `Scene` gets completely agnostic for how the meshes etc. work and they can be changed without it affecting the scene in any way as long as something that does the same exists at the same index.

On the second question, I would suggest having a `MeshFactory`, a separate object dedicated to creating meshes. Having a separate factory would be good because you can more easily keep track of which files you have loaded so you don't load a file twice and also it makes it so that the `GraphicsEngine` does not have to know how the mesh loading works, only how your mesh class works and how the factory works which makes it easier to change the loading to support, for example `.fbx` files.

# Answer
> 0 votes
If you declare only pointers of `Mesh` etc. in `RenderData`'s header file, I think you can use forward declaration for them?

And to let `RenderData` store ints and strings is not a good/bad thing, I'd rather to discuss if it's suitable. And if it's designed to overcome the include thing, I don't think it is.

---

For the `Mesh` creation question, I think to let `Mesh` handle the Tiny Obj is better, i.e. I think to let `GameEngine` command the `Mesh` to be created itself is better. Just think `GameEngine` as a general, and `Mesh` etc. are soldiers. The soldiers should be responsible for firing bullets, reloading etc., the general just give the order when needed. If the general has to retrieve the bullets from the armory and replace the clip for the soldiers then it would be too much isn't it?

I know sometimes it's difficult or vague to see which responsibility belongs to the "objcet manager" or "object", but I think the "object"s should at least have some ability to take care itself. For the `Mesh` and `GameEngine` architecture again, the inner implementation like Tiny Obj should be taken care by `Mesh`. Since `GameEngine` is a rather large module, it shouldn't know such low-level details. Also if you encapsulate the details in `Mesh` then it's easy to replace or modify them, and you won't have to touch the `GameEngine` when you do so.

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


# Question
Title: Should I separate the Pathfinding info from the Tile Info class?
I have implemented A\* on a Tile Based Game, my Tile class contains a lot of info like Position, TileType, Items, Characters, etc on it. Right now that class has the Edges references(neighbours), movement cost, etc. Should I create a new Class like Node to just contains the Pathfinding related info?

# Answer
> 1 votes
This may not be a real answer (and I'm still new to stack exchange etc) but I'd still like to share my experience.

Last year I had to implement pathfinding in a small game we had to build in college. At first I was also planning on having the pathfinding details (like movement cost, etc) inside the tiles itself but after consulting with my teacher, I decided to create a node structure on top of the tiles, which would contain all the pathfinding logics.

The main argument for this was that it was prettier if I was able to separate my pathfinding from the game, without completely breaking it. And this is the case if all pathfinding-logics are in the node structure you build on-top of the actual tiles.

Might not be much of an answer but I hope this has helped in a minor way.

---
Tags: architecture, oop
---


# Question
Title: Monogame - Problem with lighting 3d mesh
I am having an issue with lighting my 3d icosphere. For some reason,the lighting appears to be coming from the correct direction (+X, -Y, -Z) but it also appears to be coming from (-X,+Y,+Z) and I have no idea why. I am not very well versed in 3D in Monogame yet, can anyone point me in the right direction of what is going on here?

EDIT:

The code for the shader

```
VertexToPixel ColoredVS(float4 inPos : POSITION, float3 inNormal : NORMAL, float4 inColor : COLOR)
{
    VertexToPixel Output = (VertexToPixel)0;
    float4x4 preViewProjection = mul(View, Projection);
    float4x4 preWorldViewProjection = mul(World, preViewProjection);

    Output.Position = mul(inPos, preWorldViewProjection);
    Output.Color = inColor;

    float3 Normal = normalize(mul(normalize(inNormal), World));
    Output.LightingFactor = 1;
    if (xEnableLighting)
        Output.LightingFactor = dot(Normal, -xLightDirection);

    return Output;
}

PixelToFrame ColoredPS(VertexToPixel PSIn)
{
    PixelToFrame Output = (PixelToFrame)0;

    Output.Color = PSIn.Color;
    Output.Color.rgb *= saturate(PSIn.LightingFactor) + xAmbient;

    return Output;
}

```

And this is for calculating normals

```
            for (int i = 0; i < Vertices.Length; i++)
                Vertices[i].Normal = new Vector3(0, 0, 0);

            for (int i = 0; i < Indices.Length; i += 3)
            {
                Vector3 p1 = Vertices[Indices[i]].Position;
                Vector3 p2 = Vertices[Indices[i + 1]].Position;
                Vector3 p3 = Vertices[Indices[i + 2]].Position;

                Vector3 v1 = p2 - p1;
                Vector3 v2 = p3 - p1;
                Vector3 normal = Vector3.Cross(v1, v2);

                normal.Normalize();

                Vertices[Indices[i]].Normal += normal;
                Vertices[Indices[i + 1]].Normal += normal;
                Vertices[Indices[i + 2]].Normal += normal;
            }

            for (int i = 0; i < Vertices.Length; i++)
                Vertices[i].Normal.Normalize();

```

# Answer
> 0 votes
The problem was being caused by the fact that I had CullMode set to None in my RasterState and so I couldn't immediately tell that my triangles were facing the wrong direction. Because triangles were being rendered I thought that they were all correctly ordered in counter-clockwise order when they were in fact not. I changed CullMode back to its original value and fixed the ordering of the vertices in my vertex array and that fixed the shading.

---
Tags: monogame, lighting, 3d-meshes
---


# Question
Title: Monogame problem with flat shading low poly terrain
I have been dabbling in 3d rendering recently and I am having a problem with the shading on the mesh I am using.

The code I am using to calculate the normals for all the triangles is as follows.

```
for (int i = 0; i < Indices.Length; i += 3)
{
    Vector3 p1 = Vertices[Indices[i]].Position;
    Vector3 p2 = Vertices[Indices[i + 1]].Position;
    Vector3 p3 = Vertices[Indices[i + 2]].Position;

    Vector3 v1 = p2 - p1;
    Vector3 v2 = p3 - p1;
    Vector3 normal = Vector3.Cross(v1, v2);

    normal.Normalize();

    Vertices[Indices[i]].Normal = normal;
    Vertices[Indices[i + 1]].Normal = normal;
    Vertices[Indices[i + 2]].Normal = normal;
}

```

None of the triangles in the mesh share vertices so that I can achieve a low polygon look. When it render's half the faces are dark and the other half look like they are correctly shaded. Does anyone have any idea what is going on here and what I may be doing incorrectly?

# Answer
> 1 votes
Some of my vertices were ordered clockwise instead of counter-clockwise and so they were being drawn upside down. I swapped all the vertices to be ordered in counter-clockwise and that fixed the issue.

---
Tags: xna, monogame, lighting, shading, low-poly
---


title: Reset animated actor's state in libgdx

text:
# Question
Title: Reset animated actor's state in libgdx
I am a complete newbie, making an app in libgdx for which I have this actor that I want to animate on button click. Here is the code for that:

```
public class Boss extends Actor {
    protected Animation animation = null;
    private float stateTime = 0;
    private float width, height;
    private Texture bossTexture;
    private boolean acting, reset;

    public Boss(Animation animation) {
        bossTexture=new Texture("calm.png");
        width=Gdx.graphics.getWidth();
        height=Gdx.graphics.getHeight();
        acting=false;
        this.animation = animation;
    }

    @Override
    public void draw(Batch batch, float parentAlpha) {
        batch.draw(bossTexture, 200, 100);
        if(acting!=false) {
            TextureRegion currentFrame = animation.getKeyFrame(stateTime);
            batch.draw(currentFrame, 200, 100);
            acting=false;
        }
        if(reset==true){
            batch.draw(bossTexture, 200, 100);
        }
    }

    @Override
    public void act(float delta)
    {
        super.act(delta);
        if(PlayScreen.slapped==true){
            acting=true;
        }
        stateTime+=delta;
    }

    public void reset()
    {
        reset=true;
        stateTime = 0;
    }
}

```

This is the workaround I have for resetting the actor to the default state, but I'm sure there must be another better way. Any suggestions?

\**UPDATE : \**

I am trying this now. package com.storm.game;

```
public class Boss extends Actor {
protected Animation animation = null;
private float stateTime = 0;
private float width, height;
private Texture bossTexture;
private boolean slapping, reset, react;
TextureRegion currentFrame;

public Boss(Animation animation) {
    bossTexture=new Texture("calm.png");
    width=Gdx.graphics.getWidth();
    height=Gdx.graphics.getHeight();
    slapping=react=reset=false;
    this.animation = animation;
    currentFrame = animation.getKeyFrame(0);
}

public void setAnimation(Animation anim){
    this.animation=anim;
}

@Override
public void draw(Batch batch, float parentAlpha) {
    if(slapping) {
        currentFrame=animation.getKeyFrame(stateTime);
        batch.draw(currentFrame, 200, 100);
        slapping=false;
        //react();
    }
    else{
        batch.draw(currentFrame, 200, 100);
    }
    if(reset){
        currentFrame=animation.getKeyFrame(0);
        batch.draw(currentFrame, 200, 100);
    }
}

@Override
public void act(float delta)
{
    super.act(delta);
    slapping=PlayScreen.slapped;
    stateTime+=delta;
}

public void reset()
{
    reset=true;
    stateTime = 0;
}

}

```

And what happens is the first frame is drawn and that frame is on the top of every other frame that is drawn in the **Slapping** condition.

Which is why, i get a glitched animation showing first frame overlaying every other frame i draw.

This is the playscreen class fom where i draw this actor on screen

```
public class PlayScreen implements Screen{

public static boolean slapped, punched;

//init variables
Punish game;

//others
Stage buttonStage;
Sprite bossSprite, backgroundSprite;
Texture bossTexture, backgroundTexture;
TextureRegion bossRegion;
Table buttonTable;
ImageButton slapButton, punchButton;
ImageButton.ImageButtonStyle slapButtonStyle, punchButtonStyle;
TextureAtlas slapButtonAtlas, bossSlapAtlas, punchButtonAtlas, bossPunchAtlas;
Skin slapSkin, punchSkin;
Animation bossSlapAnimation, bossPunchAnimation;
Boss boss;

public PlayScreen(Punish game){
    slapped=punched=false;

    this.game=game;
    buttonStage =new Stage();
    buttonTable=new Table();

    backgroundTexture=new Texture("background.jpg");
    bossTexture=new Texture("calm.png");
    backgroundSprite=new Sprite(backgroundTexture);

    slapButtonAtlas=new TextureAtlas(Gdx.files.internal("button.pack"));
    punchButtonAtlas=new TextureAtlas(Gdx.files.internal("punchButton.atlas"));
    bossSlapAtlas=new TextureAtlas(Gdx.files.internal("boss.pack"));
    bossPunchAtlas=new TextureAtlas(Gdx.files.internal("punchAnimation.pack"));

    slapSkin=new Skin();
    punchSkin=new Skin();

    //make buttons
    slapSkin.addRegions(slapButtonAtlas);
    punchSkin.addRegions(punchButtonAtlas);

    //adding style to slap button
    slapButtonStyle=new ImageButton.ImageButtonStyle();
    slapButtonStyle.down=slapSkin.getDrawable("handhit");
    slapButtonStyle.up=slapSkin.getDrawable("hand");
    slapButtonStyle.over=slapSkin.getDrawable("handhit");

    punchButtonStyle=new ImageButton.ImageButtonStyle();
    punchButtonStyle.down=punchSkin.getDrawable("punchHit");
    punchButtonStyle.up=punchSkin.getDrawable("punch");
    punchButtonStyle.over=punchSkin.getDrawable("punchHit");

    //apply style to slap button
    slapButton=new ImageButton(slapButtonStyle);
    punchButton=new ImageButton(punchButtonStyle);

    bossSlapAnimation=new Animation(1/10f, bossSlapAtlas.getRegions());
    bossPunchAnimation=new Animation(1/10f, bossPunchAtlas.getRegions());

    boss=new Boss(bossSlapAnimation);
    boss.setPosition(200,100);

    //Image img=new Image(new Texture("plus.png"));

    //make UI
    buttonTable.left().bottom();
    buttonTable.add(slapButton);
    buttonTable.row();
    buttonTable.add(punchButton);
    buttonTable.add();
    //buttonTable.setBounds(50,50,Gdx.graphics.getWidth(),Gdx.graphics.getHeight());
    buttonStage.addActor(buttonTable);
    buttonStage.addActor(boss);

    //add listeners
    slapButton.addListener(new ClickListener(){
        @Override
        public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) {
            slapped=true;
            boss.setAnimation(bossSlapAnimation);
            boss.act(Gdx.graphics.getDeltaTime());
            Gdx.app.log("debug-app", "touched slap");
            boss.reset();
            return true;
        }

        @Override
        public void touchUp(InputEvent event, float x, float y, int pointer, int button) {
            super.touchUp(event, x, y, pointer, button);
        }
    });

    punchButton.addListener(new ClickListener(){
        @Override
        public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) {
            punched=true;
            boss.setAnimation(bossPunchAnimation);
            boss.act(Gdx.graphics.getDeltaTime());
            Gdx.app.log("debug-app", "touched punch");
            boss.reset();
            return true;
        }

        @Override
        public void touchUp(InputEvent event, float x, float y, int pointer, int button) {
            super.touchUp(event, x, y, pointer, button);
        }
    });

    Gdx.input.setInputProcessor(buttonStage);

    /*bossTexture=new Texture("boss_large.png");
    bossSprite=new Sprite(bossTexture);*/
}

@Override
public void show() {

}

@Override
public void render(float delta) {

    //Gdx.gl.glClearColor(0,0,1,1);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

    game.batch.disableBlending();

    game.batch.begin();
    game.batch.draw(backgroundTexture,0,0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
    game.batch.end();

    game.batch.enableBlending();
    game.batch.begin();

    buttonStage.act();
    buttonStage.draw();

    game.batch.end();
}

@Override
public void resize(int width, int height) {
    buttonStage.getViewport().update(width, height, true);
}

@Override
public void pause() {

}

@Override
public void resume() {

}

@Override
public void hide() {

}

@Override
public void dispose() {

}
}

```

Any advises?

# Answer
I don't see big problems in your code since you don't seem to have a problem in the code logic although I'm a little confused in the `draw()` method. Still, I think you can have another small modification in the `draw()` method. Also some minor formatting. Boolean values in comparison statements don't need to be compared explicitly. They can be used as themselves.

```
public class Boss extends Actor {
    protected Animation animation = null;
    private float stateTime = 0;
    private float width, height;
    private Texture bossTexture;
    private boolean acting, reset;

    public Boss(Animation animation) {
        bossTexture=new Texture("calm.png");
        width=Gdx.graphics.getWidth();
        height=Gdx.graphics.getHeight();
        acting=false;
        this.animation = animation;
    }

    @Override
    public void draw(Batch batch, float parentAlpha) {
        if(acting) {
            TextureRegion currentFrame = animation.getKeyFrame(stateTime);
            batch.draw(currentFrame, 200, 100);
            acting=false;
        } else { // so that it don't have to draw every frame but still keeps the logic
            batch.draw(bossTexture, 200, 100);
        }
        if(reset){
            batch.draw(bossTexture, 200, 100);
        }
    }

    @Override
    public void act(float delta)
    {
        super.act(delta);
        acting = PlayScreen.slapped;
        stateTime+=delta;
    }

    public void reset()
    {
        reset=true;
        stateTime = 0;
    }
}

```
> 0 votes

# Answer
I had the 'same' problem after fading a non-looping actor. I changed the animation to loop and added

```
myActor.addAction(
  Actions.sequence(
    Actions.delay((frameDuration*framesAnimated), Actions.removeActor())));

```

this removes the actor after one loop and allows it to be reused
> 0 votes

---
Tags: android, libgdx, animation
---


# Question
Title: Animation loop finishes in 8 meters at 17 frames, how fast is it going?
So I made this model in Blender and synced its walk cycle using an animated path that was 8 meters long at 17 frames. But I don't know how to sync it when moving the model using a rigidbody.

# Answer
> 2 votes
Just multiply through:

```
(8 m) / (17 frames) * (24 frames/s)

= 192/17 m/s
= 11.2941176470588 m/s

```

Or you can enable root motion in your animation to let the animated content drive the GameObject's motion directly.

---
Tags: unity, animation, blender
---


title: Panorama from cube map without geometry

text:
# Question
Title: Panorama from cube map without geometry
Is it possible to achieve effect equivalent to looking on the cube textured from cube map from its center, but without creation of its faces (6 quads or 12 triangles)?

Say, one needed a skybox, but without the "box". There is no anything except skybox and there is no need to calculate depth of something - all the points of that skybox are always visible.

# Answer
> 2 votes
It's very easy to do this. Cube maps only need a 3d vector pointing in the looking direction. You can generate this in the shader.

What you'll need to provide as uniforms are the aspect ratio, the FOV and the cube map. You need to render a quad that fills the whole screen and give it the usual texture coordinates between 0 and 1.

First of all, let's generate the x coordinate of the vector. You need to take the u coordinate of the texture coordinates, subtract 0.5 and multiply it by aspect ratio * FOV, then put this into the cosinus function:

```
x = cos((u - 0.5) * aspectRatio * FOV)

```

The y is almost the same thing, but you won't need to multiply by the aspect ratio and you'll need to use sinus:

```
y = sin((v - 0.5) * FOV)

```

Now z should make this vector a unit vector, so x^2 + y^2 + z^2 should equal 1, so z is

```
z = √(1 - x^2 - y^2)

```

And that's the vector you need to provide to the cubemap. If you want to rotate it, then simply use a rotation matrix (if you have a 4x4 transformation matrix, then just clip it to 3x3 and use that).

However, there's absolutely no reason to use this over a simple box. 8 vertices and 36 indicies isn't much

---
Tags: opengl, shaders, cubemap, skybox
---


# Question
Title: Unity target position never stops with Vector3.SmoothDamp
I've integrated `Vector3.SmoothDamp` method to have a more fluid and native movement between the character and his camera in Unity. The camera movement is perfectly in sync with the character because both uses `SmoothDamp` to move, but the character sometimes still looking for the final position in the `x` axes.

How can I fix the problem introduced by `SmoothDamp` without remove it? The problem seems to be correlated to `targetPosition.x` which still changes but I'm not sure why because `hrxMovement` and `velocity.x` reaches `0`:

```
float movementDuration = 0.3f;
float movementSpeed = 2.5f;

void Run () {
    float hrzMovement = Input.GetAxis("Horizontal");
    Vector2 velocity = new Vector2(Vector2.right.x * movementSpeed * hrzMovement, body.velocity.y);
    Vector3 targetPosition = new Vector3(body.transform.position.x + hrzMovement, body.transform.position.y, body.transform.position.z);

    body.transform.position = Vector3.SmoothDamp(body.transform.position, targetPosition, ref transformVelocity, movementDuration);

    print("hrzMovement: " + hrzMovement + ", velocity.x: " + velocity.x + ", targetPosition.x: " + targetPosition.x);

    if (velocity.x != 0) {
        animation.SetBool("isMoving", true);
        orientationMovement = velocity.x;
    } else {
        animation.SetBool("isMoving", false);
    }

    if (orientationMovement < 0) {
        body.transform.localScale = new Vector3(-1, 1, 1);
    } else {
        body.transform.localScale = new Vector3(1, 1, 1);
    }

}

```

### Additional packages used:

I'm using Pixel Perfect Camera package, I hope this doesn't affect the code.

# Answer
I've found a solution by adding a condition which removes decimals to be easy to be reached but I loose movements precision I wouldn't loose.

```
Vector3 targetPosition = new Vector3(body.transform.position.x + hrzMovement, body.transform.position.y, body.transform.position.z);

if (Mathf.Approximately(body.transform.position.x, targetPosition.x)) {
    targetPosition = new Vector3((float)Math.Round((double)body.transform.position.x, 1), body.transform.position.y, body.transform.position.z);
}

```

Maybe there is some smartest way to keep movement precision?
> -1 votes

---
Tags: unity, animation, unityscript, tweening
---


# Question
Title: How to texture a floor so that edges have slightly different texture than the rest of the floor
When trying to create somewhat realistic environments, I often find that the edges where floor/wall/ceiling meet will have slightly different texture compared to the rest of the floor/wall/ceiling.

An example of this can be seen on this concrete walkway:  The parts of the concrete away from any walls is worn smooth by people walking across it, but it becomes lighter and rougher closer to the wall or the metal pole.

What are some techniques (general or UE4 specific) to emulate this when texturing a level?

# Answer
You can use tileable nine slices. These are textures that have 3 parts, corners, edges and a center.

(This is a scaled one, but you get the point)

So, first of all, get or create a texture that has a tileable middle and edges. Split it into 9 parts (they don't need to be equal in size), then tile the center both horizontally and vertically, the edges should tiled paralell to their direction and the corners shouldn't be tiled.
> 1 votes

---
Tags: textures, unreal-4, uv-mapping, materials
---


# Question
Title: For loop not detecting Actors in draw method. (libGDX)
**Question:** In my code, I want to draw my actors through a For Loop. However the for loop doesn't seem to detect the addActor() call or even other libGDX calls.

**Code:**

```
package com.puzzlepieces.jjstudios;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.assets.AssetManager;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.Batch;
import com.badlogic.gdx.scenes.scene2d.ui.Table;

import java.util.Random;

public class Box extends Table

{
    Texture box = new Texture(Gdx.files.internal("box.png"));
    Random rand = new Random();
    Texture test = new Texture("bomb.png");

    @Override
    public void draw(Batch batch, float parentAlpha)
    {
        super.draw(batch, parentAlpha);

        batch.draw(box, 400, 90, 900, 600);

        this.setBounds(400 , 90, 900, 600);
        this.addActor(new Bomb());

        this.setDebug(true);

        for (int i = 0; i>5; i++)
        {
            for (int a = 0; a > 9; a++)
            {
                int randomNo = rand.nextInt(2);  // Sets random value
                int est = 0;

                if (randomNo == 0)
                {
                    this.addActor(new Bomb());   //Spawns bomb if value 0
                }
                else if (randomNo == 1)
                {
                    this.addActor(new FireCracker());  //Spawns FireCracker if value 1
                }
                else if (randomNo == 2)
                {
                    this.addActor(new SteeringWheel());  //Spawns SteeringWheel if value is 2
                }
                else if (est == 1)
                {
                    batch.draw(test, 400, 90);
                }
            }
            this.row();
        }
    }
}

```

Please help me and sorry if I made some mistakes in my post as I'm a newbie

# Answer
> 1 votes
Looking at the code you do this:

```
int est = 0;

...

else if (est == 1) {
    batch.draw(test, 400, 90);
}

```

It doesn't seem like you change the `est` variable to 1. Because of this the batch will never draw.

---

Another remark: When using the `Table` class you want to use `add()` not `addActor()`. Otherwise the call to `row()` won't actually create a new row and space the actors properly.

# Answer
> 0 votes
I have updated your code so the Box will only get set to bomb cracker or wheel once when it is made by moving the loop into the constructor.

```
public class Box extends Table{

    // variable fields for this Box class
    Texture box = new Texture(Gdx.files.internal("box.png"));
    Random rand = new Random();
    Texture test = new Texture("bomb.png");

    // the constructore, called once when you make a new Box
    // e.g. something = new Box();
    public Box(){

        this.addActor(new Bomb());
        this.setDebug(true);

        for (int i = 0; i>5; i++)
        {
            for (int a = 0; a > 9; a++)
            {
                int randomNo = rand.nextInt(2);  // Sets random value
                int est = 0; // <- this is 0 so will never be 0 to match the else if check below

                if (randomNo == 0){
                    this.add(new Bomb());   //Spawns bomb if value 0
                }else if (randomNo == 1){
                    this.add(new FireCracker());  //Spawns FireCracker if value 1
                }else if (randomNo == 2){
                    this.add(new SteeringWheel());  //Spawns SteeringWheel if value is 2
                }else if (est == 1){// this will never be 1 as it is set earlier to 0
                    batch.draw(test, 400, 90);
                }
            }
            this.row();
        }
        this.pack();
    }

    // this methos is the draw method and will run once every frame.
    // this will be about 60 times per second depending on computer performance
    @Override
    public void draw(Batch batch, float parentAlpha)
    {
        super.draw(batch, parentAlpha);
        batch.draw(box, 400, 90, 900, 600);
        this.setBounds(400 , 90, 900, 600);
        batch.draw(test, 400, 90);
    }
}

```

---
Tags: java, libgdx, scene2d
---


# Question
Title: Evenly distribution of 2 or more shapes given their x and y points inside a bounding box
I have a set of dynamically shaped objects, How do I distribute them evenly either Horizontally or Vertically.The objects are surrounded by a bounding box and the objects are placed at x,y as shown.

Can anyone help me in providing the algorithm or pseudo code.

**UPDATE:** It is clear that, the shapes those stay at extremes (forming a bounded box) are kept constant and the remaining objects inside the space is distributed evenly. I used a word processing application to simulate the above example.

For 2 objects inside,

# Answer
If you have a set of bounding boxes and the first and last one shouldn't get moved, then you can create a line out of the center points of these two and line the ither center points up with it.

So, the x position of the center of a bounding box given the line defined by A and B and the y position is

```
x = (B.x - A.x) * (y - A.y) /(B.y - A.y) + A.x

```

So if you need the upper left position, then subtract half of the width from the value you calculate with this formula
> 2 votes

---
Tags: mathematics, transformation, objects, motion
---