title: Unity 2d sprite repeated as background

text:
# Question
Title: Unity 2d sprite repeated as background
I'm a web developer with over 12 years of experience and I'm moving my first steps in game development in the latest days. Specifically I'm playing with Unity and trying to understand how it works and how can I realize a 2d platform game. Currently I created a character that can be controlled with the keyboard (it moves to right, left and can jump), so far it seems more easy than I was expecting and despite I never used C# before I'm already quite comfortable. My first big concerning is about sprites and how can I create combined sprites or use an image as a repeated background. For example, let's imagine that I have a png of a brick and that I want to use it to create a wall, that can be of a variable width and height. How can I achieve that? With html/css I would simply create a class like this:

```
.wall {
    background: url(brick.png);
}

```

and by applying that class to any html element it will render a repeated background by adapting it to its container no matter how large or tall is it. In unity/C# what should I do?

So far I tried to create a new material and applied it to a cube object but the result is that the image gets stretched and sucks. I saw some example that creates N sprites programmatically by adding them one after another, but I wonder about the performance implications of this technique... for example if I have to repeat the brick 100 times I have to create 100 objects, it seems unfeasible to me! What I want to achieve is the most flexible, simple and performant way to create "shapes" with repeated background.

# Answer
> 2 votes
So, I've recently done something along these lines and I'll put this here for future use.

This is the object I use for this effect:

Here's the script that modifies the object:

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

public class SlidingSpriteBackground : MonoBehaviour
{
    public Sprite[] backgrounds;
    public RawImage backgroundRenderer;
    public float repeat = 3;
    public float slidingSpeedX = .2f, slidingSpeedY = -.2f;
    float moveByX, moveByY;
    Resolution res;
    Sprite useThis;
    float horizontalTiles, verticalTiles;
    int vTiles, hTiles;
    // Use this for initialization
    void Start()
    {
        res = Screen.currentResolution;
//this script uses a random background, you can set any kind of texture here
        System.Random rnd = new System.Random(System.DateTime.Now.Minute);
        useThis = backgrounds[rnd.Next(0, backgrounds.Length)];
//this part calculates the screen's size vs texture's size,
//so that you don't have to think about it
        horizontalTiles = (float)Screen.width / (float)(useThis.texture.width);
        verticalTiles = (float)Screen.height / (float)(useThis.texture.height);
//adds in the repeat amount you want in there
        verticalTiles = verticalTiles * repeat;
        horizontalTiles = horizontalTiles * repeat;
        backgroundRenderer.texture = useThis.texture;
        Rect uvRect = new Rect(0, 0, horizontalTiles, verticalTiles);
        backgroundRenderer.uvRect = uvRect;

    }

    // Update is called once per frame
    void Update()
    {
//moves the sprite over time. if you want this to move with the player,
//you'll need to get the player location and move it according to that.
//(it should be relatively easy, but it'll take time to implement).
            moveByX = moveByX + slidingSpeedX * Time.unscaledDeltaTime;
            moveByY = moveByY + slidingSpeedY * Time.unscaledDeltaTime;
            backgroundRenderer.uvRect = new Rect(moveByX, moveByY, horizontalTiles, verticalTiles);
//check if the screen size changed and recalculate
            if (res.height != Screen.currentResolution.height
            || res.width != Screen.currentResolution.width)
            {
                horizontalTiles = (float)Screen.width / (float)(useThis.texture.width);
                verticalTiles = (float)Screen.height / (float)(useThis.texture.height);
                verticalTiles = verticalTiles * repeat;
                backgroundRenderer.texture = useThis.texture;
                horizontalTiles = horizontalTiles * repeat;
            }
    }
}

```

And here's what it looks like in effect (unfortunately I can't upload anything bigger because it goes over the 2MB limit):

# Answer
> -2 votes
As far as I understand your problem, you can try the following.

1. Firstly, depending on the screen resolution, you have to scale the background object so that it occupies the entire space. This can be done using the something like the following code.

newWidth = Screen.width / textureSize; newHeight = Screen.height / textureSize; transform.localScale = new Vector3(newWidth * textureSize, newHeight * textureSize, 1);

The variable textureSize is the size of your sprite.

2. Secondly, while applying the texture to the background object, you can add the tiling values so that the sprite is repeated instead of being stretched. This can be done using something like this.

GetComponent().material.mainTextureScale = new Vector3(newWidth, newHeight, 1);

I hope this helps you.

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


# Question
Title: Determing winning on the server side or client side?
I am using JavaScript + Node.js+Websockets to develop a multiplayer card game. In my single game version the Win determining calculation is done on the client side (of course) with a function.

It looks something like this:

```
function(CheckWin){
if (something) {
player1 win
document.getElementById("winning").innerHTML="reason"
}
else if (something) {
player2 win
document.getElementById("winning").innerHTML="reason"
}
else if (something) {
player1 win
document.getElementById("winning").innerHTML="reason"
}

}

```

It is a bit chunky but that is how it is. So in my multiplayer game I can either:

1. When all card values are collected, the server emits all the cards value to the client side and then it will execute the function there like it was in my single game (but I heard this is not SAFE)
2. Execute the function in the server side and then emit the result to the client (but I don't know how to emit all this information, comments, winning to client with socket.io, I think socket.io can only emit limited number of value types, I am planning to emit just the Boolean value win or lose).

I am new with programming/gaming so hopefully this question is not too silly.

# Answer
> 7 votes
Hello visitors of Jindsay's Card Game Forum. Here is your friend xXx\_GameH4x0rPhilipp\_xXx with another cheat for you. Do you want to win every game? Here is a simple hack which works with every web browser:

1. Press F12
2. Click on "Debugger"
3. Select `check_win.js`
4. There is now a window with lots of programming code. Don't worry, you don't need to understand any of it. Just click on the line number 65. There should now be a little icon on it.
5. Play the game to the end.
6. When the game is over, it will seem as if the game is frozen, but it's not. The program is just paused. There should now be a little arrow next to line 65 in the code window.
7. You will notice a window with variables to the right. Look for the variable `player1Score` and change it to `999999999`
8. Press F8 to continue the game.

The game will now say that you won the game, even when you lost.

This might change a little when jindsay updates the game. When it stops working, just send me a PM and I update above instructions. When jindsay reads this, he might try to make this more complicated and the above instructions might get a bit longer. But unless he moves all the game mechanics to the server and turns the client-sided programming into nothing but a dumb input-output interface, there will always be a way to do this cheat.

Have fun!

# Answer
> 5 votes
Doing basically anything on client-side apat from the inputs is a bad idea. And believe me, if the programmers could collect inputs on the server side, so the client couldn't fake them, then they would happily do so.

Literally anyone can change the code to always register a winning condition. If they make it send it back to the server, than it's even worse.

The client shouldn't be a game, it should be a renderer to visualize the data sent by the server, every gameplay logic should be handled on server-side.

Every player is a cheater.

---
Tags: javascript, networking, node.js, websocket, card-game
---


title: How to get Flare elements?

text:
# Question
Title: How to get Flare elements?
Is it possible to get the elements or the textures of a Flare and to change them at runtime? If so, then how do I get them?

Pseudocode:

```
Flare flare = GetComponent<Flare>();
foreach (Element e in flare) {
    e.Size = 10;
    e.Color = Color.green;
}

```

Thanks in advance :)

# Answer
According to the documentation, you can't edit a flare at runtime, only in the inspector :

> ## Flare
>
> **Description**
>
> A flare asset. Read more about flares in the components reference.
>
> **The flare class has no properties. It needs to be setup up in the inspector.** You can reference flares and assign them to a Light at runtime.

```
    // Drag & Drop the flare assets here
    public Flare[] Flares;
    private LensFlare lensFlare;

    protected void Start()
    {
        // Supposing you have a LensFlare component attached
        lensFlare = GetComponent<LensFlare>();
        lensFlare.flare = Random.Range(0, Flares.Length) ;
    }

```
> 1 votes

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


title: Finding the contact point with SAT

text:
# Question
Title: Finding the contact point with SAT
The Separating Axis Theorem (SAT) makes it simple to determine the Minimum Translation Vector, i.e., the shortest vector that can separate two colliding objects. However, what I need is the vector that separates the objects along the vector that the penetrating object is moving (i.e. the contact point).

I drew a picture to help clarify. There is one box, moving from the before to the after position. In its after position, it intersects the grey polygon. SAT can easily return the MTV, which is the red vector. I am looking to calculate the blue vector.

My current solution performs a binary search between the before and after positions until the length of the blue vector is known to a certain threshold. It works but it's a very expensive calculation since the collision between shapes needs to be recalculated every loop.

Is there a simpler and/or more efficient way to find the contact point vector?

# Answer
> 7 votes
What you're talking about is fairly difficult if you structure it as first moving an object, then testing for collision, then backing off until you're out of the object. It's probably better to think of this as a *dynamic intersection test*: a moving object against a stationary object.

Luckily, separating axis tests can help you here! Here's a description of the algorithm, courtesy of Ron Levine:

> The algorithm goes like this. You work with the relative velocity vector of the two convex bodies. Projecting each of the two bodies and the relative velocity vector onto a particular separating axis at *t*₀ gives two 1-D intervals and a 1-D velocity, such that it is easy to tell whether the two intervals intersect, and if not, whether they are moving apart or moving together. If they are separated and moving apart on any of the separating axes (or, in fact, on any axis whatever), then you know that there is no future collision. If on any separating axis the two projected intervals intersect at *t*₀ or are separated and are moving together, then it is easy to compute (by two simple 1D linear expressions) the earliest future time at which the two intervals will first intersect and (assuming continuing rectilinear motion) the latest future time at which the two intervals will last intersect and begin moving apart. (If they are intersecting at *t*₀ then the earliest future intersection time is *t*₀). Do this for at most all the separating axes. If the maximum over all the axes of the earliest future intersection time is less than the minimum over all the axes of the latest future intersection time then that maximum earliest future intersection time is the exact time of first collision of the two 3D polyhedra, otherwise there is no collision in the future.

In other words, you loop through all the axes that you normally would in a static separating axis test. Instead of early-outing if you find no overlap, you keep going and check the projected *velocity* of the moving object. If it's moving away from the static object, *then* you early-out. Otherwise, you can solve for the earliest and latest time of contact fairly easily (it's one 1D interval moving towards another 1D interval). If you do that for all axes and keep the maximum of the earliest intersection time and the minimum of the latest intersection time, then you know if your moving object will hit the static object, as well as when. So you can advance your moving object exactly up to the point at which it will hit the static object.

Here's some rough and entirely unverified pseudocode for the algorithm:

```
t_min := +∞
t_max := -∞
foreach axis in potential_separating_axes
    a_min := +∞
    a_max := -∞
    foreach vertex in a.vertices
        a_min = min(a_min, vertex · axis)
        a_max = max(a_max, vertex · axis)
    b_min := +∞
    b_max := -∞
    foreach vertex in b.vertices
        b_min = min(b_min, vertex · axis)
        b_max = max(b_max, vertex · axis)
    v := b.velocity · axis
    if v > 0 then
        if a_max < b_min then
            return no_intersection
        else if (a_min < b_min < a_max) or (b_min < a_min < b_max) then
            t_min = min(t_min, (a_max - b_min) / v)
            t_max = max(t_max, 0)
        else
            t_min = min(t_min, (a_max - b_min) / v)
            t_max = max(t_max, (a_min - b_max) / v)
    else if v < 0 then
        // repeat the above case with a and b swapped
    else if v = 0 then
        if a_min < b_max and b_min < a_max then
            t_min = min(t_min, 0)
            t_max = max(t_max, 0)
        else
            return no_intersection
