# Question
Title: Is there a reason to add options to not use advanced technologies in a game engine?
I have been developing a game engine, and have been discovering and reading up on game technologies such as anisotropic filtering, ambient occlusion, anti-aliasing, etc.

Usually in games, you can toggle these settings on and off. However, if these settings only add nothing but positives, is there a reason to add toggle values for these in a game engine for the developer?

I understand that performance is a major factor, but is there any other reason why these settings are always available to change?

# Answer
Performance is *generally* the major reason these features can be switched on and off by the user. Generally, they are expensive, and by allowing users to toggle them off a developer broadens the set of machines that effectively run the game to include more lower-end machines. This translates to potentially more players, and thus potentially more sales (assuming those players can live with the decreased visual fidelity).

These advanced features might also incur more of a hit to battery life or fan output, as @Artelius pointed out, and so users might want to disable them for those reasons.

Finally, it simply to provide users with a choice about what they prefer. Some people may not like how anti-aliasing looks, or how disabling v-sync can cause screen tearing. Or for a more practical example, consider Pillars of Eternity, which has an option to enable or disable font ligatures. These *probably* don't cost that much in terms of runtime performance, but some users may find the text harder to read with them. Or (as @SeanMiddleditch points out), one might want to disable a feature because it's buggy on an individual machine. Or one might want to disable a feature to get a competitive advantage (such as by disabling noisy visual effects that distract from mechanics).
> 49 votes

# Answer
As Josh Petrie already pointed out, the most important concern is performance. Not only can't you know how powerful the end-users hardware is, when you are building an engine you don't even know how people are going to use it. Maybe the game developers want to build a game which puts so many polygons on the screen that even the best hardware can't render it in real-time without switching off the effects? But handling that automatically might not be a good idea either: Maybe the developers want to decide which effects to disable on which objects.

But besides performance, it can also be of aesthetic concern.

For example, switching from anisotropic filtering to nearest-neighbor interpolation and using low-resolution textures or upscaled sprites leads to a nostalgic pixel-art look. A popular example of a game which does this is Minecraft. And of course the many games which copy its aesthetics. Not because they don't know how to do better, but because they don't want to.
> 11 votes

# Answer
Of course, performance. Some effects such as Crepuscular Rays, Depth of Field and Bloom are very taxing of fps, in particular in older GPUs. Also a good way to gain some extra fps is to reduce or disable reflections and shadows. Also - to repeat Artelius point \- visual effects will also hit battery life.

Besides that:

* Some effects may be glitchy. Not all machines are made equal, and some GPU may handle wrong your code... having a way to disable effects is good for the players suffering from such cases, and is good for the developers for ease of debugging.
* Some effects may handicap gameplay. In particular effects that hide details, such as Depth of Field, Motion Blur and to a lesser extend Anisotropic filtering and Anti-aliasing.
* Some effects may be annoying / distracting. That happens to me with Depth of Field, when the focus changes, it litteraly drives attention to it.
* Some effects should be considered for Accessibility Options. This is the case of View Bobbing and Motion Blur, these can make some people sick, no joke.
* Some effects should be considered for Parental Control. Turning off blood particle effects and similar - at least it helps with parental game reviews.

---

*Modded* Minecraft is really a good playground for this. Minecraft renders whole chunks, so its polygon count is greater than it appears to be. Add to that the complications of disposing chunks on a garbage collected and devoid of pointer language such as Java\[1\], and you may expect some performance issues - in particular, in old hardware, as always. Some people demanded better graphics, while others wanted better performance. And so, mods such as *GLSL Shaders Mod* and *Optifine* came to be, both adding extra graphic options - although to different ends - they are compatible\[2\], if you have the chance to use them you may experiment on the performance effects of the visual effects.

\[1\]: Microsoft has made a C++ port of Minecraft for Windows 10 - based on the pocket edition - it performs much better than the older Java versions. That's not mean Java can't perform, this is not only a symptom of being C++ but also of being Microsoft.

\[2\]: In fact, those mods merged for Minecraft 1.8.9 - *Optifine* absorbed *GLSL Shaders Mod*.

---

And you say you are developing a *game engine*, so you expect your code to have a chance of being reused for many different games. It is a good idea to allow the game developer to decide if they want to use these effects, and if they want provide options to disable them or not. Not all effects may make sense for all games, and some games may depend on some effects.

Consider that some games will use these effects to set a mood, to convey information to the player, or just for artistic license.

In particular there is tred of using visual effects to try to make the look as if seen by a camera instead of the human eye. This is attempted by using effects such as Chromatic Aberrations, Lens Flares, Film grain and other "Cinematic" effects. These are not a good fit for every game, and so they shouldn't be imposed by the game engine.

Arguably most of this - if not all - is done in shaders, let your *game engine* allow the developer to upload their shaders.

---

*A note on Accessibility Options: Many video games disregard deaf people. Providing information only in auditory manner may not be good enough. Adding visual effects to reflect things such as the direction of incoming fire or the presence of nearby enemies (that you "can hear") is a good idea\[3\]. And of course, close caption. Also, be aware that there is color blind people... those items that are only distinguished by color... yeah, considered a redesign.*

*\[3\]: You just don't know what a pain are those creepers in Minecraft, when you can't hear not even a hiss. They become random instadeath.*

*The more you know ★*
> 5 votes

# Answer
Something not mentioned by others yet:

Disabling graphics features might be a valid **workaround for problems with a certain setup**, unrelated to performance.

Just one example, some graphics options simply don't work correctly with a given rendering engine when running a Windows game on Wine (the Windows compatibility layer for Linux).

For a certain (intentionally unnamed) game, I need to tune down filtering to trilinear, and disable reflections. Not because my rig is not up to it (it certainly is), but because of rendering glitches and crashes if I don't.

In another game, you had to disable "fog" effects for any rig running nVidia cards (even on native Windows), because they always rendered the fog 100% opaque.

---

Something that *is* mentioned in other answers / comments, but is actually a reason **not** to make certain settings (like foliage density, gras) optional:

**Visibility of opponents in competitive games.**

If players can gain a competitive advantage by setting the "looks" of your game to "really bad", you're hurting the game experience in two ways:

* competitive players will only get to see a "bad looking" game;
* recreational players will be at a (potentially significant) disadvantage unrelated to skill, simply for preferring a good-looking game.

Avoid that if at all possible. Make gras and foliage look clunky for low-performance rigs, but make sure that lower settings do not give a gameplay advantage.
> 5 votes

# Answer
## Clarity of view in competitive games

Players in competitive online games may well prefer a simpler or clearer view to a more beautiful view even if performance is not a concern - many visual options add visual realism but obscure the things that players actually want to see.

It may easily be that in your game it is easier to notice or target an enemy if you configure the game client to disable all kinds of extra grass or leaves, special effects, smoke/fog/fire, etc. This places players who enable such effects at a disadvantage.
> 4 votes

# Answer
The other answers are good, but I think they lack good examples of actual effects that you might want to turn off.

For me, the really cheap and awful "motion blur" that for example GTA3 had, made the game worse. Luckily I could turn it off.