if t_max < t_min then
    // advance b by b.velocity * t_max
    return intersection
else
    return no_intersection

```

Here's a Gamasutra article talking about this implemented for a few different primitive tests. Note that just like SAT, this requires convex objects.

Also, this is a fair bit more complicated than a simple separating axis test. Be absolutely sure you need it before you try it. A very large number of games simply push the objects out of each other along the minimum translation vector, because they simply don't penetrate very far into each other on any given frame and it's pretty much unnoticeable visually.

# Answer
> 2 votes
You want to use polygon clipping. This is best explained with pictures, which I don't have, but this guy did, so I'll let him explain it.

https://dyn4j.org/2011/11/contact-points-using-clipping/

The contact manifold will return a point on one of the objects that is "most responsible" for the collision, not the direct point of collision. However, you don't really need that direct collision point. You can simply push the objects apart using the penetration depth and normal you already have, and use the contact manifold to apply other physical affects (make the box tumble/roll down the slope, for instance).

Note that your picture illustrates a small problem: the point on the blue vector you're asking for will not be found in any physical simulation, because that isn't actually where the box would hit. The box would hit with it's bottom-left corner somewhere further up the slope as just a small bit of the corner penetrates.

The penetration depth will be relatively small, and simply pushing the box out of the slope along the penetration normal will put the box close enough to the "correct" position to be almost unnoticeable in practice, especially if the box is going to bounce, tumble, or slide afterward anyway.

# Answer
> 0 votes
Just project the MAT Vector onto the direction Vector. The resulting Vector can be added to the Direction Vector to compensate the penetration. Project it the same way, as you do on the Axis when doing the SAT. This sets the Object exactly on the position that it touches the other object. Add a small epsilon to fight floating point problems.

# Answer
> 0 votes
There are a couple of caveats to my answer, that I will get out of the way first: It only deals with non-rotating bounding boxes. It assumes that you are trying to deal with *tunneling* issues, i.e. issues caused by objects moving at high speed.

Once you have identified the MTV, you know the edge/surface normal you need to test against. You also know the linear velocity vector of the interpenetrating object.

Once you have established that at *some point* during the frame, an intersection occurred, you can then perform binary half step operations, based on the following starting points: Identify the vertex that penetrated first during the frame:

```
vec3 vertex;
float mindot = FLT_MAX;
for ( vert : vertices )
{
    if (dot(vert, MTV) < mindot)
    {
         mindot = dot(vert, MTV);
         vertex = vert;
    }
}

```

Once you have have the vertex identified, the binary half step becomes far less expensive:

```
//mindistance is the where the reference edge/plane intersects it's own normal.
//The max dot product of all vertices in B along the MTV will get you this value.
halfstep = 1.0f;
vec3 cp = vertex;
vec3 v = A.velocity*framedurationSeconds;
float errorThreshold = 0.01f; //choose meaningful value here
//alternatively, set the while condition to be while halfstep > some minimum value
while (abs(dot(cp,normal)) > errorThreshold)
{
    halfstep*=0.5f;
    if (dot(cp,normal) < mindistance) //cp is inside the object, move backward
    {
        cp += v*(-1*halfstep);
    }
    else if ( dot(cp,normal) > mindistance) //cp is outside, move it forward
    {
        cp += v*(halfstep);
    }
}

return cp;

```

This is reasonably accurate, but will only provide a single collision point, in a single case.

The thing is, it's usually possible to tell in advance if an object will move fast enough per frame to be able to tunnel like this, so the best advice is to identify the leading vertices along velocity and do a ray test along the velocity vector. In the case of rotating objects, you will have to do some kind of binary halfstep slerp in order to assertain the correct contact point.

In most cases, though, it can be safely assumed that most objects in your scene will not move fast enough to penetrate that far in a single frame, so no half stepping is necessary, and discrete collision detection will suffice. High speed objects like bullets, which move too fast to see, can be raytraced for contact points.

Interestingly, this halfstep method can also give you the (almost) exact time that the object occurred during the frame:

```
float collisionTime = frametimeSeconds * halfstep;

```

If you are doing some kind of physics collision resolution, you can then correct the position of A by:

```
v - (v*halfstep)

```

then you can do your physics normally from there. The downside is that if the object moves reasonably fast, you will see it teleporting back along it's velocity vector.

---
Tags: collision-detection, physics, separating-axis-theorem
---


# Question
Title: Do I still need limit FPS when I have a variable timestep?
Lets say I have a simple game loop (variable timestep - but it applies also for other timesteps):

```
double lastTime = SDL_GetTicks();

while(isRunning){

    double currentTime = SDL_GetTicks();
    double elapsed = currentTime - lastTime;

    processInput();
    updateGameWorld(elapsed);
    render();

    lastTime = currentTime;
}

```

My FPS increases drastically to 4k+ and CPU to 80%+ (actually it was very simple app) and I had to limit the FPS anyway (which I think is destroying the timestep). My question is: is locking FPS necessary or I'm doing it wrong?

# Answer
> Is locking FPS necessary or am I doing it wrong?

No, locking the framerate is not *necessary*.

However, you may consider the following reasons to use a fixed timestep:

* Better consistent behaviour across all the devices. If you cap your framerate at 60 hz, and you can guarantee that your minimum specs machine can run the game at that framerate, every users will experience the same simulation.
* Most monitors are capped at 59-60hz (this is less and less true, I think). There is no point in trying to go faster.
* On devices that run on battery, more frames per second == more computation and rendering, this results in battery getting drained faster.
* I find it easier to think in fixed timestep.
> 0 votes

# Answer
Yes, you should still limit the FPS.

1. Even if you have a variable timestep, extremely short timesteps can cause weird behavior in some situations due to floating point inaccuracies.
2. Extremely high framerates can cause the GPU to overheat.
3. Rendering more frames than the human eye can perceive is simply unnecessary waste of system resources. It slows down other processes on the user's device and it will unnecessarily drain the user's battery or ramp up their electricity bill.
> 0 votes

---
Tags: game-loop, sdl2, timestep
---


# Question
Title: How to load background image in sprite class in libgdx?
How can I insert a background image in sprite class? here is my code..Thank's and advance

```
import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.Animation;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureRegion;

public class Sprite implements ApplicationListener {
// Constant rows and columns of the sprite sheet
private static final int FRAME_COLS = 5, FRAME_ROWS = 1;
// Objects used
Animation<TextureRegion> walkAnimation; // Must declare frame type (TextureRegion)
Texture walkSheet;
SpriteBatch spriteBatch;

// A variable for tracking elapsed time for the animation
float stateTime;

@Override
public void create() {
    // Load the sprite sheet as a
    walkSheet = new Texture(Gdx.files.internal("cat2.png"));
    // Use the split utility method to create a 2D array of TextureRegions. This is
    // possible because this sprite sheet contains frames of equal size and they are
    // all aligned.
    TextureRegion[][] tmp = TextureRegion.split(walkSheet,
            walkSheet.getWidth() / FRAME_COLS,
            walkSheet.getHeight() / FRAME_ROWS);

    // Place the regions into a 1D array in the correct order, starting from the top
    // left, going across first. The Animation constructor requires a 1D array.

    TextureRegion[] walkFrames = new TextureRegion[FRAME_COLS * FRAME_ROWS];
    int index = 0;
    for (int i = 0; i < FRAME_ROWS; i++) {
        for (int j = 0; j < FRAME_COLS; j++) {
            walkFrames[index++] = tmp[i][j];
        }
    }
    // Initialize the Animation with the frame interval and array of frames
    walkAnimation = new Animation<TextureRegion>(0.075f, walkFrames);

    // Instantiate a SpriteBatch for drawing and reset the elapsed animation
    // time to 0
    spriteBatch = new SpriteBatch();
    stateTime = 0f;
}

@Override
public void resize(int width, int height) {

}
@Override
public void render() {
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); // Clear screen
    stateTime += Gdx.graphics.getDeltaTime(); // Accumulate elapsed animation time

    // Get current frame of animation for the current stateTime
    TextureRegion currentFrame = walkAnimation.getKeyFrame(stateTime, true);
    spriteBatch.begin();
    spriteBatch.draw(currentFrame, 50, 50); // Draw current frame at (50, 50)
    spriteBatch.end();

}

@Override
public void pause() {

}

@Override
public void resume() {

}

@Override
public void dispose() { // SpriteBatches and Textures must always be disposed
    spriteBatch.dispose();
    walkSheet.dispose();
}

}

```

# Answer
First of all I think you should go read the libgdx wiki: https://github.com/libgdx/libgdx/wiki

To answer your question, just create a Texture with the background image and then draw it. I have written it below this text and i have inserted it in your code and marked it with bold.

```
Texture Background;
Background = new Texture(Gdx.files.internal("Background.png"));
spriteBatch.draw(Background,0,0);
Background.dispose();

```

```
import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.Animation;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureRegion;

public class Sprite implements ApplicationListener {
// Constant rows and columns of the sprite sheet
private static final int FRAME_COLS = 5, FRAME_ROWS = 1;
// Objects used
Animation walkAnimation; // Must declare frame type (TextureRegion)
Texture walkSheet;
SpriteBatch spriteBatch;
**Texture Background;**

// A variable for tracking elapsed time for the animation
float stateTime;

@Override
public void create() {
    // Load the sprite sheet as a
    walkSheet = new Texture(Gdx.files.internal("cat2.png"));
    // Use the split utility method to create a 2D array of TextureRegions. This is
    // possible because this sprite sheet contains frames of equal size and they are
    // all aligned.
    TextureRegion[][] tmp = TextureRegion.split(walkSheet,
            walkSheet.getWidth() / FRAME_COLS,
            walkSheet.getHeight() / FRAME_ROWS);

    // Place the regions into a 1D array in the correct order, starting from the top
    // left, going across first. The Animation constructor requires a 1D array.

    TextureRegion[] walkFrames = new TextureRegion[FRAME_COLS * FRAME_ROWS];
    int index = 0;
    for (int i = 0; i (0.075f, walkFrames);

    // Instantiate a SpriteBatch for drawing and reset the elapsed animation
    // time to 0
    spriteBatch = new SpriteBatch();
    stateTime = 0f;

    **Background = new Texture(Gdx.files.internal("Background.png")); //File from assets folder**
}

@Override
public void resize(int width, int height) {

}
@Override
public void render() {
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); // Clear screen
    stateTime += Gdx.graphics.getDeltaTime(); // Accumulate elapsed animation time

    // Get current frame of animation for the current stateTime
    TextureRegion currentFrame = walkAnimation.getKeyFrame(stateTime, true);
    spriteBatch.begin();
    **spriteBatch.draw(Background,0,0);**
    spriteBatch.draw(currentFrame, 50, 50); // Draw current frame at (50, 50)
    spriteBatch.end();

}

@Override
public void pause() {

}

@Override
public void resume() {

}

@Override
public void dispose() { // SpriteBatches and Textures must always be disposed
    spriteBatch.dispose();
    walkSheet.dispose();
    **Background.dispose();**
}

}

```
> 1 votes

---
Tags: libgdx, sprites
---


# Question
Title: Card game War master deck resizing when players reshuffle
I'm working on the card game "war" and I'm noticed an issue. When both players have different sized hands and one player reshuffles, the size of the master deck resizes. This is an issue because the master deck needs to stay the same size throughout the entire game so a winner can be decided on. Can anyone explain to me why and how to fix it? You'll notice it happening if you open the console and watch the log. The second time one player reshuffles, the deck gets smaller.

Fiddle

**JS**

```
var play = document.getElementById("play");
var reshuffle = document.getElementById("reshuffle");
var cardHolder = document.getElementsByClassName("cardHolder");
var wonCardsHolder = document.getElementsByClassName("wonCardsHolder");

play.onclick = function(){
    PlayGame(Player1, Player2);
}
Player = function(name, currentDeck, wonDeck){
    this.name = name;
    this.currentDeck = currentDeck;
    this.wonDeck = wonDeck;
}
Player.prototype.GetCurrentCard = function(){
    this.currentCard = this.currentDeck.shift();
}
Player.prototype.isReshuffling = false;
Deck = {
    //suits: ["Clubs", "Diamonds", "Hearts", "Spades"],
    suits: ["Spades", "Clubs"],
    cards: [14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2],
    deck: [],
    shuffledDeck: [],
    BuildDeck: function(){
        for(var suit = 0; suit < this.suits.length; suit++){
            for(var card = 0; card < this.cards.length; card++){
                this.deck.push([this.cards[card], this.suits[suit]]);
            }
        }
    },
    ShuffleDeck: function(){
        while(this.deck.length){
            var index = Math.floor(Math.random() * this.deck.length);
            this.shuffledDeck.push(this.deck.splice(index, 1)[0]);
        }
    },
    DistributeCards: function(player1Deck, player2Deck){
        for(var i = 0; i < this.shuffledDeck.length / 2; i++){
            player1Deck.push(this.shuffledDeck[i]);
            player2Deck.push(this.shuffledDeck[this.shuffledDeck.length - i - 1]);
        }
    },
    ReshuffleDeck: function(player){
        while(player.wonDeck.length){
            var index = Math.floor(Math.random() * player.wonDeck.length);
            player.currentDeck.push(player.wonDeck.splice(index, 1)[0]);
        }
        player.wonDeck = [];
    }
}
PlayGame = function(player1, player2){
    player1.GetCurrentCard();
    player2.GetCurrentCard();
    if(player1.currentCard == undefined){
        player1.isReshuffling = true;
    }
    if(player2.currentCard == undefined){
        player2.isReshuffling = true;
    }
    GoToWar = function(){
        console.log("War");
        var player1WarDeck = [];
        var player2WarDeck = [];
        player1WarDeck.push(player1.currentCard);
        player1.GetCurrentCard();
        player1WarDeck.push(player1.currentCard);
        player1.GetCurrentCard();
        player1WarDeck.push(player1.currentCard);

        player2WarDeck.push(player2.currentCard);
        player2.GetCurrentCard();
        player2WarDeck.push(player2.currentCard);
        player2.GetCurrentCard();
        player2WarDeck.push(player2.currentCard);

        if(player1WarDeck[player1WarDeck.length - 1][0] == player2WarDeck[player2WarDeck.length - 1][0]){
            console.log("Tie");
            player1.GetCurrentCard();
            player1WarDeck.push(player1.currentCard);
            player1.GetCurrentCard();
            player1WarDeck.push(player1.currentCard);

            player2.GetCurrentCard();
            player2WarDeck.push(player2.currentCard);
            player2.GetCurrentCard();
            player2WarDeck.push(player2.currentCard);
        }
        if(player1WarDeck[player1WarDeck.length - 1][0] > player2WarDeck[player2WarDeck.length - 1][0]){
            player1.wonDeck = player1.wonDeck.concat(player1WarDeck, player2WarDeck);
            console.log("Player 1 wins");
        }
        else{
            player2.wonDeck = player2.wonDeck.concat(player1WarDeck, player2WarDeck);
            console.log("Player 2 wins");
        }
    }
    if(!player1.isReshuffling && !player2.isReshuffling){
        if(player1.currentCard[0] == player2.currentCard[0]){
            GoToWar();
        }
        else if(player1.currentCard[0] > player2.currentCard[0]){
            player1.wonDeck.push(player1.currentCard);
            player1.wonDeck.push(player2.currentCard);
        }
        else{
            player2.wonDeck.push(player2.currentCard);
            player2.wonDeck.push(player1.currentCard);
        }
    }
    if(player1.isReshuffling){
        ReshuffleDeck(player1);
        player1.isReshuffling = false;
    }
    if(player2.isReshuffling){
        ReshuffleDeck(player2);
        player2.isReshuffling = false;
    }
    if(player1.currentDeck.length == 26){
        GameOver(player1);
    }
    if(player2.currentDeck.length == 26){
        GameOver(player2);
    }
    console.log(player1.currentDeck.length + player1.wonDeck.length + player2.currentDeck.length + player2.wonDeck.length)
    cardHolder[0].textContent = player1.currentCard[0] +" of " +player1.currentCard[1];
    cardHolder[1].textContent = player2.currentCard[0] +" of " +player2.currentCard[1];
    wonCardsHolder[0].textContent = player1.wonDeck.length;
    wonCardsHolder[1].textContent = player2.wonDeck.length;
}
ReshuffleDeck = function(player){
    Deck.ReshuffleDeck(player)
}
GameOver = function(player){
    console.log(player.name +" wins!");
}
Player1 = new Player("Player 1", [], []);
Player2 = new Player("Player 2", [], []);
Deck.BuildDeck();
Deck.ShuffleDeck();
Deck.DistributeCards(Player1.currentDeck, Player2.currentDeck);

```

# Answer
Your problem comes from the fact that you do

```
player1.GetCurrentCard();
player2.GetCurrentCard();

```

even in the case where you have to shuffle.

When player 1 still has cards in his hand but player 2 has none, you will discard a card from player 1 hand, then shuffle player 2 hand, then start the loop again, which means the discarded card from player 1 is lost in the process.
> 1 votes

# Answer
I found out the issue. As @realUser404 mentioned in his/her answer, the issue was in the logic. Regardless of whether the player was reshuffling or not, the play button was always getting a new card for each player, which meant, when one player was reshuffling, the player that wasn't was still playing, and therefore, discarding a card. Another issue was this block:

```
if(player1.currentCard == undefined){
    player1.isReshuffling = true;
}
if(player2.currentCard == undefined){
    player2.isReshuffling = true;
}

```

The player's hand is going to be undefined when play starts, so this was always being set to `true` the first time the `play` button was clicked, which called the `ReshuffleDeck()` function the first time. Rather than have a check on the current card, the if statements needed to be changed to:

```
if(player1.currentDeck.length == 0){
    player1.isReshuffling = true;
}
if(player2.currentDeck.length == 0){
    player2.isReshuffling = true;
}

```
> 0 votes

---
Tags: javascript
---


title: Triangle Texture Packing Problem

text:
# Question
Title: Triangle Texture Packing Problem
I'm trying to create a texture atlas where each triangle face is laid separately from each other (i.e. it is not typical mesh parameterization). In order to do this, I would have to pack the triangles into a 2D texture image. Can someone suggest a good algorithm to do this efficiently, both timely and spatially?

# Answer
Note: this algorithm is my **"empirical approach"**, I did no research paper on the topic, so chances are high that a better algorithm exists. Simply since there's no simple to retrieve algorithm it is easier for me to create my own. I assume the following stuff:

* Triangles **can be** rotate inside the atlas
* Triangles **can't be** morphed inside the atlas

You start by taking the triangle with the widest surface and by placing it in the middle of your atlas.

At each iteration you seek the next bigger triangle, and you attach it trying to match as much as possible one of its edges with unconnected edges on the atlas.

```
void AddTriangleToAtlas( Atlas atlas, Triangle triangle){

    var edges = atlas.Edges;
    Edge atlasEdge = null;
    Edge triangleEdge = null;
    float previousScore = 0;

    foreach(var edge in edges)
    {
        foreach(var triEdge in triangle.Edges)
        {
             var match_score = edge.Lenght / triEdge .Lenght;
             if(match_score > previousScore && match_score<=1)
             {
                 if( atlas.SimulateAdd( triangle, triEdge , edge))
                 {
                     // Simulation went OK! (the triangle do not intersect other triangles)
                     atlasEdge = edge;
                     triangleEdge = triEdge;
                     previousScore = atch_score;
                 }
             }
        }
    }

    // adds the triangle to the atlas, rotating it to match edges,
    // but preserving size, surface and shape.
    // NOTE THIS UPDATE THE EDGES LIST OF THE ATLAS
    // (one edge is removed, 2 are added)
    atlas.Add( tringle, triEdge, edge);
}