Haven't played it, but what I've seen from GTA5 is another quite hacky solution that i would disable if I ever try GTA5. (see https://www.youtube.com/watch?v=VjIhl8hbO18)
> -1 votes

---
Tags: graphics-programming, scalability
---


# Question
Title: Trying to get two variables to stay in sync between 2 scripts. Anyone know what the issue is?
Basically I am making an inventory system where the player has a set amount of objects, and if they go to a pickup then it will give them more of that particular type of object. I have two problems currently. First the pickup script does indeed find the value, and update it properly. However when I go to update the value from the inventory script it keeps changing it back to it's last known value, and consequently keep it a static variable.

The other lesser issue is my OnTriggerEnter portion of the pickup system only adds once, and then stops despite the log telling me it is still detecting objects.

First script is the inventory system...

```
using UnityEngine;
using System.Collections;

public class InventoryManager : MonoBehaviour {

    public Rigidbody Shape1;
    public Rigidbody Shape2;
    public Rigidbody Shape3;
    public Rigidbody Shape4;
    public Rigidbody Shape5;

    public float Shape1Amount;
    public float Shape2Amount;
    public float Shape3Amount;
    public float Shape4Amount;
    public float Shape5Amount;

    public float Shape1AmountUpdated;

    public Transform SpawnLoc;
    public Transform SpawnLoc2; //I had to make this due tot he fact because it doesn't like to spawn centered properly :(.

    public float coolDown;
    public float coolDownTimer;

    // Use this for initialization
    void Start () {

    }

    // Update is called once per frame
    void Update ()
    {
        Shape1AmountUpdated = GameObject.Find("PickUp").GetComponent<PickUpSystem>().ShapeValue1; //This was my attempt at trying to *tell* the pick up system the new amount, but it didn't quite work.
        Shape1Amount = Shape1AmountUpdated;

        if (coolDownTimer > 0) // If it's above it will subtract from timer.
        {
            coolDownTimer -= Time.deltaTime;
        }

        if (coolDownTimer < 0) // Checks that cd timer isn't below zero.
        {
            coolDownTimer = 0;
        }

        if (Input.GetKeyDown("1") && coolDownTimer == 0 && Shape1Amount > 0)
        {
            Rigidbody ShapeToSpawn1;
            ShapeToSpawn1 = Instantiate(Shape1, SpawnLoc.position, SpawnLoc.rotation) as Rigidbody;
            coolDownTimer = coolDown;
            Shape1Amount = Shape1Amount - 1;
        }
        if (Input.GetKeyDown("2") && coolDownTimer == 0 && Shape2Amount > 0)
        {
            Rigidbody ShapeToSpawn2;
            ShapeToSpawn2 = Instantiate(Shape2, SpawnLoc2.position, SpawnLoc.rotation) as Rigidbody;
            coolDownTimer = coolDown;
            Shape2Amount = Shape2Amount - 1;
        }
        if (Input.GetKeyDown("3") && coolDownTimer == 0 && Shape3Amount > 0)
        {
            Rigidbody ShapeToSpawn3;
            ShapeToSpawn3 = Instantiate(Shape3, SpawnLoc2.position, SpawnLoc.rotation) as Rigidbody;
            coolDownTimer = coolDown;
            Shape3Amount = Shape3Amount - 1;
        }
        if (Input.GetKeyDown("4") && coolDownTimer == 0 && Shape4Amount > 0)
        {
            Rigidbody ShapeToSpawn4;
            ShapeToSpawn4 = Instantiate(Shape4, SpawnLoc2.position, SpawnLoc.rotation) as Rigidbody;
            coolDownTimer = coolDown;
            Shape4Amount = Shape4Amount - 1;
        }
        if (Input.GetKeyDown("5") && coolDownTimer == 0 && Shape5Amount > 0)
        {
            Rigidbody ShapeToSpawn5;
            ShapeToSpawn5 = Instantiate(Shape5, SpawnLoc.position, SpawnLoc.rotation) as Rigidbody;
            coolDownTimer = coolDown;
            Shape5Amount = Shape5Amount - 1;
        }
    }
}

```

And here is the pickup system itself...

```
using UnityEngine;
using System.Collections;

public class PickUpSystem : MonoBehaviour {

    public float ShapeValue1;
    public float ShapeValue2;
    public float ShapeValue3;
    public float ShapeValue4;
    public float ShapeValue5;

    private float oldShapeValue1;
    private float oldShapeValue2;
    private float oldShapeValue3;
    private float oldShapeValue4;
    private float oldShapeValue5;

    private float ShapeValue1Updated;

    // Use this for initialization
    void Update ()
    {
        oldShapeValue1 = GameObject.Find("Main Camera").GetComponent<InventoryManager>().Shape1Amount;
        oldShapeValue2 = GameObject.Find("Main Camera").GetComponent<InventoryManager>().Shape2Amount;
        oldShapeValue3 = GameObject.Find("Main Camera").GetComponent<InventoryManager>().Shape3Amount;
        oldShapeValue4 = GameObject.Find("Main Camera").GetComponent<InventoryManager>().Shape4Amount;
        oldShapeValue5 = GameObject.Find("Main Camera").GetComponent<InventoryManager>().Shape5Amount;
    }

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

    //}

    void OnTriggerEnter (Collider other)
    {
        if (ShapeValue1 > 0)
        {
            Debug.Log("Object detected!");
            ShapeValue1 = oldShapeValue1 + 1; //Fix me. I only add 1 on the first collision afterwards I won't add anymore.
        }
    }
}

```

Anyone know how I should be "syncing" the two variables? Basically the ShapeAmount1 value should always be equal to the ShapeValue1 in the other script.

# Answer
When trying to keep 2 variables in 2 different scripts synced you should update them both from only one script. Scripts don't run at the same time, and it is hard, if not impossible, to keep track of what order the scripts run in. Also to keep in mind is that Update functions will not run simultaneously with trigger / collider functions. The physics engine has it's own `Update` function called `FixedUpdate`.

Please have a look at this page (http://docs.unity3d.com/Manual/ExecutionOrder.html) for some more information on this.

For a solution to your problem, you should get rid of the variable updating code in your InventoryManager's `Update`, and update the variable there from the `Trigger` function in your pick-up system where the variable actually gets updated (See code below). Or use volvis' answer.

A little side note: The "find" function is very heavy and is never a good idea to use in an Update function.

As for the problem of your trigger only updating once, this is because the `OnTriggerEnter` only fires once when the trigger is entered. To keep updating while in the trigger, you need to use `OnTriggerStay`.

```
    // Use OnTriggerStay instead of OnTriggerEnter
    void OnTriggerStay (Collider other)
    {
        if (ShapeValue1 > 0)
        {
            Debug.Log("Object detected!");
            ShapeValue1 = oldShapeValue1 + 1;
            // After Updating send the updated variable back to the InventoryManager
            // Or just update the variable in the InventoryManger directly
            GameObject.Find("Main Camera").GetComponent<InventoryManager>().Shape1Amount = ShapeValue1;
        }
    }

```

Using this in your pickup system script and removing the variable update in the inventory manager should fix your problems.
> 4 votes

# Answer
One way about it is moving your shared variables into a ScriptableObject instance and passing that to components that require access to them. Something like--

```
using UnityEngine;

[CreateAssetMenu()]
public class MySharedStuff : ScriptableObject {
    public float SharedFloat {get; set;}
}

public class ObjectUsingSharedStuff : MonoBehaviour {
    [SerializeField]
    MySharedStuff mySharedStuff;
}

```

The ScriptableObject is passed as a reference so they're always 'in sync'.
> 0 votes

# Answer
Generally, you can sync variables between two scripts by making instance of script. Make instance of `InventoryManager` like below:

```
public static InventoryManager instance
//public variables

void Awake()
{
    MakeInstance ();
}

void MakeInstance()
{
    if (instance == null) {
        instance = this;
    }
}

```

And use public variables in another script like below,

```
ScriptName.instance.variableName

```
> 0 votes

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


# Question
Title: Unity - Copy another object's Y location?
I'm creating a Pong clone inside of Unity and was trying to figure how to copy another object (In this case being the Y co-od of the Ball Object) How would i go about doing this? I'm using vectors as my method of paddle movement and I want to create a public int AISpeed so that the AI paddle is a little slower in comparison

In my mind I assumed it was along the lines of: **rightPaddle.location.y = pongBall.location.y**

How would I create this?

# Answer
Assuming that rightPaddle and pongBall are both game objects, your code would look something like the following:

```
Vector3 paddleOldPos = rightPaddle.transform.position;
Vector3 ballPos = pongBall.transform.position
Vector3 newPos = new Vector3(paddleOldPos.x, ballPos.y, paddleOldPos.z);

rightPaddle.transform.position = newPos;

```

You can't modify a transform's position directly, you'll have to overwrite it, as above.

Hope that helps :-)
> 2 votes

---
Tags: unity, rigidbody
---


# Question
Title: Updating a gameobject position that needs to be consistent across all players' games
I am creating a real time multiplayer game in Unity 3d using Google Player Services that has a ball that the players will interact with. I'm not particularly sure how I will update the ball's position on all of the games though. I have each player sending updates for their positions and all of that but with the ball being interacted with by all players I'm not sure how to figure out who's update of the ball position I should take.

# Answer
> 1 votes
> I'm not sure how to figure out who's update of the ball position I should take.

One way to handle this problem is to introduce the concept of *authority* over an object. It's particularly useful in games that aren't backed by a dedicated server process (if there *is* a dedicated server, just make the server the authority for the ball's simulation).

The client that has "authority" over a particular object is the one responsible for the simulation of that object that everybody else eventually sees. Even if each client does some local prediction of the ball movement (which they probably should), they will ultimate defer to the authoritative corrected state of the ball sent to them from the client with authority *over* that ball.

Grant authority to a client when that client first interacts with the ball in some fashion. That client retains authority over the ball until some other client touches or interacts with it. While a client has authority, it's the one responsible for periodically sending updates to everybody else.

You'll need some form of consistent timestamp or token mechanism to resolve who wins in the event that two clients interact with the ball at approximately the same time.

---
Tags: unity, multiplayer, google-play-services, realtime
---


title: What is differential scrolling?

text:
# Question
Title: What is differential scrolling?
I have seen the term a few times (e.g. here). I tried looking it up but did not find much information. I thought it would be something like parallax-scrolling, but I have seen suggestions otherwise (e.g. here). What is the difference?

# Answer
> 2 votes
Parallax scrolling could be seen as a *kind* of differential scrolling.

Differential scrolling is simply an effect whereby two (or more) pieces of content scroll at different rates proportional to the *differences* in some property shared between the pieces of content. For example, as in the demos linked in your second example. The three vertical columns of text in this example scroll at different rates (based on their length), but they aren't three distinct nested scrollable areas of content. The entire page still scrolls as one unit, but the shorter columns of text move less per unit of scroll because there is less content overall for them to scroll through.

Parallax scrolling is a kind of differential scrolling trying to achieve a certain effect, specifically a parallax effect:

> /ˈparəˌlaks/ (noun) the apparent displacement of an observed object due to a change in the position of the observer

In parallax scrolling, you're moving multiple pieces of content (foreground and background layers) differently in proportion to their "distance from the viewer" property to make it appear that the background is displaced more per unit change of the "viewpoint" (even though the viewpoint may not actually be moving, you're just scrolling the background by).

---
Tags: 2d, terminology, parallax-scrolling
---


title: Pass Vector2 to Instantiated GameObject

text:
# Question
Title: Pass Vector2 to Instantiated GameObject
I am trying to get an AI sprite to randomly shoot a SINGLE bullet while walking around. This is a 2D Top-down perspective. The sprite can move up, down, left and right. It randomly changes directions.

When I call the `ShootBullet()` function, the bullet just sits at were it is instantiated.

The Sprite has a ***WalkingController*** attached to it that calls a bullet prefab. The bullet prefab has a script that just handles the movement.

How do I get the bullet to know which direction it should travel when it is created?

I am trying to AVOID the use of the `FindObjectWithTag` methods. As I have been learning, it seems that - that specific tag is slow.

I really appreciate any help while I am learning!

**WALKING SCRIPT** This script is also generic so I could attach different enemies with the same setup.

```
public class WalkingController : MonoBehaviour {

    public Animator    anim;
    public Rigidbody2D body;
    public float moveSpeed  = 0.75f; //HOW FAST THE ENEMY WALKS

    //DEALS WITH SHOOTING BULLET
    public GameObject   objectToSpawn; //WHICH BULLET TO SHOOT
    public float        shootDamage     = 1.0f;
    public float        timeToSpawn     = 1.0f;
    private float       internalTimer   = 2.0f;

    //Holds the direction the enemy should move
    public Vector2 enemyMovement;

    void Awake() {
        anim = GetComponent<Animator> ();
        body = GetComponent <Rigidbody2D> ();
    }

    void Start () {
        StartCoroutine ("ChangeDirection");
    }

    void Update() {

        //WHEN TO SHOOT A BULLET
        this.internalTimer += Time.deltaTime;

        if (this.internalTimer > this.timeToSpawn) {
            this.ShootBullet();
            this.internalTimer = 0.0f;
        }
    }

    void FixedUpdate () {
        //THIS MOVES THE ENEMY
        body.MovePosition (body.position + enemyMovement * moveSpeed * Time.deltaTime);
    }

    private void ShootBullet() {
        //THIS FIRES THE BULLET
        Instantiate(objectToSpawn, this.transform.position, Quaternion.identity);

        //HOW DO I MAKE THE BULLET MOVE?????
         gameObject.Direction(enemyDirection);

        //HOW DO I PASS HOW MUCH DAMAGE BULLET HAS??

    }

    public Vector2 getEnemyMovement() {
        //TRIED MAKING A PUBLIC ACCESSOR FOR THE BULLET TO ACCESS, BUT DIDN'T WORK
        return enemyMovement;
    }

    IEnumerator ChangeDirection() {
        //RANDOMLY CHANGE THE ENEMY DIRECTION
        while(true){
            yield return new WaitForSeconds(Random.Range (0.3f, 1.5f));
            randomDirection();
        }
    }

    void randomDirection() {
        switch(Random.Range (0,3)){
            case 0:
                //Debug.Log ("Moving enemy Up");
                 enemyMovement = new Vector2 (0,1);
                break;
            case 1:
                //Debug.Log ("Moving enemy Right");
                 enemyMovement = new Vector2 (1,0);
                break;
            case 2:
                //Debug.Log ("Moving enemy Down");
                 enemyMovement = new Vector2 (0,-1);
                break;
            case 3:
                //Debug.Log ("Moving enemy Left");
                 enemyMovement = new Vector2 (-1,0);
                break;
            default:
                 enemyMovement = new Vector2 (0,0);
                break;
        }
        anim.SetBool ("Walking", true);
        DefineFacingDirection (enemyMovement);

    }

    void DefineFacingDirection (Vector2 vec){
        //THIS IS FOR THE ANIMATOR TO PLAY THE CORRECT ANIMATION
        anim.SetFloat ("InputX", vec.x);
        anim.SetFloat ("InputY", vec.y);
    }
}

```

**PROJECTILE SCRIPT** I wanted this script to be pretty generic, so I could attached any animation or prefab to it so i could have different bullets. ie rocks, arrows, throwing stars etc...

```
public class Projectile : MonoBehaviour {

    public float        moveSpeed = 4.0f;

    //Tried to make the direction public so we could set it on creation, didn't work.
    public Vector2  Direction { get; set; }

    private Rigidbody2D body;

    void Awake() {
        body = gameObject.GetComponent<Rigidbody2D> ();
    }

    void FixedUpdate(){

        body.MovePosition (transform.position + Direction * moveSpeed * Time.deltaTime);
    }

}

```

UPDATE I tried just making the bullet move by placing it on the scene. Using the below code. It doesn't move when I add `body.MovePosition (transform.position + transform.forward * moveSpeed * Time.deltaTime);` but if I remove transform.forward the bullet moves to the center of the screen. There are no other scripts attached to the bullet.

```
public float     moveSpeed = 4.0f;
    public Rigidbody2D body;

    void FixedUpdate(){
        body.MovePosition (transform.position * moveSpeed * Time.deltaTime);
    }

```

# Answer
Couple of things you are using in wrong way. Basically it is just the matter of concept.

* `Instantiate` will give you an `Object` in return. So whatever you want to do with instantiated object, you have to keep reference of that.
* `gameObject.Direction`, actually `gameObject` always represents the `GameObject` on which that very script is attached.

So what you have to do is simply

* `Instantiate` your bullet
* Keep reference of that `Object`
* Get the script attached to your bullet prefab

Change your `ShootBullet` method as,

```
        GameObject bullet = Instantiate(objectToSpawn, this.transform.position, Quaternion.identity) as GameObject;
        bullet.GetComponent<Projectile>()._direction = enemyDirection;

```

Now on other hand, your `Projectile` script should look like,

```
public class Projectile : MonoBehaviour {

    public float _moveSpeed = 4.0f;

    public Vector2  _direction = Vector2.zero;

    private Rigidbody2D _body;

    void Awake() {
        _body = gameObject.GetComponent<Rigidbody2D> ();
    }

    void FixedUpdate(){
        _body.position = _body.position + _direction.normalized * _moveSpeed * Time.deltaTime;
    }

}

```

Now it should work if you provide proper direction.
> 3 votes

# Answer
They have an example of this in the Unity API docs actually.

```
 Rigidbody clone;
 clone = Instantiate(projectile, transform.position, transform.rotation) as Rigidbody;
 clone.velocity = transform.TransformDirection(Vector3.forward * 10);

```

Instantiate returns an Object reference then you can cast to the desired type using the as statement. In your case you would just do `as GameObject`, then call `GetComponent<Projectile>().Direction = enemyDirection;` on the returned and casted GameObject variable.
> 0 votes

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


title: How do I get a vector from an angle?

text:
# Question
Title: How do I get a vector from an angle?
I want a ship to move forward in the direction it's facing when you press the up key, but I don't know how to get a normalized vector from the angle the ship is facing. Can someone show me what code is necessary for moving something in a direction based on an angle?

# Answer
Consider trigonometry's unit circle (image source):

Any (`x`, `y`) point on this circle is given by (`cos(theta)`, `sin(theta)`), where `theta` is the angle from the x-axis. Assuming your facing angle is defined the same way (which it should be, because things will be easier for you), you can get a heading vector simply by using the (`x`, `y`) point on the unit circle as the x and y coordinates of your heading vector:

```
heading = [math.cos(angle), math.sin(angle)]

```

Since the unit circle has a radius of one, the length of the vector will also have a length of one, so it's already normalized for you.
> 4 votes

---
Tags: vector, pygame
---


# Question
Title: Player moving back and forth when moving with camera LIBGDX
I have a problem. When in libGDX my player moves across the screen and the camera is moving after him the player jumps back and forth a bit. Player still moves forward but it looks goofy

*I'm moving left-up*

```
package com.qookie.miner;
import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx.*;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.freetype.FreeTypeFontGenerator;
import com.badlogic.gdx.graphics.g2d.freetype.FreeTypeFontGenerator.FreeTypeFontParameter;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.audio.*;
import com.badlogic.gdx.Input.Keys;

public class MinerMain extends ApplicationAdapter {
SpriteBatch batch;
SpriteBatch b;
private OrthographicCamera camera;
private float timer;
private int rand;
Texture img;
Texture map;
FreeTypeFontGenerator generator;
FreeTypeFontParameter parameter;
BitmapFont font;
private int speed = 250;
GameObject player;

@Override
public void create () {
    batch = new SpriteBatch();
    b = new SpriteBatch();
    img = new Texture("images/player.png ");
    map = new Texture("map1_fixed.png");
    generator = new FreeTypeFontGenerator(Gdx.files.internal("fonts/VCR_OSD_MONO_1.001.ttf"));
    parameter = new FreeTypeFontParameter();
    parameter.size = 10;
    parameter.color = Color.WHITE;
    font =  generator.generateFont(parameter);
    generator.dispose();
    player = new GameObject(img);
    camera = new OrthographicCamera(800,480);

}

@Override
public void render () {
    update();
    Gdx.gl.glClearColor(1, 0, 0, 1);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

    //Normal rendering(map, player, objects, enemies)
    batch.begin();
        batch.draw(map,0,0);
        batch.draw(player.getTexture(),player.x,player.y);
    batch.end();

    // GUI rendering(always in the same spot on the screen)
    b.begin();
        font.draw(b,"0_01a",4,476);
    b.end();
}

public void update() {
    //batch.setProjectionMatrix(camera.combined);
    //camera.position.set(player.x+player.width/2,player.y+player.height/2,0);
    //camera.update();
    if(Gdx.input.isKeyPressed(Keys.W)){
        player.y += speed * Gdx.graphics.getDeltaTime();
    }

    if(Gdx.input.isKeyPressed(Keys.A)){
        player.x -= speed * Gdx.graphics.getDeltaTime();
    }

    if(Gdx.input.isKeyPressed(Keys.S)){
        player.y -= speed * Gdx.graphics.getDeltaTime();
    }

    if(Gdx.input.isKeyPressed(Keys.D)){
        player.x += speed * Gdx.graphics.getDeltaTime();
    }

    if(Gdx.input.isKeyPressed(Keys.ESCAPE)){
        Gdx.app.exit();
    }

    timer += Gdx.graphics.getDeltaTime();

    rand = MathUtils.random(10);
    batch.setProjectionMatrix(camera.combined);
    camera.position.set(player.x+player.width/2,player.y+player.height/2,0);
    camera.update();
}
@Override
public void dispose() {
    font.dispose();
    batch.dispose();
    img.dispose();
    b.dispose();
}
}

```

GameObject.java file:

```
package com.qookie.miner;
import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.*;
import com.badlogic.gdx.graphics.g2d.*;
import com.badlogic.gdx.math.*;

public class GameObject extends Rectangle {
private Texture txt;
public Texture getTexture() {
return txt;
}
public GameObject(Texture t) {
this.txt = t;
this.width = t.getWidth(); this.height = t.getWidth();
  }

}

```

# Answer
If I remember correctly, SpriteBatch stores it's own matrices. This means that when you do:

```
batch.setProjectionMatrix(camera.combined);
camera.position.set(player.x+player.width/2,player.y+player.height/2,0);
camera.update();

```

the camera should be updated first, then the projection matrix set after the update, instead. So instead I believe it should be:

```
camera.position.set(player.x+player.width/2,player.y+player.height/2,0);
camera.update();
batch.setProjectionMatrix(camera.combined);

```

This may be the cause of your problem, but I'm not entirely sure - good luck, and I hope this helps!
> 1 votes

---
Tags: java, libgdx
---


title: Sprite Sheet Texture not being rendered

text:
# Question
Title: Sprite Sheet Texture not being rendered
I'm making space invaders (in OpenGL/SDL) and I've run into a problem when trying to draw the sprite for the spaceship from the spritesheet. In my entity class, I have a pointer for the sprite that belongs to the current instance of the object. In main, I make an instance on the heap of the sheetSprite, passing in the u,v,width, and height of the sprite for the parameters and then storing this reference in the mySprite field of the spaceship entity.

The coordinates provided by the texture atlas are: `<SubTexture name="playerShip2_green.png" x="112" y="866" width="112" height="75"/>`

To draw the spaceship, I call the draw method from its "mySprite" attribute. For some reason, only a white square is being rendered without the actual texture. What could be causing the problem? The relevant code is below:

```
class SheetSprite {
public:

    SheetSprite(unsigned int textureID, float u, float v, float width, float height, float size, ShaderProgram program)
        :textureID(textureID), u(u), v(v), width(width), height(height), size(size), program(program) {}

    void Draw() {
        //glBindTexture(GL_TEXTURE_2D, textureID);
        glUseProgram(program.programID);
        GLfloat texCoords[] = {
            u, v + height,
            u + width, v,
            u, v,
            u + width, v,
            u, v + height,
            u + width, v + height
        };
        float aspect = width / height;
        float vertices[] = {
            -0.5f * size * aspect, -0.5f * size,
            0.5f * size * aspect, 0.5f * size,
            -0.5f * size * aspect, 0.5f * size,
            0.5f * size * aspect, 0.5f * size,
            -0.5f * size * aspect, -0.5f * size ,
            0.5f * size * aspect, -0.5f * size };
        glBindTexture(GL_TEXTURE_2D, textureID);
        //float vertices2[] = { -0.5, -0.5, 0.5, -0.5, 0.5, 0.5, -0.5, -0.5, 0.5, 0.5, -0.5, 0.5 };
        glVertexAttribPointer(program.positionAttribute, 2, GL_FLOAT, false, 0, vertices);
        glEnableVertexAttribArray(program.positionAttribute);
        //float texCoords2[] = { 0.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 1.0, 1.0, 0.0, 0.0, 0.0 };
        glVertexAttribPointer(program.texCoordAttribute, 2, GL_FLOAT, false, 0, texCoords);
        glEnableVertexAttribArray(program.texCoordAttribute);
        glDrawArrays(GL_TRIANGLES, 0, 6);
        glDisableVertexAttribArray(program.positionAttribute);
        glDisableVertexAttribArray(program.texCoordAttribute);
    }
    float size;
    unsigned int textureID;
    float u;
    float v;
    float width;
    float height;
    ShaderProgram program;
};

class Entity {

public:
    Matrix modelMatrix, projectionMatrix, viewMatrix;
    float width, height = 1.0;
    float xDir, yDir = 0.0;
    float posX, posY = 0.0;
    float objSpeed = 0.0;
    float rotState = 0.0;
    float u, v, spr_width, spr_hght, spr_size = 0.0;
    unsigned int textureID;
    ShaderProgram program;
    //GLuint spriteSheetTexture = LoadTexture("sheet.png");
    SheetSprite* mySprite;

    Entity(float wid, float hght, float xDirect, float yDirect,
        float xPosition, float yPosition, float speed, float rState, ShaderProgram program) : width(wid), height(hght),
        xDir(xDirect), yDir(yDirect), posX(xPosition), posY(yPosition), objSpeed(speed), rotState(rState), program(program) {}

//Extra methods
};

//instantiation of sheetSprite in main

Entity spaceship(0.1f, 0.7f, 1.0f, 1.0f, -5.1f, 0.0f, 3.0f, 0.0f, program);
    spaceship.objSpeed = 10;

    GLuint spriteSheetTexture = LoadTexture("sheet.png");
    spaceship.mySprite = new SheetSprite(spriteSheetTexture, 112.0f / 1024.0f, 866.0f / 1024.0f, 112.0f / 1024.0f, 75.0f / 1024.0f, 0.7, program);

//in the game loop

spaceship.mySprite->Draw();

```

# Answer
> 0 votes
The problem was that the shader program needed to be passed to the SheetSprite class as a pointer instead of just being passed as an object.

---
Tags: opengl, c++, textures, sprites, sdl
---


title: Calculating interpolation percentages

text:
# Question
Title: Calculating interpolation percentages
I've been reading valve's article on multiplayer networking repeatedly recently and everything is starting to make since. One thing I'm wondering on though however is what percentage value to use for interpolation. For example the article shows this image:

Then the following explanation is given:

> The last snapshot received on the client was at tick 344 or 10.30 seconds. The client time continues to increase based on this snapshot and the client frame rate. If a new video frame is rendered, the rendering time is the current client time 10.32 minus the view interpolation delay of 0.1 seconds. This would be 10.22 in our example and all entities and their animations are interpolated using the correct fraction between snapshot 340 and 342.

At the end of the last sentence it states to use "the correct fraction between snapshot 340 and 342". What would this fraction be? Is it the time it takes for a frame to render?...or am I way off?

# Answer
> 2 votes
Client 1 has a frame-rate of 120Hz, meaning each frame is 8.333mS.
Client 1 has a tick-rate of 20Hz, meaning each tick is 50mS.

Each `Update(float deltaTime)` on Client 1 is, therefore:

```
 8.333mS / 50mS = 16.6% of a tick

```

For each tick, Client 1 `Updates()` and `Renders()` about 6 times and each `Update()` increases the lerp by about 16.6%.

Client 2 has a frame-rate of 60Hz, meaning each frame is 16.666mS.
Client 2 never received tick 342 and is interpolating between 340 and 344.
Client 2 is lerping 2 tick's worth of time, therefore:

```
 16.666mS / 100mS = 16.6% of two ticks

```

Between those two ticks, Client 2 `Updates()` and `Renders()` about 6 times and each `Update()` increases the lerp by about 16.6%.

---
Tags: multiplayer, interpolation
---


title: Unity, shader, vertexID

text:
# Question
Title: Unity, shader, vertexID
I'm writing a shader and I just wanna ask if it's possible to get the ID of the vertex that is currently being manipulated. I read something about gl\_vertexID, but I couldn't find out if that is something I can use.

# Answer
> 0 votes
Answer: Added the vertexIDs in a second uv(set x value to the id) channel in the mesh(from my c# code), and then in the shader I could use the ids as I needed, example:

```
     void function(inout appdata_full v)
     {
          int vertexID = v.texcoord1[0];
          ...
     }

```

# Answer
> 1 votes
I don't seem to have much trouble doing this. Here's a sample vert shader input struct:

```
struct VS_INPUT
{
 float4 pos        : POSITION;
 float3 norm       : NORMAL;
 float2 uv         : TEXCOORD0;
 float4 col        : COLOR0;
 uint   id         : SV_VertexID;
};

```

Good luck! I hope it helps!

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


# Question
Title: Updating a multithreaded Entity-Component-System
I am currently trying to implement an (sort-of) Entity-Component-System. I've got the gist of it, that is, how an ECS is supposed to work. So far i have 4 classes in my design (not yet fully implemented): `EntityWorld` is a global container for systems, entities and their respective components. It is responsible for updating systems/stepping. `EntitySystem` represents the base class for a system, with a virtual update-function. `Entity` is a container, basically with a list of components and an id, nothing more. `EntityComponent` represents a component. Now, i thought about making it possible to multithread my systems, but i think i've ran into a problem here. Suppose my `EntityWorld` stores its entities in the simplest way possible, in a `std::vector<Entity*>` for example. Now, that list would either be fully passed to a system when it is updated, or the `EntityWorld` loops through this list and sends the entities to the systems one-by-one. In my understanding though, when using multiple threads, this would require me to lock the whole list every time a system is being updated. That would practically equal zero increase in performance, since the other threads are always waiting for the list to get free. Is there a better way to implement this? So multiple threads can be updated (and r/w to entites at the same time)? Thanks in advance!

# Answer
The simple version: don't.

One could argue that you have perhaps a slight misunderstandings about how to build an ECS (why would you sent a list of Entity\* to a system to update? the System is supposed to have its own self-contained collection of the components it cares about, and the global entity list should barely ever even be used... a "true" ECS doesn't even *have* an `Entity` object!).

Even if you fixed that, though, Systems in an ECS sense aren't the conceptual blocks that you want to thread. That leads right back into the old-school mentality of putting physics on one thread and graphics on another, which scales poorly and schedules worse (what happens when you have more cores than Systems? what happens when you have more Systems than cores?).

One alternative simple approach that is the fork-join model of parallelism. e.g., your `PhysicsSystem::Update` spawns a bunch of jobs for your worker threads and then waits for all those jobs to complete. No other System updates in parallel to each other; you're sequentially updating Systems but allowing those updates to go as wide as possible.

A more complex approach would be to build a full task system. Doing this very well, however, turns out to be at strong odds with an ECS approach. The problem is that ECS still relies on shared data (e.g., multiple Systems using the exact same TransformComponent) rather than having their own copies of the data.

Which is one of the many many reasons that I tell people to *not* use ECS. It's an over-complicated, over-constrained form of component-based design. I'll explain an alternative; bare with me, it's topical to the question. :)

Your components should be little more than glue to your low-level modules. e.g. your PhysicsComponent just contains a pointer/id that references the Box2D/Havok/PhysX body and its sole purpose is to help provide a mapping between EntityID and the physics body object. Then the physics module has its own internal data structure for physics that neither knows nor cares about your entity system.

You're forced to do this with third-party middleware, but you should build your own modules the same way. Your graphics engine should not have even the slightest clue what an entity or a component is. It should have its own internal data structures for rendering. Those data structures could have entries that correspond to entities or even entries that have nothing to do with entities. Your ModelComponent just glues your Entity to one (or more!) of the nodes in that internal structure.

Now you can freely thread your modules, as they have zero dependencies upon each other. There's some synchronization points where you copy the transform data out of physics, feed it into graphics and game logic, and then feed inputs from game logic back into physics, but that synchronization is potentially just a memcpy (but probably a loop of some kind). The entity architecture plays no part in threading, or really anything performance-sensitive at all.
> 11 votes

---
Tags: c++, entity-system, component-based, entity-component, entity
---


# Question
Title: How can I play user-provided music stored on the phone inside my game?
I am creating a car game. Is any way to play the music stored on the phone inside the game? I'd like the player to choose files that are already on their device and hear them played in the game.

For example, in GTA Vice City game there was a folder named *Music,* and if we placed songs in there they would play on the car radio while we're driving around inside the game. If we want to switch the songs around, we can do so. how can I do the same in Android and iOS?

I am using unity 5.2, C#.

# Answer
> 3 votes
It is possible to do so. Given a directory, unity's WWW class will be able to obtain the file using the URL. You can then create a clip with that file and pass it to the audio source.

Do note that you will have to either hard code a directory on the phone, use a navigator to allow the user to select the folder or create a searcher to find all audio files.

Use `file://<filepath>` to access a local resource. Do take note that different devices have different file structure and you have to adapt for each of them.

---
Tags: unity, c#, android, ios, music
---


# Question
Title: Play an effect where a sprite touches a trigger
I have a sprite-based GameObject in Unity to which is attached a RigidBody and a Collider2D. When this GameObject comes into contact with a particular Collider2D Trigger, I want a particle effect to play *at the point of contact*. This sounds extremely simple to set up and yet I can't seem to find any solution that works, since OnTriggerEnter2D doesn't bother to provide hit coordinates.

Please note that the trigger represents a non-solid space, so adding a solid (non-trigger) collider for hit detection is not a solution.

The sprite is large, so I can't just play the particle effect at its transform position. Raycast is not an appropriate solution for this problem; it doesn't handle nearly enough cases.

# Answer
> 1 votes
You could use raycast:

If transform.forward isn't right, use whatever vector that represents that direction the object is going in.

```
OnTriggerEnter(Collider other){
  RaycastHit hit;
  if (Physics.Raycast(transform.position, transform.forward, out hit))
  {
    // do something with hit.point
  }
}

```

---
Tags: collision-detection, unity
---


# Question
Title: Old Age: Decreasing stats/attributes as characters level up
I just had an off the cuff idea of decreasing stats (strength/speed/stamina) as players level up. After all, higher level characters should have higher level of challenge! (And it's not hard to rationalize as a character aging & weakening process)

I would put a minimum on the decrease, of course, and provide items, armor, and skills to provide increased offense and defense by active actions.

I haven't seen this done in any game I can remember, though. What are the downsides that I'm probably missing? *(apart from player dis-incentivizing)*.

# Answer
I have never seen a game do this either. This is how I would design it so that hopefully there is an incentive to level up:

At the beginning, when the character is young, they will be able to use the brute-force method. The character will have no issue wiping out waves of low-level grunts. The issue arises when the player encounters more intelligent enemies who can avoid or outsmart these simple attacks. The player has no means of fighting them because they aren't smart enough.
As the player ages they will no longer have the strength they once had. However, they will have gained *wisdom*, which will allow them to outsmart those highly intelligent enemies. In fact, when speaking in terms of *potential*, the older player can be more effective. Strategy is more powerful than brute-force.

In this design, enemies don't become much more powerful, but they do get smarter and smarter (which possibly means better AI). Here, the *wisdom* stat is your magical power. You might be able to turn this into something other than magic, but the same basic idea applies. Slowly degrade the players strength but slowly reveal to them new dynamics of strategy.

This design gives players an incentive to level up, even though they will degrade other stats. This will also increase the level of challenge throughout the game because it gradually forces the player to use more intelligent strategies.

So, to answer your question: The downside to this (well, not a downside, just a challenge) is you have to be very clever with how you intend the player to use strategy. You have to design it in such a way that the player *must* use strategy to advance. You have to design it so that the ability to use strategy is more desirable (and more satisfying) than the ability to use brute-force. You have to make enemies intelligent as well (or make them seem intelligent while simply having puzzling loopholes in their defenses), which is obviously difficult to pull off.
> 3 votes

---
Tags: rpg, character, levels
---


title: How to smooth hand drawn lines?

text:
# Question
Title: How to smooth hand drawn lines?
So I am using Kinect with Unity.

With the Kinect, we detect a hand gesture and when it is active we draw a line on the screen that follows where ever the hand is going. Every update the location is stored as the newest (and last) point in a line. However the lines can often look very choppy.

Here is a general picture that shows what I want to achieve:

With the red being the original line, and the purple being the new smoothed line. If the user suddenly stops and turns direction, we think we want it to not exactly do that but instead have a rapid turn or a loop.

My current solution is using Cubic Bezier, and only using points that are X distance away from each other (with Y points being placed between the two points using Cubic Bezier). However there are two problems with this, amongst others:

1) It often doesn't preserve the curves to the distance outwards the user drew them, for example if the user suddenly stop a line and reverse the direction there is a pretty good chance the line won't extend to point where the user reversed the direction.

2) There is also a chance that the selected "good" point is actually a "bad" random jump point.

So I've thought about other solutions. One including limiting the max angle between points (with 0 degrees being a straight line). However if the point has an angle beyond the limit the math behind lowering the angle while still following the drawn line as best possible seems complicated. But maybe it's not. Either way I'm not sure what to do and looking for help.

Keep in mind this needs to be done in real time as the user is drawing the line.

# Answer
You could try using Chaikin's smoothing algorithm. It's an alternative to using spline curves.

In this article, which details an implementation of a swipe gesture in the style of Fruit Ninja's swiping, you can see a couple of steps taken to first simplify and then smoothen the input points to generate the swipe path.
> 1 votes

---
Tags: mathematics, kinect, lines
---


title: Creating a Roguelike game in C

text:
# Question
Title: Creating a Roguelike game in C
I'm trying to create a simple rogue-like game in ncurses in a C program.

The idea here is that, I'd parse a file like this:

```
10X10 ds2 de2 dw5
12X12 ds3 de2 dw1
14X14 ds5 de1 dw5
10X10 ds5 de3 dw5
12X12 ds5 de2 dw5
14X14 dw2 de1 ds2

```

Where the first number is a door size(rows,columns), the second string being a door, where s = south, w = west, etc, so ds2 = door south 2 down (in the y direction).

Effectively, this looks like this when parsed, I have this:

Where (hopefully viewable), the plus signs at the end of each room, are the doors that lead to another room, so in the first room, the east door would lead to the room to the right, etc.

However, this is where I'm not sure how to go about implementing my logic. I need to make it when I step on a plus sign "effectively" a door, I'd teleport the player (the @ sign cursor) to the correct door.

Okay, great I know the locations of each doors, but how would I actually mvoe the cursor to the next room.

I can't simply hard code the distance between two rooms, as that's just ineffective and would take too long.

Just to clarify, what I mean about teleporting: See this picture:

Where the user "@" symbol would move to the door (in the first room), then get teleported to the second room (12x12 room). (AS seen in the next picture) (Again where the @ symbol is the user, moving the cursor around (w,a,s,d).

So to clarify: I need a way to move a cursor, between two rooms, without hardcoding the distance between rooms, unless there is an effective way to hard code the distances.

Any ideas?

# Answer
What you could do is save the location a door teleports to in your mapfile. For example, after the door size you could have two integers for the X and Y position of where it teleports to.
> -1 votes

---
Tags: algorithm, movement, c, logic, roguelikes
---


# Question
Title: How can I instantiate in the current rotation in Unity 2d?
## Backstory

I'm currently working on a 2D sidescroller/platform game as a hobby, and I just started recently. Followed a few tutorials and such I managed to wrote my own code for basic command like walk, jump, health and so on. However my basic code wasnt perforning as I would expect, I needed a more "Tight" feeling with the movements so I followed a suggestion to use a physics based controller (Prime31's PC2D, Acrocatic or even Corgi Engine...)

Well, now the movements are what I feel is good, So I kind of dived in the scripts to add/remove/customize some code.

## Question

I'm stuck now on a simple issue, I added these lines

```
public Transform weaponMuzzle;
public GameObject projectile;
float fireRate = 0.5f;
float nextFire = 0;

```

then in my `Update()`

```
if (Input.GetButtonDown("Fire2"))
{
  animator.Play.Weapon();
  fireProjectile ();
}

```

and here is the problem I have

```
void fireProjectile ()
{
  if (Time.time > nextFire)
  {
    nextFire = Time.time + fireRate;

    if (_motor.facingLeft)
    {
      Instantiate (projectile, weaponMuzzle.position, Quaternion.Euler (new Vector3 (0,0,180f)));
    }
    else if (!_motor.facingLeft)
    {
      Instantiate (projectile, weaponMuzzle.position, Quaternion.Euler (new Vector3 (0, 0, 0)));
    }
  }
}

```

The prefabs are also physics based and they are fired with no problems, however they don't want to follow the current rotation of the player, they always go in the right X axis.

First of all, the `facingLeft` on my code is what I understand is the reference to the character controller motor, I tried with `_motor.normalizedXMovement > 0` and `_motor.normalizedXMovement < 0` (`normalizedXMovement` -1 is full left and 1 is full right) this just make it that you can only fire while moving, not stopped and the problem still persists.

I also tried with `Quaternion.Identity` instead of Euler and it's the same.

For a full source code : https://github.com/prime31/CharacterController2D

I'm kinda lost and it would means a lot if you can help me out on this issue.

Ps: I already searched here and other related forums but cannot find the answer, this is not a repost.

# Answer
*Wanted to make a comment but new to Gamedev so sorry about that*

I haven't been able to find the snippet of code you provided on github. However you have several options to get the rotation working:

* Depending on how you handle the rotation towards the cursor you could simply reference the `transform` of the muzzle / player object when instantiating your projectile. I'm going to assume that's what you are trying to do now.
* Using Quaternion.SetLookRotation`(RayCastHit.position - transform.position)`
> 1 votes

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


title: OpenGL ES 2 inheriting issues

text:
# Question
Title: OpenGL ES 2 inheriting issues
I am Having an issue where one of my classes will not inherit the other ones variable value. In the class which is inherited. It shows the value of the float just fine. But when I go to the Class which is inheriting the float from that class. the float is 0. example:

```
public class PlayerMode(){
    protected float[] mModelView;

    protected PlayerMode(){
        mModelView = new float[16];
        Matrix.setIdentityM(mModelView, 0);
    }

    protected void setxPosition(float x){
        mModelView[12] = x;
        Log.d("PlayerMode", String.valueOf(mModelView[12])); //Which equals 3
    }
}

public class PlayerModel extends PlayerMode {
    public void draw(){
       //Draw Stuff...
       Matrix.multiplyMM(mvp, 0, mMvpMatrix, 0, mModelView, 0);
       Log.d("PlayerModel", String.valueOf(mModelView[12])); //Which equals 0
    }
}

```

I have tryed making a method in PlayerMode that returns mModelView\[12\] to PlayerModel but with no results. I can also see this as the object I am drawing is not moving at all.

# Answer
That's not how inheritance in Java works at all.

You do not inherit the value, that doesn't make any sense.

Simply put you inherit data members (the variables) and methods (the functions), that's all.

Don't use the PlayerMode class directly, use your PlayerModel class. You can call the setxPosition method there since it's inherited and your value will be set in the instance of PlayerModel you are using.
> 0 votes

---
Tags: java, android, opengl-es, opengl-es2
---


title: AI multithreading

text:
# Question
Title: AI multithreading
MMO game. ~5000 (fake) players should be controlled by the server. Many of them have different classes -\> different behavior. They should make some random pauses while doing some actions (~500-1500 ms) before attacking the next monster or after picking up a drop and so on. Also they should constantly checking the environment for aggressive monsters, other players. etc.

My question is, should I create a diff. thread for each player (looks not the best idea) or use another design strategy?

# Answer
> 11 votes
Implementing logic by threads is almost always a very bad idea. Multi-threaded programming is difficult! You will run into race conditions and deadlocks resulting in impossible to reproduce bugs.

There is usually only one justifiable reason to use multithreading, and that's performance: A program can sometimes be made faster by sharing work between CPU cores by running one thread per available core. But when you create more threads than you have cores, you usually achieve the opposite effect, because creation and management of threads is a quite expensive operation in itself.

Instead of running a separate thread per entity, have the main loop of your gameserver process all of them in order:

```
for (FakePlayer p: fakePlayers) {
       p.update();
}

```

If you want the object to perform an action every `n` game-ticks (you should really measure time in game-ticks, not seconds), it should have an internal counter when it performed the last action and check that counter in their update-function.

When you implement this and notice that the performance is too slow and **after profiling it** you found out that the bottleneck is the CPU, you might consider to parallelize the processing of your game objects into multiple threads. A good tool for this is to use a ThreadPool because it will automatically assign tasks to a number of threads in a smart way without you having to manage threads yourself. Call `awaitTermination` after passing all your update tasks to it to make sure the procession is finished before you continue with your main loop.

```
for (FakePlayer p: fakePlayers) {
     threadPool.submit(p -> p.update());
}
threadPool.awaitTermination();

```

And now for what's so hard about this: If you decide to do this and the `fakePlayers.update` methods read and write *any* data shared between them, you need to make sure these data structures are "thread-save". To understand all the ramifications of this, you should read and understand the official Java lesson about concurrency. Yes, all of it. Yes, from front to back. Otherwise you will get randomly occuring and impossible to reproduce bugs and your player-community will start a lynch mob.

A save way to do this without having to bash in your head too much about synchronization is to do only the *decision finding* (which should only require read-access to shared data) in parallel and then do the *decision execution* in serial order.

```
for (FakePlayer p: fakePlayers) {
     threadPool.submit(p -> p.thinkAboutNextMove());
}
threadPool.awaitTermination();

for (FakePlayer p: fakePlayers) {
     p.performNextMove();
}

```

# Answer
> 7 votes
Create a thread for each player is an overkill, 5000+ threads will trash your server performance.

My suggestion is to create a job queue where you put all your 5000 players state then you can launch a small number of thread, depending on your server architecture, that will execute a simple loop like this.

```
while(true){
    dequeueAIState();
    updateAIState();
    enqueueAIState();
}

```

This is not difficult to implement and will maximize parallelism avoiding an excessive number of thread.

Bonus point is that it's scalable, you can change the number of thread every time you want.

---
Tags: java, ai, software-engineering
---


# Question
Title: how to recieve a trigger with collider or recieve a trigger with collider in unity
i know if your object has a Collider you can sense another Collider with OnCollisionEnter function or... and you can sense another collider with trigger with OncollsionEnter function and... but i want to sense other object with trigger even with collider or even with trigger. i cant sense otherobjects that have triggers. for example i have bullet that as i dont want to collider have any physics i turned it to trigger but how can make a charcter to sense it?

Thank you for helping

# Answer
It's more than simple, but remember you must have attached rigidbody on either object.

Second is *tag*. It is one of the many ways to detect any specific object through tag. Create a specific tag by selecting any GameObject from hierarchy, in inspector click on tag drop down and add a new tag, for example **bullet**. Set the tag of your bullet to the newly created one, i.e. **bullet**

Now I'm assuming that your character have rigidbody attached then you can detect through script attached to your character by,

```
void OnTriggerEnter(Collider collider)
{
    if(collider.gameObject.tag == "bullet") // this string is your newly created tag
    {
        // TODO: anything you want
        // Even you can get Bullet object
        GameObject strikingBullet = collider.gameObject;
    }
}

```
> 1 votes

# Answer
You should read this documentation

There is this image here you can use as a reference:
> 5 votes

---
Tags: unity, collision-detection
---


# Question
Title: Cut rest of image behind object (like POV)
There are two objects - blue circle and black square. When you normally render them, you will see situation in "A". But how do I render only specific part of blue circle, which can be "seen" (is in sight) from red dot in middle of the circle ("B" situation)?

# Answer
> 1 votes
An ugly but possibly easier solution could be to

1. Check angle between red dot and all corners of the square. Store the two corners that have the largest and smallest angle to the red dot.
2. Make a blue triangle between the two stored corners and the red dot.
3. Make a blue arc covering the whole circle except the angles between the two stored corners.

If you have multiple obstacles within the vision circle, you'd have to first count how many obstacles there are, then alternate between arcs and polygons around the circle accordingly.

Edit: An even uglier paint-picture to illustrate:

# Answer
> 1 votes
Since I'm curious about an optimal solution I'll post the naive solution that will check if the center of a pixel can be raycast from the red point to the pixel without hitting a black pixel.

For every blue pixel in the blue object perform a 2D-DDA traversal from the center of the pixel to the center of the red dot. For every cell traversed check the black bitmap for a black pixel. If you hit a black pixel set the pixel to white on the blue bitmap. (Or write to another bitmap with a blue pixel if you reach the red dot).

The incomplete algorithm would look like:

```
for (var y = 0; y < blueBitmapHeight; ++y)
{
    for (var x = 0; x < blueBitmapWidth; ++x)
    {
        if (sampleBlueBitmap(x, y) == blue pixel)
        {
            // 2D-DDA traversal from (x + 0.5, y + 0.5) to redPoint
            // if hit then write a white pixel at (x, y)
        }
    }
}

```

I should point out that this is a very expensive operation and wouldn't be ideal for real-time. Even if you implemented it in a fragment/pixel shader it would require possibly hundreds, maybe thousands, of samples per pixel.

**An optimization would be to post-process the image into a quad-tree and do a 2D-DDA quadtree traversal. This would help a lot if the black bitmap contains very sparse objects.**

The 2D-DDA algorithm is described in this post.

---
Tags: java
---


title: Move Camera When Player Move C#

text:
# Question
Title: Move Camera When Player Move C#
i developing side Scrolling endless Game. i want to Change X Axis of camera as player moving to Right. and i almost Done That. but the problem is when move Camera to the Right then its look so stiff in Android Device not Move Smooth. That's the code I Write in my Script to move Camera when player move.

```
public static float offsetX;

void Update () {

    if (BirdScript.instance != null) {

        if (BirdScript.instance.isAlive) {
            MoveTheCamera ();
        }
    }

}

void MoveTheCamera() {
    Vector3 temp = transform.position;
    temp.x = BirdScript.instance.GetPositionX () + offsetX;
    transform.position = temp;

}

```

and in my Player Script(BirdScript.cs) i also set my player Position and also Get in CameraScript

```
void Awake() {

   setCameraX();

}

void setCameraX() {

    CameraScript.offsetX = (Camera.main.transform.position.x - transform.position.x) - 1f;

}

public float GetPositionX(){

    return transform.position.x;
}

```

what should i do to move my camera smoothly in device? thanks.....

# Answer
> 4 votes
use **Mathf.Lerp** for smooth transform For more details click here

```
using UnityEngine;
using System.Collections;

public class SmoothCamera2D : MonoBehaviour {

 public float dampTime = 0.15f;
 private Vector3 velocity = Vector3.zero;
 public Transform target;

 // Update is called once per frame
 void Update ()
 {
     if (target)
     {
         Vector3 point = camera.WorldToViewportPoint(target.position);
         Vector3 delta = target.position - camera.ViewportToWorldPoint(new Vector3(0.5f, 0.5f, point.z)); //(new Vector3(point.x, 0.5, 0.5));
         Vector3 destination = transform.position + delta;
         transform.position = Vector3.SmoothDamp(transform.position, destination, ref velocity, dampTime);
     }
 }
}

```

Edit 2;

for a 2D Endless Runner no need to move the camera. set the camera as constant and scroll the background. it ll give player moving effect

Eg 1.

Eg 2.

Click the link and Read the Complete documentation and see video tutorial. They gave complete tutorial about 2d endless runner game

# Answer
> 0 votes
There's a script called "SmoothFollow" provided by unity itself in the Standard Assets package. You should be able to modify that to make a sidescroller.

# Answer
> 0 votes
## For 3D

If you are developing 3D game then you can get your relevant stuff from here

## For 2D

If you are developing 2D game then I have a script, that will help you most probably.

using UnityEngine; using System.Collections;

```
public class CameraFollow2D : MonoBehaviour
{
    [Header("Camera Follow")]
    public float _dampTime = 0.15f;
    public Transform _target;

    // These public booleans allow you to move in any specific direction
    public bool _followX = true;
    public bool _followY = true;

    private Vector3 _velocity = Vector3.zero;

    // Use this for initialization
    void Start ()
    {

    }

    // Update is called once per frame
    void Update ()
    {
        if (_target) {
            Vector3 point = Camera.main.WorldToViewportPoint (_target.position);
            Vector3 delta = _target.position - Camera.main.ViewportToWorldPoint (new Vector3 (0.5f, 0.5f, point.z)); //(new Vector3(0.5, 0.5, point.z));
            Vector3 destination = transform.position + delta;
            transform.position = Vector3.SmoothDamp (transform.position, new Vector3 (_followX ? destination.x : transform.position.x,
                                                                                _followY ? destination.y : transform.position.y,
                                                                                transform.position.z), ref _velocity, _dampTime);
        }

    }
}

```

In both cases, drop the script to your `Camera`. Assign target to it from inspector and configure it according to your need.

---
Tags: unity, c#, android, camera, movement
---


title: Ball can double jump in Jumper Game

text:
# Question
Title: Ball can double jump in Jumper Game
I wrote a game that has a ball which can only jump (like in most jumper games) to avoid incoming obstacles (only, I haven't integrated the obstacles part yet). Right now, it's just a ball that can jump. The problem is, is that when the ball is on its way back down, it can jump, resulting in a double jump. I only want my ball to have one jump at a time. How can I fix this?

Main

```
import javax.swing.JFrame;

public class Main {
    public static void main(String[] args) {
        JFrame frame = new JFrame();
        View view = new View();
        Jumper jumper = new Jumper();
        Model model = new Model(view, jumper);
        view.setJumper(jumper);

        frame.setSize(500, 460);
        frame.getContentPane().add(view);
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}

```

View

```
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.awt.event.KeyEvent;

import javax.swing.AbstractAction;
import javax.swing.ActionMap;
import javax.swing.InputMap;
import javax.swing.JPanel;
import javax.swing.KeyStroke;

public class View extends JPanel {
    private Jumper jumper;
    private Rectangle bounds;
    private Model model;

    public View() {
        setBackground(Color.BLACK);
        bounds = new Rectangle(0, 0, 400, 400);

        addKeyBinding("space.pressed", KeyEvent.VK_SPACE, new MoveAction(true, Key.SPACE), false);
        addKeyBinding("space.released", KeyEvent.VK_SPACE, new MoveAction(false, Key.SPACE), true);
    }

    public void addKeyBinding(String name, int keyEvent, AbstractAction action, boolean pressed) {
        InputMap inputMap = getInputMap(WHEN_IN_FOCUSED_WINDOW);
        ActionMap actionMap = getActionMap();

        inputMap.put(KeyStroke.getKeyStroke(keyEvent, 0, pressed), name);
        actionMap.put(name, action);
    }

    public void setJumper(Jumper jumper) {
        this.jumper = jumper;
    }

    public Rectangle getViewBounds() {
        return bounds;
    }

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        jumper.paint(g);
    }

    public void setModel(Model model) {
        this.model = model;
    }
}

```

Jumper

```
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Point;

public class Jumper {
    private Point location;
    private Dimension dimension;
    private Graphics graphics;

    public Jumper() {
        location = new Point(250, 250);
        dimension = new Dimension(20, 20);
    }

    public Dimension getSize() {
        return dimension;
    }

    public void setLocation(Point location) {
        this.location = location;
    }

    public void callPaint() {
        paint(graphics);
    }

    public void paint(Graphics g) {
        graphics = g;
        g.setColor(Color.GREEN);
        g.fillOval(location.x, location.y, dimension.width, dimension.height);
    }

    public Point getLocation() {
        return location;
    }
}

```

Model

```
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.HashSet;
import java.util.Set;

import javax.swing.Timer;

public class Model {

    private boolean canBePressed, jumping;
    private int ballX, ballY;
    private int jumpCounter;
    private Thread thread;
    private Jumper jumper;
    private View view;
    private Timer timer1;
    private Point point;
    static Set<Key> key;

    public Model(View view, Jumper jumper) {
        this.view = view;
        view.setModel(this);
        canBePressed = false;
        jumping = false;
        key = new HashSet<Key>(3);
        this.jumper = jumper;
        ballX = 250;
        ballY = 0;
        thread = new Thread();

        timer1 = new Timer(5, new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                update();
                view.repaint();
            }

        });
        timer1.start();
    }

    public void update() {

        if (jumping) {
            // Only enter when space is pressed
            if (jumpCounter <= 100) {
                ballY--;
                jumpCounter++;
            } else {
                jumping = false;
            }
        } else {

            if (canBePressed && !key.isEmpty()) {
                // Start jumping (set variable to true)
                jumpCounter = 0;
                jumping = true;
                canBePressed = false;
            }

            if (jumper.getLocation().y + jumper.getSize().height > view.getViewBounds().height) {
                // Make the ball unable to jump
                canBePressed = true;
            } else {
                ballY++;
            }

        }

        //Set location of ball
        point = new Point(ballX, ballY);
        jumper.setLocation(point);
        point = null;
    }

}

```

Key

```
public enum Key {
    SPACE
}

```

MoveAction

```
import java.awt.event.ActionEvent;

import javax.swing.AbstractAction;

public class MoveAction extends AbstractAction {

    private boolean pressed;
    private Key direction;

    public MoveAction(boolean pressed, Key direction) {
        this.pressed = pressed;
        this.direction = direction;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if (pressed) {
            if (Model.key.size() < 1)
                Model.key.add(direction);
        } else {
            Model.key.remove(direction);
        }

    }

}

```

# Answer
> 1 votes
To prevent your character from from jumping more than once at a time, you make sure that the character touched the ground before allowing it to jump again. You set a flag noting that the jump is being performed, and reset the flag when the ground is touched.

```
// pseudo code
Update
  if ( canJump and jumpButtonDown )
    performJump
    canJump = False
  else if (canJump == False and isTouchGround)
    canJump = True
  end

```

---
Tags: java, gui
---


# Question
Title: Problem merging vertices of two polygonial bodies
**SUMMARY**

I need help to create a weld joint that fixes the two bodies together in a way as illustrated in the first image.

**ISSUE**

I am having an issue where I cannot find out how to weld vertices of two polygonial bodies together while also snapping the edges between each object's vertices together resulting in something like this:

Now, I have no real idea how to even get the vertice positions of an active body, so I've tried doing this using one weld joint and creating an anchor at the position of one of the bodies (The one that is being controlled, which is the triangle). I have also not been able to snap the edges together using this method:

The code to achieve the above:

```
/* Check for new collisions */
        Array<Contact> contactList = engine.getPhysicsWorld().getContactList();

        /* Iterate through the list of contact events in world */
        for (int i = 0; i < contactList.size; i++) {
            Contact contact = contactList.get(i);

            if (contact.isTouching()) {
                boolean sensorCollided = false;
                Fixture otherFixture = null;
                int sensorVertexNumber = 0;

                /* Iterate through the list of vertices for the current polygon object's body */
                for (int j = 1; j < polygon.getVerticeCount(); j++) {
                    sensorCollided = contact.getFixtureA().equals(polygon.body.getFixtureList().get(j));
                    if (sensorCollided) {
                        otherFixture = contact.getFixtureB();
                        sensorVertexNumber = j;
                        break;
                    }
                    sensorCollided = contact.getFixtureB().equals(polygon.body.getFixtureList().get(j));
                    if (sensorCollided) {
                        otherFixture = contact.getFixtureA();
                        sensorVertexNumber = j;
                        break;
                    }
                }

                /* If the colliding fixtures are sensors */
                if (otherFixture != null && otherFixture.isSensor() &&
                        polygon.body.getFixtureList().get(sensorVertexNumber).isSensor())
                {

                    Entity collision = engine.bodyOwnerLookupTable.get(otherFixture.getBody());
                    Polygon colPolygon = GameEngine.polygonMapper.get(collision);

                    /* Check if already collided with one sensor or not, we want to collide with two to merge */
                    if (colPolygon.sensorCollision == null ||
                            !(colPolygon.sensorCollision.equals(polygon.body.getFixtureList().get(sensorVertexNumber))))
                    {
                        /* If not collided with a sensor, set the first sensor collision to this sensor */
                        if (colPolygon.sensorCollision == null) {
                            colPolygon.sensorCollision = polygon.body.getFixtureList().get(sensorVertexNumber);
                        }

                        /* If this is the second sensor colliding, merge the two bodies together */
                        else {
                            /*int oldSensorVertexNumber = 0;
                            for (int j = 1; j < polygon.getVerticeCount(); j++) {
                                if (colPolygon.sensorCollision.equals(polygon.body.getFixtureList().get(j)))
                                    oldSensorVertexNumber = j;
                            }*/
                            colPolygon.isControlled = true;
                            colPolygon.setParent(polygon);
                            polygon.addChild(colPolygon);

                            /* Create weld joint */
                            WeldJointDef weldJointDef = new WeldJointDef();
                            weldJointDef.initialize(polygon.body, colPolygon.body, polygon.body.getPosition());
                            weldJointDef.collideConnected = false;

                            engine.getPhysicsWorld().createJoint(weldJointDef);
                        }
                    }
                }
            }
        }

```

If someone knows how to achieve this behaviour, it would be very appreciated if you would let me know how to do it. Thanks.

# Answer
> 1 votes
**SOLUTION**

I have somewhat solved my problem, even if it is not the best solution. I present to you an illustration of my solution followed by an explanation of each step:

1. At the merging event of two sensors (see step 2), I access the parental fixture of the controlled sensor by calling `getUserData()`. When I have grabbed my parental fixture, I can access each of it's world transformed vertices by calling `((PolygonShape)fixture.getShape()).getVertex(index, Vector2)` (PolygonShape).
2. At the creation of a body (or attached fixture, see step 3), I create one CircleShape fixture as sensor for each of the edges of the parental fixture. I also give each sensor it's own side ID to know which side of the parental fixture it is on. By doing this, I can now check for a collision with another sensor belonging to another body and initiate a merge event.
3. When the merge event is run, the body collided with gets removed and a fixture on the controlled body is created with the same shape as it's ancestor. The newly created fixture is then rotated so that the two vertices on each side of each fixture is colliding (Polygon makes it easy to rotate vertices). New sensors for the newly created fixture is created and all actions described in step 2 is made.
4. At creation of the fixture described in step 3, it's origin of rotation is set to one of the vertices of the edge of the controlled fixture so that rotation will be easier.

*Note that no WeldJoints were used in this solution.*

Hope my solution helps some people that has the same issue as I had when I wrote this question.

---
Tags: libgdx, box2d
---


# Question
Title: If a 3d surface is occluded by another 3d surface, does this have any effect on the performance and rendering speed?
We have a 3D character who is wearing a gauntlet on his forearm and visibility of which can be turned on and off. Would it be better to create two versions of arm, one without extra triangles that are hidden beneath the gauntlet? Or we can just one model with gauntlet as separate object which can be turned on and off ?

Does the hidden triangles have any effect on rendering or are they completely ignored by engine?

We are using Unity 3D.

# Answer
> 3 votes
My answer, much like Krom's, is that it depends.

In cases where you have large swaths of polygons being obstructed by another object, it's likely going to be a good idea to cull objects that are completely obscured. Suppose you are looking at a wall made of two triangles, and behind it are several objects composed of several thousand polygons. If you draw everything, you waste valuable GPU time. But by culling the objects behind the wall you can turn a draw call of thousands of polygons into a draw call of only two polygons. In this theoretical scenario, you likely would not see a massive difference in performance as a few thousand polygons is nothing to a GPU. However, when applied to larger scenes the performance gains can be quite significant.

On the inverse, and as is probably closer to your scenario, when dealing with a minute amount of polygons being obscured, while it may technically be slightly faster to draw a different model that has the obscured polygons removed, the gains will be minute, and almost definitely invisible. In addition, you will have to factor in the memory increase by loading in the alternate model. (Or models, assuming you have a different one for each area that can be obscured on your character)

Specifically, in your case, it's unlikely that culling the few polygons will do much for you, but it's always wise to do an A-B test to determine if that's true.

# Answer
> 3 votes
It depends.

There is performance difference depending on fill-rate limitations, order in which polygons are drawn and early Z-test. If, for example, your engine renderer is fill-rate limited and you draw from far to near several times, accumulating layers, then each pass eats from you budget. This is why it is beneficial to draw opaque geometry from near to far, so that early Z-test can happen and skip the "expensive" repeating part. How it is happening in your exact engine, it's hard to tell, they are all quite different in such details.

Now there are some other more real problems that can be mitigated by keeping the model "clean":

* Z-fighting if those layers are very close to each other
* Polygon collisions/penetrations if those are skeletally animated with skinning
* Consistent AO, if you plan to have different AOs baked into the arm models

And drawbacks:

* Additional work to make and maintain now 2 models instead of one
* Additional code paths to support the switching of them
* Additional time to load and memory to use for 2 models instead of one

Answering your original question - **best option is to test** and measure performance differences. Likely they are minimal, compared to all the rest game does, a few hundred polygons is next to nothing.

# Answer
> 2 votes
Generally, if you know your object will not be displayed, you should not send it to the graphics card.

Culling on the CPU removes some work to be done by the GPU.

For a few polygons, it's ok to send them (as Krom Stern suggests), but in my experience, if you start to do some few polygons here, and few polygons there, you can end up sending uselessly many polygons to the GPU, which will have to take the time to realize it does not need to work on it.

A good habit is thus to not send them.

# Answer
> 2 votes
For a low-polygon textured model, generally speaking, having a few more triangles around its hand should not be an issue (performance wise). Of course it all depends of the sizes of your models but I'm guessing we are talking about sensible volumes here. If you have permanently attached the gauntlet to the hand and you switch its visibility on/off, then, when invisible, every engine that respects itself should NOT send its triangles to the GPU (or do anything with it anyway). If visible, then BOTH hand and gauntlet will be sent to the GPU (unless the gauntlet is big enough to cover the entire hand AND the hand mesh is a separate mesh from the rest of the model AND the engine supports such kind of culling).

So, yes, it depends of the situation, but for most scenarios I can thing of, performance should not be an issue.

That said, you should consider some other things apart the performance. Those are simplicity of implementation and expandability of the solution.

For example, if you are going to have just one character with just one gauntlet, it should be fairly easy for your modeler to create 2 versions of the hand. The benefit here is that you will avoid potential visual artifacts (they can happen) and it MAY be a simpler solution (especially in FPS situations where you only see the hands) If your case is that you may have many different characters that may wear many different types of gauntlet, you may need to attach the thing on the hand (to avoid creating endless combinations). If you already have a way to attach things to the character's hands (weapons, potions), it may be simpler to simply attach the gauntlet the same way.

Just saying...

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


# Question
Title: Database works on unity editor,but not on android device
I am working on database connectivity in unity.When I run my project I am able to access my database(**retrieving and inserting data into database**).But the problem is that when I take the android out the project I am having not able to accessing my database on my mobile android device. It seems that it doesn't read my database or I don't know my database is not included upon build.

Below code is working fine. I am using MySQL

```
string loginCode="http://localhost/unity_db/login.php";
string registerCode="http://localhost/unity_db/register.php";

public string username="";
public string password="";
public string output="";

void Start () {
    Debug.Log("print");
}
// Update is called once per frame
void Update () {
}

void OnGUI()
{
    GUI.Window (0, new Rect (Screen.width/4,Screen.height/4,Screen.width/2,Screen.height/2-5), LoginWindow, "Login");

}
void LoginWindow(int windowID)
{
    GUI.Label (new Rect (140, 40, 130, 100), "Enter the Username");
    username = GUI.TextField (new Rect (25, 60, 375, 30), username);
    GUI.Label (new Rect (140, 92, 130, 100), "Enter the Password");
    password = GUI.TextField(new Rect (25, 115, 375, 30), password);
    if (GUI.Button (new Rect (29, 160, 175, 50), "Login"))
    StartCoroutine(handleLogin(username,password));
    GUI.Label (new Rect (55, 222, 250, 100),output);
    if(GUI.Button (new Rect (225, 160, 175, 50), "Register"))
    StartCoroutine(handleRegister(username,password));
}

IEnumerator  handleLogin(string user,string pass)
{
    /*if (username == "Achu" && password == "achu123") {
                    Debug.Log (username + password);
            } else {
        Debug.Log ("error");
            }*/

    string login_url = loginCode + "?username=" + user + "&password=" + pass;
    WWW logindata = new WWW (login_url);
    yield return logindata;
    if (logindata.text == "right") {
        output="login successful";

    } else {
        output="invalid user pass";
    }

}
IEnumerator  handleRegister(string user,string pass)
{

    string register_url = registerCode + "?username=" + user + "&password=" + pass;
    WWW registerdata = new WWW (register_url);
    yield return registerdata;
        if(registerdata.text=="registered")
        {
        output="registration successful";
        }
        else{
            output="registration failed pass";
        }

    }

}

```

# Answer
Your localhost is on your local development machine, you can't acces that from your android device. Try using a database which is actually hosted somewhere in the internet, it should work then.

There are lots of webhosters where you can get 2GB webspace with MySQL support for free. For example bplaced.
> 1 votes

# Answer
For a lan test, you can change "localhost" by the ip address of the machine that is running the database and then connect your android device at the same network.

Make sure your MySQL is not blocking lan access.
> 0 votes

# Answer
Just like guys said. You have to use your IP to connect. Use your local IP, also don't forget to create a User in the DB's that have free access, otherwise you aren't going to be able to connect in the server(because MOST DB's can't be accessed by outsider IP's of your connection
> 0 votes

---
Tags: unity, android, databases, mysql
---


title: Online AI competition

text:
# Question
Title: Online AI competition
I would like to create a framework that would allow user to compete with his AI code against other player AI online.

The problem is that I don't know how should server simulate the fight online. If users send their AI codes to server I don't know how would I eliminate security risks without completely interpreting the AI code. Also I thought about the option that AI code would be running on client.

What's the best way? Is it by using some specific script language for AI and interpreting it by server or something else?

# Answer
> 1 votes
Running on the client is asking for cheating. Especially considering that with such games you are targeting a demographic of enthusiastic and competitive programmers. So there is no way around running it on the server.

When you decide to make up your own scripting language, that language would be highly specialized. So unless you build some serious bugs (and that risk exists in any server application) this should be save.

When you decide to use an existing scripting language (choices are endless) make sure that this language can be properly sandboxed to control what it can and can't do.

---
Tags: ai, server, client-server, competition
---


# Question
Title: Is it possible to map mouse coordinates to isometric tiles with this coordinate system?
I'm trying to implement mouse interaction in a 2D isometric game, but I'm not sure if it's possible given the coordinate system used for tile maps in the game.

I've read some helpful things like this. However, this game's coordinate system is "jagged" (for lack of a better word), and looks like this:

Is it even possible to map mouse coordinates to this successfully, since the y-axis can't be drawn on this tile-map as a straight line?

I've thought about doing odd-y-value translations and even-y-value translations with two different matrices, but that only makes sense going from tile to screen.

# Answer
Yes, it is possible, the easiest way would be to draw a 2d-array numerical representation of the tiles, where each tile 'pixel' in the array is coded with a serial tile number.

Otherwise

Here is the complete answer:

Assuming each tile is defined by this height and width properties:

```
TILE_WIDTH = xyz;
TILE_HEIGHT = abc;

```

And the game map looks like this: We first make sure that anything on the green and red triangles is the '0' tile. Meaning a tile that does not exist.

We have as input the mouse (x, y)

```
offsetY = (mouseY - 0.5 * TILE_HEIGHT) % TILE_HEIGHT;
greenPixels = TILE_WIDTH * Math.abs(TILE_HEIGHT/2 - offsetY) / TILE_HIGHT;

offsetX = mouseX % TILE_WIDTH;
redPixels = TILE_HEIGHT * (TILE_WIDTH/2 - Math.abs(TILE_WIDTH/2 - offsetX)) / TILE_WIDTH;
if(mouseX < greenPixels || mouseY < redPixels) return (0,0);
else
{
    rowY = (int) Math.floor((mouseY -0.5 * TILE_HEIGHT) / TILE_HEIGHT);
    columnX = (int) Math.floor((mouseX * TILE_WIDTH) / TILE_WIDHT);
    if( (offsetX / TILE_WIDTH) + (offsetY / TILE_HEIGHT) < 1.0) return (columnX, 2 * rowY - 1);
    else
    {
        if(offsetX < TILE_WIDTH / 2) columnX --; // columnX = columnX - 1
        if(offsetY < TILE_HEIGHT / 2) return (columnX, 2 * rowY - 2);
        else return (columnX, 2 * rowY);
    }

}

```

This is the general pseudo code you need, there might be typos and you are welcome to ask questions and I will elaborate.

Generally what I did is build an imaginary square grid over the even rows of the tiles - ie the second row, the fourth row and such.

Then I check in which of this grid's squares the mouse is pointing (which is relatively simple since it is not jagged like the tiles.

Now I check the distance on x and y from the center of the square grid. If the pointer is not far enough from the center of the tile(which is also the center of the square in the grid) it is inside the tile.

Done like in this question:

Checking if an object is inside bounds of an isometric chunk

If not, if it is too high, it is one row above, if it's too low, it is one row below, if it is too much to the left, it is one column behind (cause the tiles on the un-even rows start a little later than the ones on the even rows) and if it is too much to the right than it is in the same jagged column as the even tile in the center.
> 3 votes

# Answer
## Screen-space mouse coordinates to tile coordinates

The general dimetric projection matrices in my answer to the question linked above will get you the transformation from screen coordinates to tile coordinates. In particular, this matrix can be used for transformation of the screen coordinates to tile coordinates:

The values to input are:

* *w*: **half** of the width of a single tile on screen
* *h*: **half** of the height of a single tile on screen
* *f*x: X-Position of the upper corner of the (0,0) tile in screen coordinates
* *f*y: Y-Position of the upper corner of the (0,0) tile in screen coordinates

The mouse coordinates have to be extended by a constant value of 1 to be a 3-dimensional vector (*x*mouse, *y*mouse, 1) and multiplied by this matrix to arrive at the tile coordinates.

## Tile coordinates to tile indices

Unfortunately if you apply them straight away to your image, you'll find that the actual tile indices aren't quite in line with their coordinates.

The somewhat thicker green lines in the picture are at coordinates *x*=0 and *y*=0; the others are spaced one unit of length apart. Remember that the *y* coordinate goes *down* as usual with computer graphics, so the tile indexed by (1,0) is in the tile with coordinates *x*=\[1, 2) and *y*=\[-1, 0).

Given the "normal" integer tile coordinates *x* and *y* (in blue on the picture above), you can calculate your tile indices *x*ind and *y*ind with the following formulas(1):

*x*ind = floor(*x* \- *y* \+ 1)/2)

*y*ind = *x* \+ *y*

---

(1) In this context, the floor() function rounds *down* towards -∞.
> 1 votes

# Answer
If it's still not working, these tutorials may be of help:

http://www.gamedev.net/page/resources/\_/technical/game-programming/isometric-n-hexagonal-maps-part-i-r747 , http://www.wildbunny.co.uk/blog/2011/03/27/isometric-coordinate-systems-the-modern-way/
> 0 votes

# Answer
As I saw on a game I did, it's easier to "move" your x/y axes, and handle row and cols as linear function : you can easy calculate `a` and `b` from `y(x) = ax+b` with tile position.
> 0 votes

# Answer
I'll preface my answer with this: I know this is an old question, but it's the first that came up when I was searching.
I had the same issue, and I looked at the solution presented here, but they deal with either a known offset or can be inaccurate with mouse coordinates. My solution is small and in a single function.

This is in Lua:

```
function global.XYtoIsoTile(x,y)
  local isoW,isoH = cGenericTile.getSize()
  local gridX,gridY = math.floor(x/isoW)+1,math.floor(y/isoH)+1
  --Get the coordinates in relation to center of grid area
  local pointX,pointY = (x%isoW)-(isoW/2),(y%isoH)-(isoH/2)

  if math.abs(pointY) > ((isoH/2) - (((isoH/2)*math.abs(pointX))/(isoW/2))) then
    if pointX >= 0 and pointY >= 0 then
      gridX,gridY = gridX,gridY+1/2
    elseif pointX >= 0 and pointY < 0 then
      gridX,gridY = gridX,gridY-1/2
    elseif pointX < 0 and pointY >= 0 then
      gridX,gridY = gridX-1,gridY+1/2
    else --if pointX < 0 and pointY < 0 then
      gridX,gridY = gridX-1,gridY-1/2
    end
  end
  return gridX,gridY
end

```

cGenericTile.getSize() just returns the height and width of my isometric tiles.
my gridX and gridY have the +1 to them because Lua tables start at 1, not 0, and my tiles are stored in a 2D table/array. In Lua, `--` denotes a comment, rather than `//` or `#`

math.abs(pointY) \> ((isoH/2) - (((isoH/2)\*math.abs(pointX))/(isoW/2))) is a math function that, if graphed, forms an isometric tile. It checks if the |y| is above the line, and if so, it enters the `if` statement code, else skips over it all.
> 0 votes

---
Tags: 2d, mathematics, isometric, tilemap
---