```

Each triangle you add, open 2 edges, so the computational cost of this algorithm is not very cheap, however you can improve it greatly by some euristics:

* You can keep a **list of edges sorted by Lenght**, so you can search only the firsto 20/30 edges.
* You can check, whenever the placement simulation fails, if it is failed by a good margin (in example the triangle was intersecting 50% of its surface with pre-existing triangles, in that case you can remove the edge from the list to avoid it is re-used for a simulation).
* edges near texture limits are automatically discarded

**Chances for optimization are many**. The algorithm in itself is not very complicated, however you need the following stuff before starting to develop it:

* An algorithm to rotate triangles and to place it over another image
* Another algorithm to check intersection between triangles (actually it can be faster, especially for small triangles, to just rotate them and then see if you are going to write to a pixel that is already occupied or not).

By using the above euristics you could basically ends up in an algorithm that is `O(n log n + p)` where n is number of triangles to be placed and p is number of pixels (total surface).

Without euristics the algorithm is `O(n^2 log n+p)`
> 0 votes

---
Tags: textures, algorithm, texture-atlas
---


# Question
Title: Game Loop delay the right way and game speed
I am a newbie game developer. I am trying to find a right way to create my game loop.

Consider following example. Simple Android Game I have a game with a simple gameplay - bouncing ball.

I want to have a control of the ball speed. Also I want my game to have the same framerate (framespeed) on all devices.

1. Where the speed logic should be implemented ? In my case I have simple ball object with a velocity vector. I can change the velocity vector properties in order to make my ball move faster or slower, am I right ?
2. The Main Loop. I have read a lot of about this part of a game. I found this article http://gameprogrammingpatterns.com/game-loop.html . And decided to use this code example

```
    double previous = getCurrentTime();
    double lag = 0.0;
    while (true)
    {
    double current = getCurrentTime();
    double elapsed = current - previous;
    previous = current;
    lag += elapsed;

    processInput();

    while (lag >= MS_PER_UPDATE)
    {
    update();
    lag -= MS_PER_UPDATE;
    }
   render();
   }

```

I have a lot of questions about this example.

I have the similar loop in my game.

```
 @Override
        public void run() {
            while (mIsRunning) {
                processGameInput();
                updateGameState();
                drawGame();
            }
        }

```

I cannot understand while `update();` is called while waiting for a constant delay ? Why not the render method ? Maybe I am missing something.

Here is how my update for the ball looks like.

```
   public void updatePosition() {
        mCenterX += mVector.x;
        mCenterY += mVector.y;
    }

```

As you could see, each time I increase the position of the ball by the value of the velocity vector.

But as can guess, in case of using the example from the article, the `update` method will be called for instance 100 times. And the `render` method only once per 100 `update` method calls. So in this case I guess, I the ball will be changing its position lagging.

My goal is to control the speed of the ball, for example from 0.1s - 2s.

How can achieve this ?

Please help to understand this topic. Any help would be highly appreciated.

# Answer
First of all, the game **main loop is not a trivial problem**, you have to understand exactly what happens before you get it wrong. Some facts:

* You don't know how long render takes
* You don't know how long game update takes

Any pre-emption on the time taken by rendering will not work, causing some stuttering, in general it is ok to have the game update with some lag compared to input collection. Unless the lag is very long, we will not notice it.

In general you want to update graphics not too fast (because anyway you can get only 60 to 100 images displayed on the screen every frame).

You also want your game to update as often as necessary, physical simulations usually have to be updated in fixed time steps, while you want your game to process to all inputs.

Rendering is updated accordign to values computed in your game update. Basically you want your game update to last as few as possible ( \< 10 ms) so you can update graphics according to it.

**AND you want to be frame rate indipendent:**

> Basically you have just to measure time elapsed since last update, and use it in your update functions.

I'm not suprised that important piece is missing in the link you provided (since that site also missed important points about ECS programming, so don't warry, **it is not your fault!** but I suggest you better readings!)

```
while (lag >= MS_PER_UPDATE)
{
    update(); // ops!! how much time elapsed here? you don't know!
    lag -= MS_PER_UPDATE;
}

```

Instead I would do the following:

```
double previous = getCurrentTime();
double totalElapsed = 0.0f;
while (true)
{
    double current = getCurrentTime();
    double elapsed = current - previous;
    previous = current;

    processInput();
    update( elapsed);
    totalElapsed += elapsed;

    if(totalElapsed > MS_PER_FRAME)
    {
        render();
        totalElapsed -= MS_PER_FRAME;
        if(totalElapsed > MS_PER_FRAME)
            std::cout<<"Performance warning, rendering or update took too long"<< std::endl;
    }
}

```

And in your ball position computation use:

```
 public void updatePosition(double elapsed) {
    mCenterX += mVector.x * elapsed;  // framerate indipendent
    mCenterY += mVector.y * elapsed;
}

```

Instead if you want a really cool reading about game loop I suggest you the following:

http://gafferongames.com/game-physics/fix-your-timestep/
> 1 votes

---
Tags: android, architecture, game-loop, frame-rate, frame-buffer
---


# Question
Title: Typical Maximum steering angle of a real car
I'm building a car sim in Unity3D. I'm trying to set the properties of the car to be as realistic as possible. I can't seem to get a straight answer on Google so I thought of asking here.

What is the typical maximum steering angle of a normal passenger car ?

# Answer
You can calculate this based on the properties of the vehicle. Using Ackermann steering geometry you can calculate the center of the turning circle. This will take into account the length and width of the car and simulate accurately the maximum steering radius you can take.

The reason you're unable to find a definitive answer is because it varies from car make to car make. The maximum turning angle of the front wheels depends on the available wheel well space and the hardware involved. You can assume some maximums based on the hardware commonly involved. I would say the wheels wouldn't turn any more than 65 degrees in either direction. That's a pretty high upper bound. However, this is something you can simulate using the model you've created of your car. How far can you turn the wheels before they contact the wheel well?
> 20 votes

# Answer
Car manufacturers generally list the turning circle radius, as well as the wheelbase of the car. From there following the diagram above with some simple maths you can calculate back to the approximate steering angle of the inner wheel.

```
atan(wheelbase / (turning circle - car width)) = angle

```

For the outer wheel don't subtract the width.

Picking a random car spec sheet look on page 62 \- a wheelbase of 2468mm and a turning circle of 10.7m (giving a radius of 5350mm), `atan(2468/(5350-1546))` is about 33 degrees.

A more extreme example from this taxi gives 53 degrees.
> 16 votes

# Answer
The maximum angle of the wheels, when turning, depends on the car's speed and its manufacturing.

More precisely, at higher speed, the steering ratio is smaller when compared to a lower speed, where the steering ratio becomes bigger.
> -2 votes

---
Tags: physics, unity, simulations, car
---


# Question
Title: Alternative to world/terrain editing with jmonkey
I have been studying Java for almost a year and have been trying to develop a game using jMonkey. I have tried Unity before but since I only know Java I decided to go with jMonkey.

My problem is that the terrain/world edit in jMonkey is buggy. When I make changes to the terrain I sometimes can not save. Many others seem to have the same problem too.

I would also prefer drag n drog exactly like Unity has, but jMonkey doesn't seem to have that.

Is there any other way I can create the terrain/world (with drag n drop like Unity) and then import into jMonkey? What are the alternatives?

# Answer
I would recommend the following:

1. jME3 SpaceShift Editor
2. World Machine
3. Blender.org

But you could also look into the List of level editors you probably would need to create an importer or do some magic with your output files but it is very possible.
> 2 votes

---
Tags: java, jmonkeyengine, world-editor
---


# Question
Title: Locating different models in a single scene
I have a curiosity.

Say I wanted to create a big forest using Blender, in this forest I'd like to have a campfire or several campfires. What I could do is create the entire scene in Blender with campfires included and of course in-engine I would add a fire effect to it. Now what I do not understand is how can I actually find the fireplaces' locations in the engine? Since it's all in one scene, I can't just say `getLocation` on the model.

I guess what I'm asking isn't how to do it per say, but what the "professional" way is. Do professional game developers fiddle around with coordinates until they find it? Do they load the campfire on top of the scene as a separate model and move it until it fits the scene? Just in case it is important, I am using jMonkeyEngine.

# Answer
> 1 votes
If you want easy ( and look professional to me ) way to find the fire place , do this simple thing :

1. In your game engine , put an invisible object / empty game object
2. Put the object in the middle of the fireplace at the map
3. Get the coordinate of the invisible object / empty game object through script

# Answer
> 0 votes
I would create a script that looks though the entire scene and finds the models that are campfires, then add the effect to them. Possibly have the exact offset from the center of the model set manually once then applied to all objects of the same type.

While this would work I don't want this to happen at runtime so when the game is being built this would get called and change the level as one of the first steps in the build process or even as the level is changed in source control depending on how it's implemented.

This way there would be no messing around with locations every iteration of the forest and it would mean that there is an extra step of security before releasing as any error would cause the build to fail meaning that I couldn't release. Couple this with a continuous integration server (like Jenkins) and as soon as someone messes with the Forest in the wrong way it tells the team what part failed and why so that the person responsible for the change has to go and fix it.

# Answer
> 0 votes
In Blender you can \[Tab\] into your mesh, and select the vertices of a campfire if your campfire is a single mesh you can press \[Ctrl+L\] after selecting a single vertex to get the linked vertices.

Once you have all the vertices you can press \[Space\] then search for "snap cursor to selection".

If you \[Tab\] out of your mesh and create a new object lets say a "Cube", and name it "campfire" now you can press \[Shift+S\] and chose object to cursor, "repeating this process for each campfire".

> I don't know if the SDK can import Empties but if it can that might be the better option insted of Cube.

When your done doing that you could just save your blender file, and convert it to j3o in the SDK. Then find your campfire cubes in the Scene Composer, and delete there geometry but leave there nodes.

Finally in your code all you would need to do is:

```
Node forestScene = (Node) assetManager.loadModel("Scenes/forest.j3o");

Vector3f campfireLocation = forestScene.getChild("campfire").getWorldTranslation();
//OR
Vector3f campfireLocation = forestScene.getChild("campfire").getLocalTranslation();

```

this would work great expecially if you are going to attach a particle emitter then all you would need to do is:

```
((Node)(forestScene.getChild("campfire")).attachChild(emitter);

```

Final Thoughts: I would probably suggest a hierarchy like the following for you campfire nodes: `scene(Node) +
 +- campfires(Node) +
 | + campfire.0(Node)
 | + campfire.1(Node)
 | + campfire.2(Node)
 | + campfire.3(Node)
 +- scene.geometry(Geometry)`

Witch would allow you to make one control to handle all the campfires.

In case you haven't looked here Blender Key Mapping

---
Tags: blender, jmonkeyengine
---


# Question
Title: Why is my Admob reward interstitial ad connected to Unity stuck on pending?
I am trying to better monetize my game by using rewarded interstitials. I have set these up on my admob console. I have also linked the ad source on the admob console to my game through the Unity ads service using my game's id.

It seems to be stuck on "pending". I can't find any further options on admob or on the unity ads console to remedy this. In the game itself, my rewarded ads are not loading.

Is there some step I am missing either through Admob or Unity ads? How long does pending take because it has been like this for a few days.

**Edit with more info** Unity version 5.5.1f1 I am using the example code from the admob site (I removed my apps id's here for privacy reasons):

```
    public RewardBasedVideoAd nonskipInterstich;
    public void NonSkipGoogleAd(){

    #if UNITY_ANDROID
    string adUnitId = "--------------------------------------";
    #elif UNITY_IPHONE
    string adUnitId = "------------------------------------------";
    #else
    string adUnitId = "unexpected_platform";
    #endif

    nonskipInterstich = RewardBasedVideoAd.Instance;

    // Create an empty ad request.
    AdRequest request = new AdRequest.Builder().Build();
    // Load the interstitial with the request.
    nonskipInterstich.LoadAd(request, adUnitId );

    nonskipInterstich.OnAdFailedToLoad += LogFailedToLoadError;

}

```

if I display the failed to load event I get "No fill". I haven't ever gotten it to fill a request, but I am only using remediation linked to the UnityAds source.

I read a post online that recommended importing the Unity Ads plugin from the asset store into the project. I did this and the google request is still not filling. I do not use the unity ads plugin directly to make the request. I also have the unity ads adapter jar found here

# Answer
> 1 votes
I figured it out. There were a number of things I missed. After adding unity ads sdk and the adapter jar file for the unity network to my project in the GoogleMobileAds/libs folder I found that the "enable" button on the admob console activated the connection for the rewarded ads.

---
Tags: unity, advertisements, admob
---


# Question
Title: How do I make 3d Sprites like Myth did 20 years ago?
The game that Bungie cut it's AAA chops on: Myth: The Fallen Lords. about 20 years old now.

https://en.wikipedia.org/wiki/Myth:\_The\_Fallen\_Lords

For the time, it had a pretty revolutionary way of doing lots of "3d" characters, hundreds, on screen and interactive at a time. to accomplish this, basically they use sprites for each character: choosing and skewing each sprite based on the camera perspective to make it appear 3d.

I would really love to read and learn more about how this technique worked, as I think it can still be applicable to modern indie games, but I've never seen this technique used since. Does anyone know where I could read more on this?

here is a youtube of the game being played, showing the characters: https://youtu.be/PySrgfe6pr4?t=6m2s

# Answer
> 3 votes
You need to create the 3D models, extract the images, and import them as resources in your game. I would suggest to create sprite sheets for the animations.

Many 3D editors support setting the camera position parametrically and exporting images from that view point (which is useful, for example, when creating skyboxes). Although you probably will need to script that to do it bulk.

You could roll your own model viewer and script the required exports (there are 3D model viewer libraries you can use) and write the load files and export images from the camera positions you need in bulk.

---

There is actually some word on how those were done. Jason Regier, who worked on graphics for Myth: The Fallen Lords and was lead programmer of the sequel, has said:

> In addition to creating the shipping product, we developed four tools to aid in the construction of the game. One utility, the Extractor, handled the importing of sprites and the sequencing of their animations. Another tool, dubbed Fear, dealt with importing polygonal models such as houses, pillars, and walls. (...)
>
> The artists used Alias|Wavefront's PowerAnimator and StudioPaint on a single Silicon Graphics Indigo 2 to create polygonal models and render all the characters. At one point, the artists worked separate day and night shifts so that they could maximize their time on the SGI. Models were brought into the game using Fear, while the sprites were cleaned up in Adobe Photoshop and imported with the Extractor. (...)

-- Postmortem: Bungie's Myth: The Fallen Lords

> Fear takes care of all the models; it is used to import the 3D rendered models into Myth.

-- Farkas, Bart (1997). Myth: The Fallen Lords: Strategies & Secrets. New York, NY: Sybex. p. 268. ISBN 9780782121407

# Answer
> 1 votes
I found information that might be helpful to you on a Myth modding page; here's a link describing how to make new units and sprites : (link removed)

Basically you'd need to:

* Create a 3D model of the unit
* Rig your model
* Animate your model performing the necessary actions (moving, attacking, etc.)
* Save multiple renders of the animations: the link says that Myth uses roughly a 30 degree angle from the ground, but you need to look from head-on (0 degrees) to 315 degrees at 45 degree increments

You can probably get more information by researching Donkey Kong Country (DKC): it used a similar process (3D renders -\> sprites), but it didn't use multiple aspect angles like Myth. The technology for DKC has been discussed a lot over the years.

---
Tags: sprites, performance, character, billboarding
---


# Question
Title: How can I prevent the knob from resizing when I use the Slider?
I am using the Unity Slider component. I have a custom background and custom knob. But whenever I move the slider, my knob's size becomes distorted. It is 100x100 pixels, and when I set it to its native size, it does so. But I soon as I move the slider, it cuts its height in half. How can I prevent this from happening?

# Answer
3 ways. 1) should work for all cases.

1) Parent the handle object to some empty and assign this object slider handle rect. Also, change the Anchor Preset to not stretched in `Handle` object. Thus slider will change Anchor Preset of `GameObject`, but `Handle` has no stretched, so it will not be changed.

2) There is a Preserve Aspect toggle in Image component, this may not work for you if you want your handle image to be another aspect.

3) Try scaling it in Scale, not changing its width or height.
> 3 votes

---
Tags: unity, gui
---


# Question
Title: are low poly games easy to create in unity 5?
I am a beginner in unity. I saw few 3d games created in it. Developers tried a lot to make those games look good in free edition but its hard to create eye crushing graphics at unity free edition. So, I choosed low poly graphics for creating my game ( it looks better than other unity graphics). Is low poly graphics/models easier than creating normal 3d graphics/models in unity?

# Answer
Unity, UE4, Cryengine, Lumberyard - game engines. Blender, Maya, 3DMax, ZBrush - modeling, rigging, animating, texturing programs.

From my experience low poly is hard. Yeah, the models and their texturing are easier to create in some way, but modeling and texturing something really good - even in low poly is very hard. Low poly has its own style and feel in every game. It's not just a bunch of low polygonal models.

Anyway, creating a game with low poly graphics is not much easier from creating a game with high poly. Actually, there is no difference. You still have to code, rig, texture and animate. It takes less time to make some good looking low-poly models when you know how to make it right.

Despite everything I said before, It's much easier to start creating games with low poly graphics. Don't mix what I said, I meant: low poly is easier to create and texture, but the right and cool low poly is hard.

Also, rendering in Unity personal edition is not different from paid edition. All features that can be implemented in games are the same for both editions. Just the skill of creator matters. You can look differences yourself here https://store.unity.com/ . If you think that image effects are available only in pro edition - you are wrong. Those are just shaders and scripts that you can even write yourself, though there are plenty of them on the Assetstore.
> 0 votes

---
Tags: unity, 3d-modeling
---


# Question
Title: Android black screen with Unity app in subview
I've exported an Unity app/game I have made to Android Studio. In Android Studio I made a layout and within it I have a framelayout. However, when I run the app the framelayout is completely black, why?

Here is my Java code:

```
public class UnityPlayerActivity extends Activity {
    protected UnityPlayer mUnityPlayer; // don't change the name of this variable; referenced from native code

    FrameLayout fl_forUnity;

    Button bt_groen, bt_gul, bt_sort;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(savedInstanceState);

        getWindow().setFormat(PixelFormat.RGBX_8888);

        mUnityPlayer = new UnityPlayer(this);
        if (mUnityPlayer.getSettings().getBoolean("hide_status_bar", true)) {
            setTheme(android.R.style.Theme_NoTitleBar_Fullscreen);
            getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                    WindowManager.LayoutParams.FLAG_FULLSCREEN);
        }

        setContentView(R.layout.main);

        this.fl_forUnity = (FrameLayout) findViewById(R.id.fl_forUnity);

        this.fl_forUnity.addView(mUnityPlayer.getView(),
                FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT);

        this.bt_groen = (Button) findViewById(R.id.bt_groen);
        this.bt_gul = (Button) findViewById(R.id.bt_gul);
        this.bt_sort = (Button) findViewById(R.id.bt_sort);

        this.bt_groen.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                UnityPlayer.UnitySendMessage("Main Camera", "ReceiveRotDir", "G");
            }
        });

        this.bt_gul.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                UnityPlayer.UnitySendMessage("Main Camera", "ReceiveRotDir", "Y");
            }
        });

        this.bt_sort.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                UnityPlayer.UnitySendMessage("Main Camera", "ReceiveRotDir", "B");
            }
        });

        mUnityPlayer.requestFocus();
    }
}

```

Here is my XML:

```
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                android:layout_width="match_parent" android:layout_height="match_parent"
                android:rowCount="3"
                android:columnCount="10">

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="400dip"
        android:id="@+id/fl_forUnity"
        android:background="#00FFFF"
        android:layout_centerHorizontal="true">

    </FrameLayout>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Grøn"
        android:id="@+id/bt_groen"
        android:layout_column="4"
        android:layout_row="2"
        android:layout_alignTop="@+id/bt_sort"
        android:layout_toRightOf="@+id/bt_sort"
        android:layout_toEndOf="@+id/bt_sort"
        android:layout_marginLeft="30dp" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Gul"
        android:id="@+id/bt_gul"
        android:layout_column="9"
        android:layout_row="2"
        android:layout_alignTop="@+id/bt_sort"
        android:layout_toLeftOf="@+id/bt_sort"
        android:layout_toStartOf="@+id/bt_sort"
        android:layout_marginRight="30dp" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Sort"
        android:id="@+id/bt_sort"
        android:layout_below="@+id/fl_forUnity"
        android:layout_centerHorizontal="true"
        android:layout_margin="10dip" />

</RelativeLayout>

```

# Answer
> -1 votes
I found the answer: add `android:process=":UnityKillsMe"` to your unity library activity tag in manifest.

And also, we should implement `onWindowfocusChangedListener` for sure:

```
void OnWindowFocusChanged(){ m_UnityPlayer.windowFocusChanged(hasFocus);}

```

My code: It worked

```
public class MainActivity extends AppCompatActivity {

   private UnityPlayer m_UnityPlayer;

   @Override
   protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       // Create the UnityPlayer
       m_UnityPlayer = new UnityPlayer(this);
       int glesMode = m_UnityPlayer.getSettings().getInt("gles_mode", 1);
       boolean trueColor8888 = false;
       m_UnityPlayer.init(glesMode, trueColor8888);

       setContentView(R.layout.activity_main);

       FrameLayout layout = (FrameLayout) findViewById(R.id.frameLayout);
       LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
       layout.addView(m_UnityPlayer.getView(), 0, lp);
       m_UnityPlayer.windowFocusChanged(true);
       m_UnityPlayer.resume();
   }
   @Override
   public void onWindowFocusChanged(boolean hasFocus)
   {
       super.onWindowFocusChanged(hasFocus);
       m_UnityPlayer.windowFocusChanged(hasFocus);
   }
   @Override
   public void onPause() {
       super.onPause();
       m_UnityPlayer.pause();
   }
   @Override
   public void onResume() {
       super.onResume();
       m_UnityPlayer.resume();
   }

   @Override
   protected void onDestroy() {
       super.onDestroy();
       m_UnityPlayer.quit();
   }
}

```

---
Tags: unity, android
---


# Question
Title: How can I add solid collideable borders to the viewport regardless of the resolution?
I'm making a game in Unity. In my game I have a sphere, what I need is for the sphere to rebound against the edges of the viewport.

For that I used a few Gameobjects with 2D box colliders.

The problem is that when game resolution changes, the edges of the camera are extended or reduced, and empty gameobjects are not on the edge.

How can I make gameobjects which always stay on the edge of the viewport?

Is this the correct way to make it bounce at the edges?

# Answer
There's more than just one way to achieve this. In my case, if this was a core mechanic, I would avoid using the colliders and just use my own code for detecting when the ball has hit an edge and then send it back with a mirrored vector. Your method is not wrong, it just wouldn't be my choice because of the lack of control. Anyway, here's how to do what you're trying to do:

Create a screen-space canvas. Put a canvas scaler script on it and set it to scale with screen size. Make your boundary gameobjects into children of that canvas. Then align the borders with the canvas' borders and it will scale to any resolution you want.

These are my working values as of the time of the tests:

The method I used here will use a script to decide the BoxCollider2D's size, but you can manually type the values in.

Here's the script for the child object:

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

public class RectBoxSize : MonoBehaviour {
    public RectTransform objectRect, parentCanvas;
    public BoxCollider2D boxCollider;
    Rect canvasOld;
    // Use this for initialization
    void Start ()
    {
        if (parentCanvas == null)
        {
            parentCanvas = GetComponentInParent<Canvas>().GetComponent<RectTransform>();
        }
            canvasOld = parentCanvas.rect;
        if (boxCollider == null)
        {
            boxCollider = GetComponent<BoxCollider2D>();
        }
        if (objectRect == null)
        {
            objectRect = GetComponent<RectTransform>();
        }
        boxCollider.size = objectRect.rect.size;
        boxCollider.offset = new Vector2(0, 0);
    }

    // Update is called once per frame
    void Update () {
        if(canvasOld.width != parentCanvas.rect.width
            || canvasOld.height != parentCanvas.rect.height)
        {
            boxCollider.size = objectRect.rect.size;
            boxCollider.offset = new Vector2(0, 0);
            canvasOld = parentCanvas.rect;
        }
    }
}

```

Here's a gif that shows how the code works:
> 1 votes

# Answer
Are you using the RectTransform's Anchors?

With this you can "snap" objects inside the canvas and it will follow the position on any resolutions.
> 0 votes

---
Tags: unity, c#, android, physics, viewport
---


# Question
Title: Can a generic class inherit from MonoBehaviour?
Expanding upon a previous tutorial, I am adapting a follow script to support multiple variations of a Bezier spline. Each spline variation uses a custom interface called `IBezierInterface`, and the follow script accesses the method `GetPointOnCurve()` to determine the correct position. In theory, this all seems very simple. However, I appear to be running in to some trouble. While I intend to pursue the general issues a bit more, myself, I realise that I may be shooting myself in the foot with the generic implementation.

While I can find a lot of good examples demonstrating the correct use of generic types, I can not find anything that gives an example of a generic class that inherits from another class. For example, Microsoft documentation includes examples of inheritance as a *restriction* on the actual type, and an example of inheriting *from* a generic class; but there are no examples of a generic class that inherits from a standard class. Unity documentation has even less examples, but none pertaining to my query. I am not getting errors; *but that is no guarantee against error*. I can not conceive a good prototype model to test my theory, either, given the fact that I am fairly new to the concept of generic types.

---

Given that I am specifically needing my class to be a `MonoBehaviour`; can I make a custom generic class that inherits from `MonoBehaviour`, such as in my example?

```
public class SplineWalker<T> : MonoBehaviour where T : IBezierInterface
{
    // ...
}

```

# Answer
As Theraot said: No, Unity does not support that.

But an alternative would be to use composition instead of inheritance. Instead of having a `SplineWalker` *for* `IBezierInterface`, create a `SplineWalker` *with* an `IBezierInterface`.

```
public class SplineWalker : MonoBehaviour
{
    public IBezierInterface spline;
}

```
> 4 votes

# Answer
The code you present is valid C#, yet as far as I know it is not supported by Unity (giving a "Generic MonoBehaviours are not supported" error warning on the console when trying to use `AddComponent` for it).

If you need to have multiple implementations of this class with different generic parameters, you may subclass again to make non-generic classes. You may also consider using a template solution (such as T4) to generate the code files.
> 1 votes

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


title: Libgdx: Aligning buttons inside dialog

text:
# Question
Title: Libgdx: Aligning buttons inside dialog
I have the following dialog, semi circle shape. I want to position buttons in it.

```
        dialog.button(closeButton, false);
        dialog.getContentTable().add(buttonS);
        dialog.getContentTable().add(button);
        dialog.getContentTable().add(hwTo);

```

The only way I am able to move a button is by using for a example

```
    dialog.getContentTable().add(hwTo).pad(300);

```

But I don't want to pad anything, since it affects other buttons, I tried `align`, `button.setPosition` and whatnot, nothing works.

I was told to remove the table and ise Custom WidgetGroup. I removed the table, still having the same problem, nothing works except padding.

# Answer
Your Dialog extends from Group, which means you can do `dialog.addActor(myActor)`. Using addActor, you have a full control of the actor positions. You should go this way.
> 1 votes

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


# Question
Title: How to Access a Field of an Unknown Class if the Field Exists
It's a very poorly worded question because I'm not exactly sure how to put it into words that are of appropriate number for a title. Read on for a better explanation. (Using Unity API, C#)

Basically, I have an AI class in a spaceship game. I can assign the AI a target GameObject, and the AI will look in the direction of and chase after it's target. I would like to make the AI be able to strafe in circles around the target. Since the AI always faces its target, I can simply TransformDirection(Vector2.left/right) and it will orbit the target nicely, but if the target is moving it always breaks orbit.

To combat this, I want to add the target's velocity to the strafe velocity of the AI. However, I have different classes for the player's ship and the AI ships whom also might be targeted by another AI. All of my ship classes have a field for the ship's velocity, but since they are different classes, I thought I may access the velocity field by doing a GetComponent() and passing some sort of predicate =\> T has a Vector2 field named "velocity". Is there some way to achieve this?

# Answer
You have 3 options I can think of:

Inheritance, all possible target types inherit from single base class`class TargetBase : MonoBehaviour` with `velocity` property, probably the most efficient solution

```
target.GetComponenet<TargetBase>().velocity

```

Introduce interface `IHasVelocity`, implement the interface in target classes and filter for components that implement it, decent solution especially from code style viewpoint

```
((IHasVelocity)target.GetComponenets().ToList().Single(c => c is IHasVelocity)).velocity

```

Using reflection, the most flexible but also more dangerous, possibly also least efficient solution

```
target.GetComponenets().ToList().Select(c => {
  Vector2? value;
  c.GetType().GetProperty("velocity").GetValue(value, null)
  return value; }).Single(v => v != null).Value

```

all solution will also work with fields with only minor changes. Code syntax not tested.
> 1 votes

# Answer
Check whether the target has changed its position within the last frame and then add that change to your AI's transform.

```
//after doing the stuff you need to do, check the changes and add those up
if(lastPos != target.transform.position && currentlyCirclingTheTarget)
{
    transform.position = transform.position + (target.transform.position - lastPos);
    lastPos = target.transform.position
}

```

I'm not sure if this will work exactly as I think it will but you should be able to incorporate the logic into your own code if it doesn't work perfectly.

(This will only work well if you want the AI to lock on to your target and stay within a certain distance, if you have different maximum speeds for different units, this will mean a slower AI will be faster when it locks on to a faster target.)
> 0 votes

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


# Question
Title: Pressed key doesn't run out of special powerups
So I'm making a game in Lua/Love2D and have a problem with my game logic. Mainly I have a spaceship that can use boost and stuff. That part is fine, I click space and it boosts up to speed quickly.

The problem is that if the person holds down space, they stay boosted, which is not the intended behavior. How do I make sure that once boost runs out, it decelerates to normal speed? This is how it is currently:

> Note: Normal speed, 1000. Max boost possible speed, 3000.

```
if love.keyboard.isDown('space') then
    if player.v < 3000 and UICounters.currentboost > 0 then
        player.v = player.v + 200
        if player.v > 3000 then
            player.v = 3000
        end
        UICounters.currentboost = UICounters.currentboost - 1
    end
else
    if player.v > 1000 then
        player.v = player.v - 100
    end
    if UICounters.currentboost < UICounters.maxboost then
        UICounters.currentboost = UICounters.currentboost + dt
    end
end

```

# Answer
While the player holds down the space key, the `else` part of your code is never reached, so the deceleration is not applied. Basically, you'd have to execute this if `UICounters.currentboost` is \<= 0, even if space is being held down. You could achieve that by duplicating parts of your code, or you could change your initial check to something like this:

```
if love.keyboard.isDown('space') and player.v < 3000 and UICounters.currentboost > 0 then
    player.v = player.v + 200
    if player.v > 3000 then
        player.v = 3000
    end
    UICounters.currentboost = UICounters.currentboost - 1
else
    if player.v > 1000 then
        player.v = player.v - 100
    end
    if UICounters.currentboost < UICounters.maxboost then
        UICounters.currentboost = UICounters.currentboost + dt
    end
end

```

Now, your booster only fires if the space key is pressed AND the velocity is below the max AND the player has boost left. Otherwise it falls into the else part and the player decelerates. This might lead to some back and forth between 3000 and 2900 in certain situations, but I think this should be a good starting point for you to further finetune the behaviour.
> 2 votes

# Answer
I think it is because you are using the keyboard.isDown which basically means if the Space bar is "held down" it will keep adding 200 to player.v untill you release it.

I suggest that you instead use:

```
function love.keypressed( key )
   if key == "return" then
      text = "RETURN has been pressed!"
   end
end

```

Read more about it here: https://love2d.org/wiki/Tutorial:Using\_Input
> -1 votes

---
Tags: game-mechanics, lua
---


# Question
Title: Will any program written with XLib work on any desktop environment (Gnome, KDE, etc.)?
I'm making an application that uses Win32 API on Windows but I want to support linux distros too.

Some people say linux doesn't have a native GUI API like Win32 API of Windows.

But I found XLib and it seems like it is somethink similiar to Win32 API. If I use XLib on my project, can I compile and run it on any linux distro that uses any desktop environment without using external libraries?

I don't want to use something like GTK+ or SDL because I'm learning Win32 (just for fun) and using a platform independent library along with Win32 API sounds really absurd.

# Answer
> 3 votes
**Short answer**: yes, XLib will work for the foreseeable future.

Although in some enviroments there will be additional libraries required. You don't need to worry about that.

---

**Long answer**:

*XLib*

XLib targets X Windows Systems (a.k.a X11). XLib is the classical library to use with X11 as works very close to it. XLib also includes a lot of helper code that eases the integration with the desktop environment.

X11 has been the core for desktop interfaces in the Linux ecosystem for a long time. Desktop Environments such as Gnome and KDE build on top X11... in essence X11 is a protocol, where the client sends requests and the X Server responds (will talk a bit more about that below), this is hidden by XLib which stores the requests in a buffer which are then taken by the X Server which will respond asynchronously, but XLib will make it appear synchronous.

High level components such as buttons et.al. exist as widgets on XLib, so this is the closest to the equivalent Win32 API.

*XCB*

All the communication hidden by XLib makes error handling harder, which led to the creation of the competition: XCB, which is intended to replace XLib by providing direct access to the X protocol. That means that XCB has a smaller footprint, it is asynchronous and has better performance. This makes XCB better in terms of performance, in particular for threaded applications.

Plot twist: XLib since the version 1.2.0 is actually built ontop of XCB. This means that you can mix XLib and XCB code with no problem... but it means that you need an additional library for XLib since it depends on XCB.

---

*X Server*

As mentioned above, there is an X Server that provides the abstract information and talks to the screen and input devices. The server doesn't know anything about user interface design. Then there are X Clients, which will interface with the server... this architecture facilitate for Clients to work over the network allowing access to remote terminals/desktops (although that's an over-simplification).

The X Server doesn't know about GUI, allowing it be changed, that's what Desktop Environments do. In this scenario X11 does all the rendering, although libraries for hardware accelerated graphics might bypass this.

---

*Wayland*

In the past there were competitors to X11, many deprecated... and there are new competitors to X11, in particular I want to mention Wayland.

Wayland is another protocol, much simpler than X11, that yields control of the actual rendering to the client.... basically Wayland shares a buffer for video memory where the client renders whatever it wants however it wants, so there is no graphics API. In fact, Wayland will handle the concept of windows and the composition of these buffers in video memory according to the windows they represent. This makes Wayland better for encapsulation in general (no API means less surface, and the model allows to isolate the memory easily).

X11 has needed a lot of updates to remain relevant with new technologies and standards (e.g. supporting font and image formats, supporting hardware acceleration, etc...), but with Wayland that problem goes to the graphic libraries the developer use.

While support for Wayland is increasing, X11 will stay around because of all the software build around it. What is expected to happen is that code from X11 will become part of the kernel, become extensions to Wayland or become libraries to be used by developers.

For instance, what do you do if you have a machine that runs Wayland but you need to run a program that uses X11? Well, there is XWayland that will run an X Server on top of Wayland.

---

*Mir*

I also have to mention Mir, which is a competitor to Wayland made by Canonical Ltd. (the people behind Ubuntu). It differs from Wayland in that Wayland doesn’t handle input but Canonical wanted that in there... so they made their own.

Similarly to Wayland, it will be able to run X11 using XWayland... but on top of Mir.

---

*Conclusions*

There may come the day where X11 isn't what you want to target. And also in the present there are environments where targeting X11 requires additional libraries.

---
Tags: windows, linux, win32
---


# Question
Title: client-side array in the OpenGL 3.3. core
It is possible the topic (not using VBO)?

in the OpenGL 3.0 compatible profile I can to draw this way:

```
GLint position_index = attrib_location_get("VertexPosition");
gl::EnableVertexAttribArray(position_index);
gl::VertexAttribPointer(position_index, 3, gl::FLOAT, false, 0, pos_Data);
gl::DrawArrays(gl::TRIANGLES, 0, count_of_vertices);

```

Bat in the OpenGL 3.3 core profile it displays a blank screen. It is right?

# Answer
**Yes, this is correct**.

From the OpenGL 3.3 specification, section E.2.2: Removed Features:

> Client vertex and index arrays - all vertex array attribute and element array index pointers must refer to buffer objects. The default vertex array object (the name zero) is also deprecated. Calling VertexAttribPointer when no buffer object or no vertex array object is bound will generate an INVALID\_OPERATION error, as will calling any array drawing command when no vertex array object is bound.
> 2 votes

# Answer
We're missing half the example here, but I assume you are trying to display directly from a RAM-stored buffer.

This is simply not possible in core profile. You need to upload your data into VRAM via a VBO, *then* display it from there.
> 0 votes

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


title: Is Orthogonal in LWJGL 2D or 3D?

text:
# Question
Title: Is Orthogonal in LWJGL 2D or 3D?
I'm attempting to develop an orthogonal game with lwjgl 3 and OpenGL in Eclipse, but I can't find an answer for rendering objects in 2D or 3D. Are both applicable? And if so what are the advantages of either one? I would also like to rotate my camera if that changes your answer.

# Answer
The orthographic camera should almost always only be used in 2d. Instead you should use the perspectivecamera

You can read more about the orthographic camera here: https://github.com/libgdx/libgdx/wiki/Orthographic-camera

Read more about creating 3d games in libgdx here: https://xoppa.github.io/blog/basic-3d-using-libgdx/

On this site it is explained why you should use the perspective camera for 3d instead of the orthographic camera: http://www.gamefromscratch.com/post/2014/12/08/LibGDX-Tutorial-Part-16-Cameras.aspx
> 1 votes

# Answer
### You can use it for both.

It makes `z` coordinate not affect any vertex positions, so you can use it for 2D games.

But it also allows you to use features like z-buffering and there is nothing wrong with rendering 3D objects with it.
> 0 votes

---
Tags: opengl, java, lwjgl3
---


title: How To Upload JavaScript Games To Steam

text:
# Question
Title: How To Upload JavaScript Games To Steam
So I've been making this game called The Necromancer and (quick note, I am **still** working on the game. Also, I know this sounds similar to this question, but my question is for the general process) I wanted to publish on the Steam Store. However, I don't know what the process is, as in what you do to get your game posted on Steam. Also, how would I get a few files, and somehow put it in a virtual package that I can give to Steam. I just feel rather confused on the subject.

Thank you for your time

# Answer
> 17 votes
Steam only deals with downloadable games, not browser games, so you'll need to package your game using something like nw.js or Electron. Also you might want this library for integrating with Steamworks.

(note that the question you linked is about Java, not JavaScript, so the technical details are very different. if only I had a nickel for every person who thinks Java and JavaScript are in any way related...)

# Answer
> 6 votes
The current (2/21/2017), general process as described on the Greenlight FAQ:

> **Who should submit their games to Steam Greenlight? Is there another way to submit my game to Steam?**
>
> Steam Greenlight has replaced our previous submission process. Any developer or publisher who is new to Steam and interested in submitting their game to the platform should submit their game through Steam Greenlight.

However, Valve is planning on changing the Greenlight in the near future to Steam Direct:

> **A better path for digital distribution**
>
> The next step in these improvements is to establish a new direct sign-up system for developers to put their games on Steam. This new path, which we’re calling “Steam Direct,” is targeted for Spring 2017 and will replace Steam Greenlight. We will ask new developers to complete a set of digital paperwork, personal or company verification, and tax documents similar to the process of applying for a bank account. Once set up, developers will pay a recoupable application fee for each new title they wish to distribute, which is intended to decrease the noise in the submission pipeline.

As pointed out in by @jhocking's answer, a JavaScript game has some additional technical complications that you'll need to deal with.

---
Tags: javascript, publishing, steam
---


title: Dealing with vectors in multiple planes

text:
# Question
Title: Dealing with vectors in multiple planes
Say I have my main "screen" plane, where vectors can be represented

I "know"/can represent vector Q, but the only information I know about vector R is relative to Vector Q. An easy way to visualize this is to have another plane at o2-- I can represent vector R in this plane (e.g. in cartesian coordinate form, or polar form), but how do I "globalize" to the original plane, or represent vector P?

Thank you

# Answer
> 1 votes
You first need to define the origin which everything is relative to. You've defined the origin (0,0) to be the top left corner of the main screen, and lets say that X goes positive to the left and Y goes positive downward.

To represent a vector, you need two pieces of information: 1) the location of the start and 2) the location of the end.

The location of the start is generally represented by a point (x,y) relative the coordinate system origin.

The location of the end can be represented by either another point relative to the coordinate system origin, or by a point relative to the starting point of the vector. Doesn't really matter as long as you do the math correctly whenever you use the vectors.

So for Q, it might be represented as start=(0,0) and end=(5,5). Since it starts at the origin, its "end" representation is the same regardless of whether your are making it relative to the origin or relative to the starting point of Q.

For P, lets say its start=(0,0) and end=(5,4).

For R, We can represent it either as start=(5,4) and end=(5,5) or we can represent it as start=(5,4) and end=(0,1), depending on whether the end point is relative to the origin or the starting point. It doesn't matter as long as you treat all vectors the same way.

# Answer
> 0 votes
There are 2 types of vectors: **position vectors** and **free vectors**

You usually use position vectors in comouter applications, because they can very clearly represent a location (obviously). They also have a start point and an end point as every other vector, but their start position is in the origin (usually (0; 0)). In the image OA is a position vector.

Free vectors are have a start point that doesn't lie on the origin. This makes them excellent for pointing between 2 object or represent physical forces. On the image BC vector is an example for a free vector.

You can represent a free vector with 2 points. Because vectors are independent of their location, they can be freely moved around, and you get the same vector. Moving BC vector to the origin to create a position vector can be done by subtracting B from C, this the vector's length is `|B - C|`

---
Tags: mathematics, vector, trigonometry
---


title: Project vertex on a line

text:
# Question
Title: Project vertex on a line
V,A and B are 3 points in 3D space and We have d0 (distance of V from (AB)line).

I want to calculate question mark point in the image above!

# Answer
> 1 votes
Easy peasy:

```
Vector3 direction = ( B - A ).normalized;

Vector3 projection = A + direction * Vector3.Dot( direction, V - A);

```

Or here's an ever-so-slightly mathier version that saves a square root (you probably won't see a performance difference though unless you're doing this thousands of times in a cache-friendly inner loop)

```
Vector3 AtoB = B - A;

Vector3 projection = A + AtoB * Dot(AtoB, V - A)/AtoB.sqrMagnitude;

```

---
Tags: unity, 3d, 3d-meshes
---


# Question
Title: Find vector tangent to circle through a point
C2 and P1 are known points. Radius of circle C2 is also constant and known. I am trying to find point T to eventually construct line p1-t, which is tangent to circle c2.

I have made an attempt involving bisecting c2-p1 at M, and performing trigonometric operations to find measure of angle TMC2. Then, I found the difference in x and y coordinates from m.x and m.y using a polar form to cartesian (polar: angle tmc2 and length of tm = c2m = 1/2 c2P). After this, I normalized vectors c2P and added the difference in x, normalized the vector perpendicular to c2p and added the difference in y.

This approach seems very convoluted for such a simple task. Are there any basic vector operations to save time and processing power?

Thank you

# Answer
It's pretty easy with some trigonometry.

Here's a hand drawn image of your problem:

OTP angle is a right angle.

Calculating `l` is done with the pythagorean theorem:

```
l = sqrt(d^2 - r^2)

```

You first want to calculate alpha. This is where the trigonometry part comes in.

```
tan(alpha) = r / l
alpha = atan2(r, l)

```

After you have alpha, you need to calculate the angle of PT relative to the coordinate system (let' call it beta). This is done by calculating the angle of PO (let's call it gamma) then subtracting alpha from it:

```
vector := O - P // vector pointing from P to O
gamma = atan2(vector.y, vector.x)
beta := gamma - alpha

```

Then finally you convert it to a directional vector with a length `l` and you add P to it

```
x := cos(beta) * l + P.x
y := sin(beta) * l + P.y

```
> 2 votes

# Answer
You can solve this without trigonometric functions, too.

Since the vector `u = T - C` is perpendicular to the vector `v = T - P`, the dot product `u . v = 0`. You also know the lengths of 2 sides of a right triangle (the radius `r` and `||C - P||`).

This allows you to write 2 equations in the 2 unknown elements of T, which you can then solve:

```
(T-C) . (T-P) = 0
        |T-P| = |C-P| - r^2

```

where `|X|` is the squared length of the vector `X`.

But this might be annoying to solve, so you can further exploit that in 2D, the vector `[x,y]` is perpendicular to the vector `[-y,x]`. And so we can instead write the equation:

```
T = P + u' t = C + u r

```

where `u'` is `[-uy,ux]` and `t = ||T-P|| = sqrt(|C-P| - r^2)`--which we have to solve for `u`. This gives us:

```
ux = (r * (Px - Cx) - t * (Py - Cy))/(r^2 + t^2)
uy = (r * (Py - Cy) + t * (Px - Cx))/(r^2 + t^2)

```

and therefore:

```
Tx = Cx + ux * r
Ty = Cy + uy * r

```

There is an unfortunate caveat--one other vector is perpendicular to `[x,y]` at `[y,-x]`, which is a clockwise rotation instead of counterclockwise. There are simple tests you can use to decide which to go with, but one or the other might suit you in practice.

This all involves only one `sqrt` call and so it may be less computationally expensive than Baliant's answer.
> 1 votes

---
Tags: physics, mathematics, vector, trigonometry
---


# Question
Title: Snowboarding character controller in Unity
I am currently trying to create a character controller that will allow the player to slide down slopes while maintaining control of their direction - in other words, a fairly simple snowboarding game. (I'm actually going to be using it for penguins sliding on their stomach but this has the same requirements). Note that ramps and cliffs should work as expected, with the player becoming airborne until they hit the ground.

I posted a thread on Twitter detailing my struggles here, but here is the best-functioning code I've managed so far:

```
// First, calculate our old trajectory
Vector3 oldTrajectory = transform.position - oldPosition;

// Objects in motion tend to stay in motion, so we start with that same motion first
Vector3 newTrajectory = oldTrajectory;

// If we're grounded, we'll take that into account for sliding purposes
if (cc.isGrounded)
{
    // First get the slope underneath us
    RaycastHit hit;
    if (Physics.Raycast(transform.position, -oldNormal, out hit, 2f) || Physics.Raycast(transform.position, Vector3.down, out hit, 2f))
    {
        oldNormal = hit.normal;
        Vector3 downSlopeRight = Vector3.Cross(hit.normal, GRAVITY_DIRECTION);
        Vector3 downSlopeDirection = Vector3.Cross(downSlopeRight, hit.normal);

        Vector3 movementForce = downSlopeDirection *
            (gravity * Time.fixedDeltaTime * Vector3.Dot(downSlopeDirection, GRAVITY_DIRECTION)) *
            (1 + (newTrajectory.magnitude * Vector3.Dot(downSlopeDirection, newTrajectory.normalized)));

        newTrajectory += movementForce * slopeImpact * Time.fixedDeltaTime;
    }
}
// Otherwise, normally account for gravity
{
    newTrajectory += gravity * GRAVITY_DIRECTION * Time.fixedDeltaTime * Time.fixedDeltaTime;
}

oldPosition = transform.position;
cc.Move(newTrajectory)

```

Essentially: Take our current momentum, add gravity directed by the slope, and accelerate even more if the slope matches our trajectory (I can't even remember why I put that part in). This kind of works but especially when rocking back and forth in a divot, you notice that the momentum isn't really being handled properly (see here).

I attempted a second approach, where the player simply moves in the direction they're facing, and they gain speed while moving down a slope or lose it while going up. I couldn't figure out a way to get this to work at all:

```
// First, take the real distance we moved, and convert it to fairy numbers (time-independant measurements)
Vector3 newMomentum = (transform.position - oldPosition) / Time.fixedDeltaTime;

// If we're grounded, we'll take that into account for sliding purposes
if (cc.isGrounded)
{
    // First get the slope underneath us
    RaycastHit hit;
    if (Physics.Raycast(transform.position, -oldNormal, out hit, 2f) || Physics.Raycast(transform.position, Vector3.down, out hit, 2f))
    {
        oldNormal = hit.normal;
        Vector3 downSlopeRight = Vector3.Cross(hit.normal, GRAVITY_DIRECTION);
        Vector3 downSlopeDirection = Vector3.Cross(downSlopeRight, hit.normal);
        Vector3 facingDirectionOnSlope = Vector3.Cross(transform.right, hit.normal);

        // All we want to do is move the player faster if they're facing down the slope, or slower if facing up
        // (will also slide them backwards eventually which is funny)
        float speed = newMomentum.magnitude;
        speed += gravity * slopeImpact * Vector3.Dot(downSlopeDirection, newMomentum.normalized);
        newMomentum = facingDirectionOnSlope * speed;
    }
}
else
{
    // WE ADD GRAVITY BECAUSE THE GRAVITY DIRECTION IS DOWN
    newMomentum += gravity * Time.fixedDeltaTime * GRAVITY_DIRECTION;
}

// Update oldPosition after everything else (just in case we use it) but BEFORE CHANGING IT
oldPosition = transform.position;

cc.Move(newMomentum * Time.fixedDeltaTime);

```

I tried a few different variations on this but I couldn't get it to work.

This *approach* is ideal, where the player can choose their direction and slopes give them speed (later I'd gently rotate them towards facing down the slope), as opposed to the other one relying on momentum and directing gravity. I just can't seem to figure out how to get it to work.

# Answer
> 1 votes
You're going to need to stop using a `CharacterController` and start using a `RigidBody`. The `CharacterController` is a class directly in the physics engine (PhysX). Because of this, Unity doesn't really allow for much customization on it (and I'm not really sure if they could) and so you lose a lot of control that you get with a straight up `RigidBody`. What you gain in the `CharacterController` in simplicity you lose in configurability. Continueing to use `CharacterController` means constantly fighting the defaults they have put in place to try to do things that are outside of the scope of that class.

When you switch to a `RigidBody`, consider the following things:

* Use `AddForce` (or a similar function that suits your use case) for gravity and it will automatically work with collisions
* Preventing the character from tumbling instead of sliding is going to require that you properly set the mass of the character as well as a bit of clever rotation management. This includes locking the rotation to the terrain you're currently on or applying rotational acceleration so the character doesn't flip over. A more complex solution will result in more realism/less seemingly like you're glued to the ground.
* Checking if your grounded is probably the hardest part because there's no one solution to this (and in itself it's kind of vague, like, are you grounded if you're on the ground but upside down?). You'll just have to use some clever raycasting and sweeping to determine this one or maybe a geometric solution.

---
Tags: unity, physics, movement
---


title: Inertial quantities in 3D physics

text:
# Question
Title: Inertial quantities in 3D physics
I'm writing a little 3D physics engine and everything is peachy except that to have constraints behave correctly, I'm having to artificially scale up the inertia tensors. Worse--the amount that I have to do so seems to vary from constraint to constraint.

I'm implementing constraints according to Erin Catto's sequential impulses paper. It does make sense to me that it's trickier to get things to behave well rotationally via discrete time impulses, but not sure what sort of approach to take to improve performance that isn't so hand-wavy; e.g. would satisfying the constraints at the acceleration level in addition help?

Open to any advice, even if it's that there's potentially something fundamentally wrong with my implementation or that I'm being too prissy about not wanting hacky solutions, etc.

# Answer
This feels a bit silly answering since I wasn't really close to descriptive enough, having assumed there was some large-scale misunderstanding I had. But for completeness--and for anyone else who happens to make the same, ridiculous mistake I made and happens to stumble upon this--the issue was that I wasn't respecting delta time in my orientation update. So I'd update position by some small step in time, and take an entire second's step with orientation. The explosions I was seeing were compounded by the fact that the canonical quaternion update only "works" for small rotations.

As I looked into the issue, I found this presentation by Oliver Strunk from Havok, which mentions comfortably inflating your inertia tensors a small amount with no noticeable artifacting.
> 0 votes

---
Tags: physics, 3d
---