# Question
Title: Unable to Set Text of another Text Object
**The Idea:** Pressing a button in the canvas will allow the player to select a race. A script is attached to an object which is accessed though the OnClick() function of the button.

The script is supposed to get which race is selected based on which button is pressed and fetch a race description in a Text Object named "DescriptionText".

However a description is not displayed, and I get this error: "NullReferenceException: Object reference not set to an instance of an object GOnClick.GetRaceDesc () (at Assets/Scripts/GUI\_Scripts/GOnClick.cs:24)".

I can't see what I am doing wrong, so here is my code:

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

public class GOnClick : MonoBehaviour {

public string race, description;
void Start()
{
    race = "";
    description = "";
}

void Update()
{
    GetRaceDesc();
}

public void GetRaceDesc()
{
    //Button butnText = GameObject.FindObjectOfType<Button>();
    //race = butnText.GetComponentInChildren<Text>().text;
    *(line 24)* race = gameObject.GetComponentInChildren<Text>().text;
    GameObject descRect = GameObject.Find("DescriptionText");

    if(race == "Dark Elf")
    {
        BaseRace raceSelection = new DarkElfRace();
        descRect.GetComponent<Text>().text = raceSelection.CharacterRaceDesc;
    }
    else if (race == "High Elf")
    {
        BaseRace raceSelection = new HighElfRace();
        descRect.GetComponent<Text>().text = raceSelection.CharacterRaceDesc;
    }
    else if (race == "Wood Elf")
    {
        BaseRace raceSelection = new WoodElfRace();
        descRect.GetComponent<Text>().text = raceSelection.CharacterRaceDesc;
    }
    else if (race == "Human")
    {
        BaseRace raceSelection = new HumanRace();
        descRect.GetComponent<Text>().text = raceSelection.CharacterRaceDesc;
    }
    else if (race == "Dwarf")
    {
        BaseRace raceSelection = new DwarfRace();
        descRect.GetComponent<Text>().text = raceSelection.CharacterRaceDesc;
    }
    else if (race == "Orc")
    {
        BaseRace raceSelection = new OrcRace();
        descRect.GetComponent<Text>().text = raceSelection.CharacterRaceDesc;
    }
    else if (race == "Goblin")
    {
        BaseRace raceSelection = new GoblinRace();
        descRect.GetComponent<Text>().text = raceSelection.CharacterRaceDesc;
    }
    else if (race == "Tiefling")
    {
        BaseRace raceSelection = new TieflingRace();
        descRect.GetComponent<Text>().text = raceSelection.CharacterRaceDesc;
    }
    else if (race == "Half Dragon")
    {
        BaseRace raceSelection = new HalfDragonRace();
        descRect.GetComponent<Text>().text = raceSelection.CharacterRaceDesc;
    }
    else if (race == "Werewolf")
    {
        BaseRace raceSelection = new WerewolfRace();
        descRect.GetComponent<Text>().text = raceSelection.CharacterRaceDesc;
    }

    }

}

```

Thanks in advance for any help.

# Answer
I made something to show you how I would do it, you can play around with it. I will explain how to use it.

Put the following script on any GameObject you like.

In the inspector, drag the text field where your race description should appear in the textField slot of this script.

As you can see I made up some classes for your races, I gave it an id and the description. The id is important, because now you will go to the button which should show the description.

Add a click listener to the button by pressing the "+" sign in the lower right of the button script.

Drag the GameObject which has the RaceSelection script to the open slot in the inspector.

You can now select a function to execute. Choose RaceSelection, then choose SetRaceDescription.

Another slot will appear where you can enter an integer. This integer corresponds to your race id. So by entering a 0 this button will show the High-Elf.

You have to do that will all your buttons, in each enter a different integer that corresponds to a race.

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

public class RaceSelection : MonoBehaviour {

    public interface Race
    {
        int RaceID {
            get;
        }
        string RaceDescription {
            get;
        }
    }

    public class HighElfRace : Race
    {
        public int RaceID {
            get {
                return 0;
            }
        }

        public string RaceDescription {
            get {
                return "High-Elf";
            }
        }
    }

    public class DarkElfRace : Race
    {
        public int RaceID {
            get {
                return 1;
            }
        }

        public string RaceDescription {
            get {
                return "Dark-Elf";
            }
        }
    }

    public Text textField;
    private IDictionary<int, Race> raceDict = new Dictionary<int, Race>();

    void Start() {
        addRaceToDictionary (new HighElfRace ());
        addRaceToDictionary (new DarkElfRace ());
    }

    private void addRaceToDictionary(Race race) {
        raceDict.Add (race.RaceID, race);
    }

    public void SetRaceDescription(int raceId) {
        textField.text = string.Format("Race : {0}", raceDict[raceId].RaceDescription);
    }

}

```

Some more guidance : You are calling GetRaceDesc in your Update method. This in itself isn't bad, but you are creating unnecessary objects in it and you are constantly looking up components. This will slow down everything. Either cache components in Start() or do it like I did in my script and drag and drop them in via inspector.
> 0 votes

# Answer
So your new question is How you would access the button through the script? I'd create the gameobject string and have it public so you can relate to a specific object in your scene. Then do an "OnGUI" you would name the var that you set up when you create the gameobject string. Hope that helped! :D
> 0 votes

# Answer
You can make public members in `GOnClick` to easily access other `GameObject`s and if you need the `Text` component, call `GetComponent` in your `Start` and save it so you only have to do it once.

```
public class GOnClick : MonoBehaviour {

    public GameObject RaceTextContainer;
    private Text RaceText;

    public string race, description;
    void Start()
    {
        RaceText = RaceTextContainer.GetComponent<Text>();
    }

    ...
}

```

Now, if you click on the object in your *Hierarchy* that has `GOnClick` attached and look at your *Inspector* you'll see an empty slot for "RaceTextContainer". You can now drag whatever object you want to extract the `Text` component from and drag it from the *Hierarchy* into that slot under the script in the *Inspector*.
> 0 votes

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


# Question
Title: How to execute game logic every 100ms but render as fast as possible?
I have created a simple snake clone and would like to execute game logic every 100ms while rendering as fast as possible. How can I achieve this when the program might run with very different frame rates?

For example when compiling the code to a native executable I have over 1000 where I can just wait until 100ms are passed before executing the next logic step. But when compiling to asm.js I get frame rates of about 20 which means the period between two logic steps could be everything from 100ms to 149ms which would result in visible stutter (one movement is faster than another).

# Answer
> 2 votes
This is some basic example of calculation of the framerate.
I'm assuming that there's a function called `current_milliseconds()` that returns the number of milliseconds from the beginning of the program.

```
/* Before the loop */
int time = current_milliseconds(); // Setting up the Timer
int FPS = 60;

/* Inside the loop (at the bottom) */
int frame_ms = current_milliseconds() - time; // Milliseconds the frame took to render
// Calculating the number of frames the machine could render in 1 second at that speed
FPS = 1000.0 / (frame_ms <= 0 ? 1 : frame_ms);
time = current_milliseconds();

```

My advice from personal experience: do NOT limit framerate manually. It's better for you to check the time of rendering of each frame and adjust your game logic accordingly.
Another solution is to use vSync to get a constant framerate.

---
Tags: game-loop, c, logic
---


title: Rotation of a cube

text:
# Question
Title: Rotation of a cube
I came across the statement "rotation about a pivot and an axis" in javafx. The axis is defined by`Point3D` and the pivotX, pivotY and pivotZ are of `double` type. I could not form a relation about what these actually deal with the rotation. Can anyone explain the geometry behind this with an example?

# Answer
> 1 votes
Well, the pivotX/Y/Z are the effective origin point of the rotation. Pretend these are (0,0,0) at first and that the center of the cube is at the origin.

The `Point3D` object is a unit vector describing the arbitrary line around which the cube will be rotated. E.g. (1,0,0) would cause it to rotate around the x-axis. If the vector was (1,1,1) it would be a (non-normalized) axis that runs from one corner of the cube to the opposite corner (imagine holding a die between your fingers, on opposite corners, and spinning it).

To take the pivot point into account, just translate the object by that amount time -1, then rotate it, then translate back by that amount.

---
Tags: 3d, rotation, javafx
---


title: Map coordinates to camera coordinates

text:
# Question
Title: Map coordinates to camera coordinates
I have a tiled map which is 3 times higher than camera. When I press on a tile, I want an actor on that tile to show up. This works if camera is not moved. If I move camera a little bit up, so the tile coordinates are greater then camera coordinates, actor is placed offscreen. Is there a way to get tile coordinates so they wil fit the camera coordinates

Im using libgdx if it helps.

# Answer
> 1 votes
Please look at the Camera `unproject(Vector3 screenCoords)` method. This will translate the point clicked on the screen to the 'world' point.

This should allow you to the tile X,Y and then translate to the correct tile.

---
Tags: java, libgdx
---


# Question
Title: Unity Editor equivalent of Playmode Start()
I am attempting to draw gizmos for easy debug in the editor. The gizmos code uses an array that gets populated during the start function. The array only needs to be populated once and may cause issues if its modified during runtime. As such, I cant call the method to populate the array in the `OnDrawGizmos()` method.

I could possibly use a singleton populate the array but that would require many other things to be changed as well. I am looking for an equivalent to `Start()` for when it is in Editor Mode. Is there a method in editor mode that execute once or an attribute for the `Start()` method to execute in editor mode?

# Answer
> 2 votes
What you are looking for is `OnEnable` in the `Editor` class.

http://docs.unity3d.com/ScriptReference/Editor.html

Here's some sample code from the docs:

```
using UnityEditor;
using UnityEngine;
using System.Collections;

// Custom Editor using SerializedProperties.
// Automatic handling of multi-object editing, undo, and prefab overrides.
[CustomEditor(typeof(MyPlayer))]
[CanEditMultipleObjects]
public class MyPlayerEditor : Editor {
    SerializedProperty damageProp;
    SerializedProperty armorProp;
    SerializedProperty gunProp;

    void OnEnable () {
        // Setup the SerializedProperties.
        damageProp = serializedObject.FindProperty ("damage");
        armorProp = serializedObject.FindProperty ("armor");
        gunProp = serializedObject.FindProperty ("gun");
    }
...

```

---
Tags: unity
---


title: Rotations of a Rubik's cube

text:
# Question
Title: Rotations of a Rubik's cube
I made a Rubik's cube by arranging smaller cubes. Now I want to apply animations to it. For that I am choosing to use the `Rotate` class and set the angle of rotation and the axis of rotation,like this

```
ar[12].setRotationAxis(Rotate.X_AXIS);//The array elements refer to the small cubes which make up the Rubik's cube.These elements represent the left face.
        ar[13].setRotationAxis(Rotate.X_AXIS);
        ar[14].setRotationAxis(Rotate.X_AXIS);
        ar[15].setRotationAxis(Rotate.X_AXIS);
        Rotate rotation1 = new Rotate(90);
        rotation1.setAxis(Rotate.X_AXIS);

```

Then I am applying the rotations as an animation,like this

```
Timeline timeline = new Timeline(
                new KeyFrame(Duration.seconds(2), new KeyValue(ar[12].rotateProperty(), 90)),
                new KeyFrame(Duration.seconds(2), new KeyValue(ar[13].rotateProperty(), 90)),
                    new KeyFrame(Duration.seconds(2), new KeyValue(ar[14].rotateProperty(), 90)),
                    new KeyFrame(Duration.seconds(2), new KeyValue(ar[15].rotateProperty(),  90)));
            timeline.stop();

            timeline.setCycleCount(Timeline.INDEFINITE);
            timeline.setAutoReverse(true);
            timeline.play();

```

The inner black sides are coming out. What mistake am I making and how to fix this ? Basically, I am getting this for each single cube  But I need this for each cube

# Answer
> 3 votes
Okay so imagine the image below is the front view of one of your faces on your cube:

Ugly, I know. Currently when you do `FACE.setRotationAxis(Rotate.X_AXIS)` you are setting the rotation axis of that individual square to be the center of the square. The black dots in the image below are your rotation axes:

So when you say to rotate, each cube rotates around that central point as such:

Instead you need to have the central axis be that point in between all four cubes:

So, we need to set the axis of rotation for each individual cube to be that center point. I don't know what graphics library you're using but it should be relatively simple to do. Here is a visual representation of the cube's dimensions using `XAxis` as the central point because that is what your code apparently does currently:

So, for the red square, the x component of the point of rotation would be `face.XAxis.x + 0.5 * face.width` and the y component would be `face.XAxis.y + 0.5 * face.height`. For the blue square, this would be slightly different: `face.XAxis.x + 0.5 * face.width` and `face.XAxis.y - 0.5 * face.height` since its point of rotation is above the center point of the square.

---
Tags: 3d, animation, rotation, javafx
---


# Question
Title: How to link the game class to the main menu class in XNA?
So I got my game in another class and my main menu in another class.

This is the update method in my Main menu class

```
MouseState mouse = Mouse.GetState();
            switch (CurrentGameState)
            {
                case GameState.MainMenu:
                    if (btnPlay.isClicked == true) CurrentGameState = GameState.Playing;
                    btnPlay.Update(mouse);
                    break;

                case GameState.Playing:

                    break;

            }
            base.Update(gameTime);

```

This is the draw method in my Main menu class

```
spriteBatch.Begin();
            switch (CurrentGameState)
            {
                case GameState.MainMenu:
                    spriteBatch.Draw(Content.Load<Texture2D> ("MainMenu"), new Rectangle (0,0, screenWidth, screenHeight),Color.White);
                    btnPlay.Draw(spriteBatch);

                    break;

                case GameState.Playing:
                    break;
                                    }

            spriteBatch.End();

```

But now I don't know how to link/call the actual game file.. Would someone be able to help me with this please?

# Answer
As first, don't do it:

```
spriteBatch.draw(Content.Load<Texture2D>("blabla"), ...);

```

Because you are calling the "Load" method in every frame. That would cause a memory leak.
And if I understand your problem correctly, your

## **First option: Using Static Values**

These static values should be in your Game class.

```
public class Game1 : Microsoft.Xna.Framework.Game
{
    GraphicsDeviceManager graphics;
    SpriteBatch spriteBatch;
    public static Texture2D globalTexture; //This is reachable from other classes

    public Game1()
    {
        graphics = new GraphicsDeviceManager(this);
        Content.RootDirectory = "Content";
    }
    //...

```

---

```
public class MainMenu
{
    //...
    public void drawItem(SpriteBatch sb)
    {
        sb.draw(Game1.globalTexture, ...);
    }
}

```

## **Second option: Using an instance of the Game class**

```
public class MainMenu
{
    Game1 gameInstance;

    public MainMenu(Game1 theGame)
    {
        gameInstance = theGame;
    }

    //...
    public void drawItem(SpriteBatch sb)
    {
        Texture2D texture = gameInstance.texture;

        sb.draw(texture, ...);
    }
}

```

---

Or you do using a parameter:

```
public class MainMenu
{
    //...
    public void drawItem(Game1 game)
    {
        SpriteBatch sb = game.spriteBatch;
        Texture2D texture = game.texture;

        sb.draw(texture, ...);
    }
}

```

---

---

**You can also have the necessary things as parameter in the public methods, which get called by the game class, like that:**

```
public class Game1 : Microsoft.Xna.Framework.Game
{
    GraphicsDeviceManager graphics;
    SpriteBatch spriteBatch;
    MainMenu menu = new MainMenu();
    private float rotation;

    public Game1()
    {
        graphics = new GraphicsDeviceManager(this);
        Content.RootDirectory = "Content";
    }

    public void drawMenu()
    {
        menu.draw(spritebatch, rotation, ...);
    }
    //...

```

---

```
public class MainMenu
{
    //...
    public void draw(SpriteBatch sb, float rotation)
    {
        float playerRot = rotation;
        sb.draw(Game1.globalTexture, ... , playerRot);
    }
}

```
> 1 votes

---
Tags: c#, xna, xna-4.0
---


# Question
Title: Cast a circle around an object and detect other objects in range (with visual)
I have my "player" object moving around an arena type area, with miscellaneous objects scattered about. What I want to do is move the player near any of these objects, and on keypress I want to display a circular radius with the player in the center that will detect nearby objects (eventually being filtered by tag).

I realize there are many ways to accomplish this, but being relatively new to Unity I am trying to find a way that is intuitive to me. Looking at the documentation, Physics2D.CircleCastAll seems like it would fit my needs, but I am unable to test at this time (at work).

Provided CircleCastAll is what I do use, is there a way in the scene to display the circle that is being cast so that the player can visually see the radius? I know it returns a RayCastHit2D, so I can get the objects from that, but the player should have something visual to let them know if they are slightly out of range or not.

Any suggesions/tips are welcome. Thanks in advance!

# Answer
> 3 votes
I think you are misunderstanding how `CircleCastAll` works. A good analogy to describe it is that `CircleCastAll` is throwing a frisbee of a certain radius over a distance and then returning all object that this frisbee hits. What I think you are looking for is a circle that emanates from the user and that does not move over a distance. The proper way to perform this action is with `OverlapCircleAll`. For this you would simply set the `point` of the circle to be your player's position and the `radius` to the radius of your desired circle.

Now onto the hard part. `OverlapCircleAll` and all other Physics functions in only return the Colliders of **the things that were hit**. They do not interact with visuals in any way. This you will need to do on your own. The easiest way I can think of to do this is to have an animated circle appear that is the same radius as your `OverlapCircleAll` appear at the same time as your `OverlapCircleAll`.

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


title: Explain Mesh.MarkDynamic

text:
# Question
Title: Explain Mesh.MarkDynamic
As the reference page says, this function/method is used to optimize a mesh for frequent updates, but the description seems a little bit unclear.
What should I consider before using it in my code? Would there be any 'side effects' like heightened memory usage etc.?

# Answer
When setting a mesh as Dynamic, you are indicating to the API that the vertex buffer contents are going to change often. Most underlying rendering systems (DirectX, for example) will manage the memory associated with a vertex buffer differently if it knows that the buffer is static or dynamic - for example the buffer can live entirely on the GPU if it is static, whereas it needs to be pushed from main RAM to GPU RAM when it changes.

Classic examples are particle systems, the results of CPU-side skinning or some cloth simulation results.
> 2 votes

---
Tags: unity, mesh
---


# Question
Title: What are "frame A" and "frame B" in btGeneric6DofConstraint's constructor for?
I have a very simple (and maybe too primitive to post here but I’ll try anyway :P) question about Bullet constraints. What are arguments `const btTransform &frameInA, const btTransform &frameInB, bool useLinearReferenceFrameA` of Bullet’s `btGeneric6DofConstraint`? Documentation doesn’t say anything about them.

I think (but am not entirely sure) that the first two are Pivot Point Transformations relative to mass-center of two rigid bodies (in their own coordinate systems). And thus they should always point to the same point in world-space. Is that true?

Also, what is Linear Reference Frame?

# Answer
Looking on the Bullet Physics forums I found a comment from Erwin (the author):

> FrameA and FrameB are constraint frames in local spaces A and B respectively Limits give the allowable range of movement if frameB in frameA space (or vice versa if useLinearReferenceFrameA == false)

He then supplies some sample code to try:

```
{ // create a generic 6DOF constraint with spring that has rest length 10
      // and connected to dynamic body at point (-5, 0, 0)
      btScalar springRestLen(10.f);
      btScalar pivotOffset(-5.f);
      btScalar springRange(7.f); // allowed oscillation range
      btTransform tr;
      tr.setIdentity();
      tr.setOrigin(btVector3(btScalar(0.), btScalar(0.), btScalar(0.)));
      tr.getBasis().setEulerZYX(0,0,0);
      btRigidBody* pBodyA = localCreateRigidBody( 0.0, tr, shape); // static body
      pBodyA->setActivationState(DISABLE_DEACTIVATION);

      btTransform frameInA;
      frameInA = btTransform::getIdentity();
      frameInA.setOrigin(btVector3(btScalar(0.), btScalar(0.), btScalar(0.))); // in A coordinate systam

      tr.setIdentity();
      tr.setOrigin(btVector3(btScalar(springRestLen - pivotOffset), btScalar(0.), btScalar(0.))); // this is (15, 0, 0)
      tr.getBasis().setEulerZYX(0,0,0);
      btRigidBody* pBodyB = localCreateRigidBody(1.0, tr, shape); // dynamic body
      pBodyB->setActivationState(DISABLE_DEACTIVATION);

      btTransform frameInB;
      frameInB = btTransform::getIdentity();
      frameInB.setOrigin(btVector3(pivotOffset, btScalar(0.), btScalar(0.))); // in B coordinate systam

      btGeneric6DofSpringConstraint* pGen6DOFSpring = new btGeneric6DofSpringConstraint(*pBodyA, *pBodyB, frameInA, frameInB, true);
      // in WCS we should have offset between origin of frameB and frameA.
      // It should be equal to springRestLen, so we should set proper limits
      // we set useLinearReferenceFrameA to true, so limits wil be in A coordinate system
      pGen6DOFSpring->setLinearUpperLimit(btVector3(springRestLen + springRange, 0., 0.));
      pGen6DOFSpring->setLinearLowerLimit(btVector3(springRestLen - springRange, 0., 0.));
      // lock all rorations
      pGen6DOFSpring->setAngularLowerLimit(btVector3(0.f, 0.f, 0.f));
      pGen6DOFSpring->setAngularUpperLimit(btVector3(0.f, 0.f, 0.f));
      // add constraint to world
      m_dynamicsWorld->addConstraint(pGen6DOFSpring, true);
      // draw constraint frames and limits
      pGen6DOFSpring->setDbgDrawSize(btScalar(5.f));
      // enable spring
      pGen6DOFSpring->enableSpring(0, true);
      pGen6DOFSpring->setStiffness(0, 39.478f); // period 1 sec for !kG body
      pGen6DOFSpring->setDamping(0, 0.01f); // add some damping
      // constraint force mixing prevents "locking" on limits
      pGen6DOFSpring->setParam(BT_CONSTRAINT_STOP_CFM, 1.0e-5f, 5);
      pGen6DOFSpring->setEquilibriumPoint(); // set current position as equilibrium point
   }

```

The relevant forum post can be found here
> 3 votes

---
Tags: c++, bullet-physics
---


# Question
Title: GPU usage below 90% = poorly optimized game
*Ok so not exactly a "development" question but highly related.*

When I play games I often look at performance numbers, like CPU usage, GPU usage, memory usage and others. Let us talk about GPU usage on PC. Here is my observation: there are two kinds of games:

* MAX GPU usage: these games produce **either** 60 FPS **or** 90%+ GPU usage.
* POOR GPU usage: these games produce **less** than 60 FPS **and** **less** than 90% GPU usage at the same time

MAX GPU examples (trying to make sure my idea is understood ok):

* 50 FPS, 100% GPU
* 60 FPS, 90% GPU
* 60 FPS, 50% GPU (also legit)

POOR GPU examples:

* 30 FPS, 60% GPU (FPS limit is 60)
* 40 FPS, 50% GPU

It appears that MAX GPU games use GPU efficiently to provide best performance while POOR GPU games are bottlenecked for some reason. U get few FPS, low GPU load and none of CPU cores reach 100% load. I checked and re-checked my PC many times and I don't see any specific issue which could make some games perform poorly, besides other games reach 90%+ GPU usage with no problem. Also I am not the only person who observed such behaviour.

So the question is: *POOR GPU games are poorly optimized, either on purpose or because of lack of effort.* True or false?

Also, it appears that MAX GPU games are probably multithreaded? I suspect that poor-gpu games go like this: use main thread

```
loop
  update;
  draw;

```

while max-gpu games go like this: use two threads

```
loop
  start-update in another thread;
  start-draw;
  wait & synchronize

```

It is of course more complex than that but the general idea is basically that max-gpu games render stuff and update stuff at the same time; that is how higher GPU usage is achieved.

Ideas? Thoughts? Thanks

# Answer
> 0 votes
> POOR GPU games are poorly optimized, either on purpose or because of lack of effort. True or false?

It's not that simple and depends a lot on the game.

Most (if not all) games render and update at the same time, that is one of the advantages of using a GPU.

The CPU transfers memory from system RAM to graphics RAM and tells the GPU to go to town on it while it goes around and does other stuff.

It's the transfer that stops GPU usage since it can only wait for it to be finished.

The memory is transferred through a parallel bus in the GPU at a set speed. The width of the bus and the transfer clockspeed of cards creates a maximum transfer rate and this rate can be a lot slower then the CPU causing it to wait as well.

How can you solve this?

* Better graphics card
* Transfer memory less frequently
* Transfer less memory

There are more factors that play into it but the memory is the main reason usage and fps can be low.

---
Tags: optimization, pc
---


# Question
Title: Import JXInput by StrikerX3 Into Eclipse
I'll be honest, I'm stumped, I've been trying all night, googling away, made multiple attempts and failed every time. The library in question that I'm trying to add to my project is:

https://github.com/StrikerX3/JXInput

The instructions say:

> Usage:
>
> ```
> 1. Install the project into your Maven repository (since it is not available in the Central Maven repository).
>
> 2. Include the Maven dependency into your project:
>
> <dependency>
>     <groupId>com.ivan</groupId>
>     <artifactId>xinput-device</artifactId>
>     <version>0.5</version>
> </dependency>
>
> 3. There is no need to extract or copy the native libraries from the VS project. The natives are included in the jar file and are extracted and loaded at runtime automatically under the lib folder of the working directory.
>
> 4. In your Java code, import the com.ivan.xinput.XInputDevice class for XInput 1.3 functionality or com.ivan.xinput.XInputDevice14 for XInput 1.4. The latter class extends the former so you can use 1.3 methods with the 1.4 class.
>
> 5. To check if the desired version is available:
>
>
> // check if XInput 1.3 is available
> if (XInputDevice.isAvailable()) {
>     System.out.println("XInput 1.3 is available on this platform.");
> }
>
> // check if XInput 1.4 is available
> if (XInputDevice14.isAvailable()) {
>     System.out.println("XInput 1.4 is available on this platform.");
>
> ```

I'm using the current latest version of Eclipse and have the latest version of Java installed. I have a simple project I'm working on, just a JOGL based 3D application.

The first step says, "1. Install the project into your Maven repository". This is where I'm most confused.. I've never used Maven before, I don't know how to use it. After some googling, I unzipped the project into my Eclipse workspace and tried going to File \> Import \> Maven \> Existing Maven Projects and imported the project.

Next the instructions refer to Maven dependency. I tried setting the dependency on the maven project, but I'm not sure if I was even in the right place for that.

The 3rd instruction refers to natives included in a Jar file, but after much searching I can't find a Jar file inside of any of the files provided by the library.

After that I tried to follow the rest of the instructions but obviously nothing has worked. I've fiddled with many settings and tried what I can all night to make this work but I can't see what it is I'm meant to do.

Can anyone give me any hints? Has anyone done this before who can give me a quick howto on this? I just don't know what I'm meant to do, any help would be greatly appreciated.

# Answer
> 1 votes
Ultimately my problem turned out be just a silly issue of needing to reinstall the JDK! After doing that, everything was working again.

---
Tags: java, input
---


title: Writing a glow shader

text:
# Question
Title: Writing a glow shader
I'm trying to learn writing shaders. And I've pieced together something that is kinda working. I want to create a transparent glow around a sphere. The problem I have is that I can't seem to alter the transparency of the glow. I tried experimenting with `ZWrite off` but that doesn't give me the desired results.

The red part around the sphere is the glow. But I'm unable to change its alpha. I'd would also like to change the "blurriness" of the glow. How would I do that?

EDIT

so I did some more tinkering. I've changed the blending to
`Blend SrcAlpha OneMinusSrcAlpha` and enabled `ZWrite off`. This allows me to change the alpha. The problem with this is that the inside of the object is also colored by the glow. I just want the glow around the circle. not inside.

```
Shader "Custom/HoleShader" {
Properties {
    _holeColor ("Color", Color) = (1,1,1,1)
    _glowColor ("Glow Color", Color) = (1,1,1,1)
    _glowSize ("Glow Size", Range (0.0,5)) = 1.0
    _glowOpacity ("Glow Opacity", Range(0,1)) = 1
}
SubShader {
Tags { "LightMode" = "ForwardBase" }
    Pass {
        CGPROGRAM
        #pragma vertex vert
        #pragma fragment frag
        uniform float4 _holeColor;
        uniform float4 _glowColor;

        struct appData {
            float4 normal : NORMAL;
            float4 vertex : POSITION;
        };

        struct v2f {
            float4 pos : SV_POSITION;
            float4 col : COLOR;
        };

        v2f vert (appData v) {
            v2f o;
            o.pos = mul(UNITY_MATRIX_MVP,v.vertex);
            return o;
        }

        float4 frag(v2f i) : COLOR {
            return _holeColor;
        }
        ENDCG
    }
    Tags { "LightMode" = "ForwardBase" "Queue" = "Transparent" "RenderType" = "Transparent"}
    Pass {
        ZWrite Off
        //Blend One OneMinusSrcColor
        Blend SrcAlpha OneMinusSrcAlpha
        CGPROGRAM
        #pragma vertex vert
        #pragma fragment frag
        uniform float4 _holeColor;
        uniform float4 _glowColor;
        uniform float _strength;
        uniform float _glowSize;
        uniform float _glowOpacity;

        struct appData {
            float4 normal : NORMAL;
            float4 vertex : POSITION;
        };

        struct v2f {
            float4 pos : SV_POSITION;
            float4 col : COLOR;
            float3 viewDirection;
            float3 normalDirection;
        };

        v2f vert (appData v) {
            v2f o;
            float4 pos = v.vertex + (v.normal * _glowSize);
            o.pos = mul(UNITY_MATRIX_MVP,pos);
            return o;
        }

        float4 frag(v2f i) : COLOR {
            return float4(_glowColor.rgb, _glowOpacity);
        }
        ENDCG
    }
}
}

```

# Answer
In my opinion the best way to generate a glow around an arbitrary object is by using the geometry shader to detect edges and extrude new faces, there are no doubt other ways that work as well or even better and you can google around for those, but I'll cover my way doing edges.

Full disclosure: I don't know Unity or glsl so I can't give direct code but I'll try to explain in a general manner.

**Geometry Shaders**

A geometry shader is a part of the graphics pipeline similar to the pixel(fragment) & vertex-shaders. Unlike those two though the geometry shader operates once on each primitive, a primitive being triangles lines or points.

The geometry shader doesn't just use primitives as input it can also output up to a defined max of new primitives, this is the true power of a geomotry shader, it can be used to cull primitives and/or expand them.

**Edge Detection**

I said earlier that the geometry shader works on primitives such as triangles lines or points, this was not a definite list and there is one primitive that is of particular intrest to us:

The Triangle adjecant

The triangle adjecant provides not only data for the triangle but for all neighbouring triangles. If the main triangle faces the camera and an adjecant triangle does not then the triangle lies on the edge and we can proceed.

To check if a triangle is backfacing calculate it's normal and dot product it with the cameras normal. I'll leave the details of the calculation as an exercise to the reader, it's not hard.

**Face Extrusion**

Now we come to the tricky part, start by drawing a line from the camera to an arbitrary point on the edge and use the cross product of this line and the edge to get the direction of where to extrude the new face, we'll call this *e*, make sure to normalize it.

Create two new points *x* distance from the edge points in the direction of *e*, *x* here being a glow amount. From these two new points and the edge we can output a new face in the geometry shader and create a glow around the object.

**But wait!**

This will only work if the edge is completly straight or concave\*, if the edge is convex we'll have a gap.

To solve this first project the edge point normals on the vector *e* this creates two new vectors *n1* and *n2*, make sure to normalize these too.

Like before create two new points *x* distance from the edge points in the direction of *n1* and *n2* and create new faces from these points, this will create a more robust glow.

**But wait again!**

Like I alluded earlier this only works *sort of* on a concave edge there will be coverage but you're probably gonna get wierd results. To solve this check if an edge is concave and in that case skip extruding in the direction *e* and just extrude in the direction of *v1* or *v2*.

**Now we're done**

Hopefully I might have somewhat answered your question or at the very least given you a direction to head in, I'll try to update this later with better images and explanations and hopefully someone more knowledgeable in opengl or Unity can give a more detailed answer.
> 5 votes

---
Tags: unity, shaders, cg
---


# Question
Title: What are the cons of using DrawableGameComponent for every instance of a game object?
I've read in many places that DrawableGameComponents should be saved for things like "levels" or some kind of managers instead of using them, for example, for characters or tiles (Like this guy says here). But I don't understand why this is so. I read this post and it made a lot of sense to me, but these are the minority.

I usually wouldn't pay too much attention to things like these, but in this case I would like to know why the apparent majority believes this is not the way to go. Maybe I'm missing something.

# Answer
> 21 votes
"Game Components" were a very early part of the XNA 1.0 design. They were supposed to work like controls for WinForms. The idea was that you would be able to drag-and-drop them into your game using a GUI (kind of like the bit for adding non-visual controls, like timers, etc) and set properties on them.

So you could have components like maybe a Camera or a... FPS counter?... or...?

You see? Unfortunately this idea doesn't really work for real-world games. The kind of components you want for a game aren't really reusable. You might have a "player" component, but it will be very different to every other's game's "player" component.

I imagine it was for this reason, and for a simple lack of time, that the GUI was pulled before XNA 1.0.

But the API is still usable... **Here's why you shouldn't use it:**

Basically it comes down to what is easiest to write and read and debug and maintain as a game developer. Doing something like this in your loading code:

```
player.DrawOrder = 100;
enemy.DrawOrder = 200;

```

Is much less clear than simply doing this:

```
virtual void Draw(GameTime gameTime)
{
    player.Draw();
    enemy.Draw();
}

```

Especially when, in a real-world game, you might end up with something like this:

```
GraphicsDevice.Viewport = cameraOne.Viewport;
player.Draw(cameraOne, spriteBatch);
enemy.Draw(cameraOne, spriteBatch);

GraphicsDevice.Viewport = cameraTwo.Viewport;
player.Draw(cameraTwo, spriteBatch);
enemy.Draw(cameraTwo, spriteBatch);

```

(Admittedly you could share the camera and spriteBatch using the similar `Services` architecture. But that is also a bad idea for much the same reason.)

This architecture - or **lack thereof** \- is so much more light weight and flexible!

I can easily change the draw order or add multiple viewports or add a render target effect, just by changing a few lines. To do it in the other system requires me to *think* about what all those components - spread across multiple files - are doing, and in what order.

It's sort of like the difference between declarative vs imperative programming. It turns out that, for game development, imperative programming is far more preferable.

# Answer
> 29 votes
Hmmm. Got challenge this one for the sake of a bit of balance here I'm afraid.

There seem to be 5 charges in Andrew's reply, so I'll try and deal with each in turn:

*1) Components are an out-of-date and abandoned design.*

The idea of components design pattern existed long before XNA - in essence it is simply a decision to make objects, rather than the over-arching game object, the home of their own Update and Draw behaviour. For objects in its component collection, the game will call these methods (and a couple of others) automatically at the appropriate time - crucially the game object does not itself have to 'know' any of this code. If you wish to re-use your game classes in different games (and thus different Game objects), this de-coupling of objects is still fundementally a good idea. A quick look at the latest (professionally produced) demos of XNA4.0 from the AppHub confirms my impression that Microsoft are still (quite rightly in my view) firmly behind this one.

*2) Andrew can't think of more than 2 re-usable game classes.*

I can. In fact I can think of loads! I've just checked my current shared lib, and it comprises more than 80 *re-usable* components and services. To give you a flavour, you could have:

* Game State/Screen Managers
* ParticleEmitters
* Drawable primitives
* AI controllers
* Input controllers
* Animation controllers
* Billboards
* Physics & Collision Managers
* Cameras

Any particular game idea will need at least 5-10 things from this set - guaranteed - and they can be fully functional in a completely new game with one line of code.

*3) Controlling draw order by the order of explicit draw calls is preferrable to using the component's DrawOrder property.*

Well, I basically agree with Andrew on this one. BUT, if you leave all you component's DrawOrder properties as default, you can still explicitly control their draw order by the order in which you add them to the collection. This is really identical in 'visibility' terms to explicit ordering of their manual draw calls.

*4) Calling a load of object's Draw methods yourself is more 'lightweight' than having them called by an existing framework method.*

Why? Plus, in all but the most trivial of projects your Update logic and Draw code will totally overshadow your method calling in terms of performance hit in any case.

*5) Placing your code in one file is preferrable, when debugging, than having it in the individual object's file.*

Well, firstly, when I'm debugging in Visual Studio the location of a breakpoint in terms of files on disk is almost invisible these days - the IDE deals with the location without any drama. But also consider for a moment that you have a problem with your Skybox drawing. Is going to the Skybox's Draw method *really* more onerous than locating the skybox drawing code in the (presumably very lengthy) *master* draw method in the Game object? Nope, not really - in fact I would argue that it is quite the opposite.

So, in summary - please take a long hard look at Andrew's arguments here. I don't believe they actually give substantive grounds to write entangled game code. The upsides of the decoupled component pattern (used judiciously) are massive.

# Answer
> 4 votes
I disagree a bit with Andrew, but I also think there is a time and place for everything. I would not use a `Drawable(GameComponent)` for something as simple as a Sprite or Enemy. However, I would use it for a `SpriteManager` or `EnemyManager`.

Going back to what Andrew said about draw and update order, I think `Sprite.DrawOrder` would be very confusing for many sprites. Moreover, its relatively easy to set up a `DrawOrder` and `UpdateOrder` for a small (or reasonable) amount of Managers that are `(Drawable)GameComponents`.

I think that Microsoft would have done away with them if they really where that rigid and nobody used them. But they haven't because they work perfectly fine, if the role is right. I myself use them to develop `Game.Services` that are updated in the background.

# Answer
> 2 votes
I was thinking about this as well, and it occurred to me: For instance, to steal the example in your link, in an RTS game you could make every unit a game component instance. Okay.

But you could also make a UnitManager component, which keeps a list of units, draws and updates them as necessary. I guess the reason you want to make your units into game components in the first place is to compartmentalize code, so would this solution adequately achieve that goal?

# Answer
> 2 votes
In comments, I posted a condensed version of my answer old answer:

**Using `DrawableGameComponent` locks you into a single set of method signatures and a specific retained data model. These are typically the wrong choice initially, and the lock-in significantly hinders the evolution of the code the future.**

Here I shall attempt to illustrate why this is the case by posting some code from my current project.

---

The root object maintaining the state of the game world has an `Update` method that looks like this:

```
void Update(UpdateContext updateContext, MultiInputState currentInput)

```

There are a number of entry-points to `Update`, depending on whether the game is running on the network or not. It is possible, for example, for the game state to be rolled back to a previous point in time and then re-simulated.

There are also some additional update-like methods, such as:

```
void PlayerJoin(int playerIndex, string playerName, UpdateContext updateContext)

```

Within the game state there is a list of actors to be updated. But this is more than a simple `Update` call. There are additional passes before and after to handle physics. There's also some fancy stuff for deferred spawning/destroying of actors, as well as level transitions.

Outside of the game state, there's a UI system that needs to be managed independently. But some screens in the UI need to also be able to run in a network context.

---

For drawing, because of the nature of the game, there is a custom sorting and culling system that takes inputs from these methods:

```
virtual void RegisterToDraw(SortedDrawList sortedDrawList, Definitions definitions)
virtual void RegisterShadow(ShadowCasterList shadowCasterList, Definitions definitions)

```

And then, once it figures out what to draw, automatically calls:

```
virtual void Draw(DrawContext drawContext, int tag)

```

The `tag` parameter is required because some actors can hold onto other actors - and so need to be able to draw both above and below the held actor. The sorting system ensures that this happens in the correct order.

There is also the menu system to draw. And a *hierarchical* system for drawing the UI, around the HUD, around the game.

---

**Now** compare those requirements with what `DrawableGameComponent` provides:

```
public class DrawableGameComponent
{
    public virtual void Update(GameTime gameTime);
    public virtual void Draw(GameTime gameTime);
    public int UpdateOrder { get; set; }
    public int DrawOrder { get; set; }
}

```

There is no reasonable way to get from a system using `DrawableGameComponent` to the system I described above. (And those are not unusual requirements for a game of even modest complexity).

Also, it is very important to note that those requirements did not simply spring-up at the start of the project. They evolved over many months of development work.

---

What people typically do, if they start down the `DrawableGameComponent` route, is they start building on hacks:

* Instead of adding methods, they do some ugly down-casting to their own base type (why not just use that directly?).
* Instead of replacing the code for sorting and invoking `Draw`/`Update`, they do some very slow things to change the ordering numbers on-the-fly.
* And worst of all: Instead of adding parameters to methods, they start "passing" "parameters" in memory locations that are not the stack (the use of `Services` for this is popular). This is convoluted, error-prone, slow, fragile, rarely thread-safe, and likely to become a problem if you add networking, make external tools, and so on.

It also makes code re-use ***harder***, because now your dependencies are hidden inside the "component", instead of published at the API boundary.
* Or, they *almost* see how crazy this all is, and start doing "manager" `DrawableGameComponent`s to work around these problems. Except they still have these problems at the "manager" boundaries.

Invariably these "managers" could easily be replaced with a series of method calls in the desired order. Anything else is over-complicated.

Of course, once you start employing those hacks, it then takes real work to *undo* those hacks once you realise you need more than what `DrawableGameComponent` provides. You become "**locked in**". And the temptation is often to continue to pile upon hacks - which in practice will bog you down and limit the kinds of games you can make to relatively simplistic ones.

---

A lot of people seem to reach this point and have a visceral reaction - possibly because they use `DrawableGameComponent` and don't want to accept being "wrong". So they latch onto the fact that it is at least *possible* to make it "work".

*Of course* it can be *made* to "work"! We're programmers - making things work under unusual restraints is practically our job. But this restraint is not necessary, useful or rational...

---

What is particularly *flabbergasting* about is that it is *astonishingly* trivial to side-step this whole issue. Here, I'll even give you the code:

```
public class Actor
{
    public virtual void Update(GameTime gameTime);
    public virtual void Draw(GameTime gameTime);
}

List<Actor> actors = new List<Actor>();

foreach(var actor in actors)
    actor.Update(gameTime);

foreach(var actor in actors)
    actor.Draw(gameTime);

```

(It's simple to add in sorting as per `DrawOrder` and `UpdateOrder`. One simple way is to maintain two lists, and use `List<T>.Sort()`. It is also trivial to handle `Load`/`UnloadContent`.)

It is not important what that code actually *is*. **What is important *is that I can trivially modify it*.**

When I realise that I need a different timing system to `gameTime`, or I need more parameters (or an entire `UpdateContext` object with about 15 things in it), or I need a completely different order-of-operations for drawing, or I need some extra methods for different update passes, I can just go ahead and *do that*.

And I can do it immediately. I don't need to faff about picking `DrawableGameComponent` out of my code. Or worse: hack it in in some way that will make it even harder the next time such a need comes around.

---

There is really only *one* scenario where it is a good choice to use `DrawableGameComponent`: and that is if you are literally making and publishing **drag-and-drop-component-style** middleware for XNA. Which was its original purpose. Which - I will add - *no one* is doing!

(Similarly, it only really makes sense to use `Services` when making custom content types for `ContentManager`.)

---
Tags: xna, game-component
---


title: glViewport Problem

text:
# Question
Title: glViewport Problem
I am using glViewport() to render a 1024x1024 shadow depth buffer for a game that is using a 1000x600 game window. Under normal circumstances it works fine, however when I am running Bandicam to monitor the FPS of the game, it seems to crop the buffer by the ratio of the window's resolution to the buffer's resolution. All of the other buffers are unaffected and the shadow depth buffer is the only one that relies on glViewport() so I believe it has something to do with glViewport(). Any suggestions as to what might be going on are appreciated.

What the shadow depth map looks like normally:

What the shadow depth map looks like when Bandicam is running:

Some of the code related to the shadow depth buffer:

```
create_and_bind_framebuffer(&shadow_depth_map_framebuffer);
create_buffer(&shadow_depth_map_depth_buffer, GL_DEPTH_ATTACHMENT, SHADOW_RESOLUTION,
    SHADOW_RESOLUTION, GL_DEPTH_COMPONENT, GL_DEPTH_COMPONENT, GL_LINEAR, GL_REPEAT);
glDrawBuffer(GL_NONE);
glReadBuffer(GL_NONE);

...

glViewport(0, 0, SHADOW_RESOLUTION, SHADOW_RESOLUTION);
glBindFramebuffer(GL_FRAMEBUFFER, shadow_depth_map_framebuffer);
shadow_depth_shader.use();
glUniformMatrix4fv(shadow_depth_shader_light_space_uniform, 1, GL_FALSE, glm::value_ptr(light_space));

glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LESS);
glEnable(GL_CULL_FACE);
glCullFace(GL_BACK);
glDrawElementsInstanced(GL_TRIANGLES, static_cast<GLsizei>(m_mesh->indices.size()),
    GL_UNSIGNED_INT, nullptr, static_cast<GLsizei>(m_instances));
glDisable(GL_CULL_FACE);
glDisable(GL_DEPTH_TEST);
glBindVertexArray(NULL);
glUseProgram(NULL);

...

glViewport(0, 0, Window::get_size().x, Window::get_size().y);

```

# Answer
If it's only happening with Bandicam then the problem is with Bandicam, not your own software. Make sure you start Bandicam *before* you start the application you want to record. Also, in Bandicam's video settings, uncheck "Use enhanced capture method. (DirectX only)"
> 2 votes

---
Tags: opengl
---


# Question
Title: How to post player´s score on Facebook (with js)
I have my game made with Phaser (and compiled with cocoon.io) and on the leadersboard state I want to let the user to post his score on Facebook.

Well, I created an App on Facebook and I´m not finding a good solution to create this simple post, something like "I scored 10 points on this riduculous game..." Pretty easy on Twitter and not so easy on Facebook, I can find information about posting links and that stuff but I´m not finding a proper way to create a simple post just with text.

How do you guys do this? I guess I´m missing something, it shouldn´t be so complicated.

(I already tested this link and it´s not working for me Simple way to post score from my game to Facebook and Twitter? API Error Code: 191 API Error Description: The specified URL is not owned by the application Error Message: redirect\_uri is not owned by the application.)

# Answer
> 0 votes
First you'll need to setup Facebook JavaScript SDK: https://developers.facebook.com/docs/javascript/quickstart/v2.5

I have tried with open graph.

```
FB.ui({
 method: 'share_open_graph',
 action_type: 'namespace:action_type',
 action_properties: JSON.stringify({
     object_type:
      {
          'og:type': 'namespace:object_type',
          'og:title': 'I scored 10 points on this ridiculous game...',
          'og:image': 'http://www.bizreport.com/2011/02/03/android-logo-200x200.jpg',
          'og:description': 'Description'
      }
 })
}, function(response)
{
        if (response.post_id != null)
        {
            // handle response
        }
});

```

action\_type and object\_type are from Facebook application which I am sure you're familiar with.
And you'll need to submit the application for review if you're using custom stories.

Since I plan on using standard share dialog with custom image, text and link, I didn't spend much time figuring out open graph and how to set it up.

```
FB.ui({ method: 'feed',
    link: 'http://mysite.com/link-to-my-game',
    picture: 'http://www.bizreport.com/2011/02/03/android-logo-200x200.jpg',
    name: 'I scored 10 points on this ridiculous game...',
    description: 'Description',
    actions: [
        { name: 'Name of my site', link: 'http://mysite.com/' }
    ],
    display: 'popup'
  }, function (response)
  {
    if (response && response.post_id)
    {
        // handle response
    }
  });

```

Here you can see other parameters you may need: https://developers.facebook.com/docs/sharing/reference/feed-dialog/v2.5

With this approach, sharing works as soon as you make your application public.
I need something simpler and I didn't want to submit the application for review, so I went with second option, but the first option is more powerful in terms of customizing.

About that redirect\_uri error, I think it is because that redirect\_uri domain is not listed in App Domains on your Facebook application Settings page. (correct me if I am wrong)

I am no expert at this, I just spent some time searching what I need, collected the code and played with it.

---
Tags: javascript, facebook, phaser
---


# Question
Title: List cells in a 2D grid that belong in a sector / portion of a circle
Are there any algorithms to find out which cells in a 2D grid lie inside/is part of a slice of a circle - a pie slice shaped region?

Essentially, as per image below, I need to list out all the green cell coordinates.

At the moment, I am ray casting (using DDA based line interpolation) from the starting red cell, and sweeping across the area in with (arbitrarily chosen) small fixed angle increments, casting multiple rays; but this does not guarantee all cells will be covered.

Are there any approaches to this problem?

# Answer
If it helps I have a similar image from helping someone with this problem a long time ago. It better illustrates the constraints (you can ignore the near plane since your example doesn't have one):

As you can see you're trying to figure out which corners are inside of the region. You have to make sure they're within the circle which is a distance check. Say our camera is at cameraPosition represented by an (x, y) vector then for each point you're checking just do:

```
if ((point.x - cameraPosition.x) * (point.x - cameraPosition.x) + (point.y - cameraPosition.y) * (point.y - cameraPosition.y) < radius * radius)

```

Then you need to figure out if the points are inside of the two lines (3 in my example image, but we'll just use the two long lines). To do this you can use a dot product test. Generate your two vector using (cos(angle), sin(angle)) or however best works for you. Then for the left and right ray find it's left hand normal. (y, -x) or (-y, x) depending on your coordinate system. Then for each point we'll take the dot product between the (point - cameraPosition) and the normal. This will tell us which side of the ray our point is on. If it's on the wrong side we can discard it.

```
normalLeftX = -sin(angle1)
normalLeftY = cos(angle1)
normalRightX = sin(angle2)
normalRightY = -cos(angle2)
pointRayX = point.x - cameraPosition.x;
pointRayY = point.y - cameraPosition.y;
if (pointRayX * normalLeftX + pointRayY * normalLeftY > 0 &&
    pointRayX * normalRightX + pointRayY * normalRightY > 0)

```

(You might have to flip the normals between (y, -x) and (-y, x) if I made a mistake).

Combining all 3 checks will test if the point is inside. When a point is inside that means all 4 adjacent tiles are inside. (I'll let someone else expand it to code if they want).

I will point out that this algorithm is very closely related to an optimal vector processing algorithm for triangle rasterization. It would be completely overkill but you can use it if you have to test large amounts of tiles.

https://software.intel.com/en-us/articles/rasterization-on-larrabee
> 4 votes

# Answer
Your best bet is looking around for "Roguelike Vision Algorithms." This result seems to have a goodly collection, discussing existing methods--including raycasting--and then suggesting the author's own method. His algorithm contains more code than I am willing to copy-paste to this answer, but involves treating cells as walls with beveled edges and using some manner of raycasting:

Whether or not you are interested in "shadow casting" (that is, if a cell inside the cone is prevents areas behind it from being "visible") will likely play a large part in determining which method suits your needs.
> 0 votes

---
Tags: mathematics, geometry, grid
---


# Question
Title: What are other sources of screen tearing?
I have a DirectX11 based engine / application that is showing screen tearing on a certain system. The system has a large TV monitor with a GTX 980 graphics card. The tearing tends to happen in roughly the same spot on the screen when the camera / eyepoint is moving around. If we change settings (e.g. turn Ambient occlusion on ) then the tearing might move to a different location but it is still consistent. Our statistics show that application is running at 60Hz and vsync is turned on in the application. We also have an OpenGL based version of the application that doesn't exhibit this problem.

Things we've tried:

* Force vsync on in nvidia's control panel
* Turn on triple buffering on in nvidia's control panel
* Updated the nvidia driver
* Changed the monitor's refresh rate (tried 60, 59, and 24 hz)

None of these changes have changed screen tearing behavior. What are other sources of screen tearing and how can they be addressed?

Update:

This computer is using windows 7 but doesn't have windows aero enabled (its using a classic theme). On another computer, that didn't initially have any tearing problems, turning off windows aero makes screen tearing occur in the application.

# Answer
> 4 votes
It appears the problem was due to Windows Aero being turned off on the target machine. According to the nvidia forum here, there is no way to enable vsync if windows aero is not enabled, so the only fix is to enable windows aero, which eliminates the screen tearing.

# Answer
> 1 votes
In the menu of your graphics card you can select wether to use the global standart or "internal". You have to select the global standart. Then you can also disable "Multi-Threading". These two steps solved the same problem for me on my new PC.

---
Tags: directx, directx11, gpu
---


# Question
Title: Inverse of perspective matrix, for what?
I dont understand for what i need the inverse of the perspective Matrix in Computer Graphics and how do i calculate it?Maybe someone has an explanation for me.

# Answer
> 4 votes
The inverse projection matrix can be used for mouse/ray picking (letting you click an object in the world)

For more info: How do you determine which object/surface the user's pointing at with lwjgl?

# Answer
> 3 votes
An inverse projection matrix is used to invert coordinates from the projected space to either world or local space, i.e. You can use the inverse projection matrix to find out where a pixel is in relation to game objects.

This can be extremly useful for postprocessing effects like deferred rendering.

Calculating it can be a bit tricky and requires knowledge in linear algebra, if you have an API handy I suggest using it. Or google around for a while.

---
Tags: opengl, graphics
---


# Question
Title: One Android app, dynamic load several Unity games
I'm a newbie in this unity world, exciting about everything in it.

Days ago I came up with this idea:

1. One day someone finds this android app, naming "Blahblah Game Engine" or anything else. This app has to be very small, containing only some simple activity and Unity runtime, without further resources related to any specific game.
2. He installs it and sees an android activity, maybe a webview, showing a list of unity games the server currently hosting, produced by the very same Blahblah company.
3. Then he clicks on one and this "Blahblah Game Engine" loads the game build via network, starts an Unity activity, without prompting an installing dialog.
4. He can exit the current game whenever he likes, returns to the previous game list, and plays another, all working well in one app's lifetime.

In a word, the user experience is very much like how we play games on www.kongregate.com with pc browsers: light-weight app, mutiple games in one list, all loads via network, playing right away and installing-less.

Any game that listed in this app should not be installed as a standalone android app, it should be part of the "Blahblah Game Engine", stored as a file inside data folder of "Blahblah Game Engine", run as an activity of "Blahblah Game Engine".

Is it possible with Unity 5, both technically and legally? If I were to start this "Blahblah Game Engine" project, should I choose Unity 5 personal or pro licence?

# Answer
> 2 votes
You can do this using AssetBundles, although the games would essentially end up merged into one game, and you would host each inside.

So imagine building all of your games into one game project, with a special selection stage being the first thing loaded. Then, you'd break up the games into asset bundles. You would then trigger the asset bundle to download when the game was selected, and then you'd load the included Stage asset when it was finished.

I'm not sure if this is a good idea, though, because I don't think you can remove those bundles without removing the entire application.

# Answer
> 0 votes
Seems like you want a "Unity emulator" for android. I don't think that kind of thing even exists; but keep in mind that you can play every unity application in webplayer, so opening local file on an embedded web browser is an option if game is not "big".

---
Tags: unity, android
---


# Question
Title: Unity: How to manage a large amount of prefab variations?
The project that I'm working on demands the ability for game designers to be very flexible when balancing, customizing items, etc. The most difficult requirement to meet at the moment is that they want to drag-drop, say, a weapon prefab *onto a weapon field* in some game entity component and from there be able to tweak the prefab's parameters. If I provide some tools that create derived prefabs at such moments, then we'll end up with possibly hundreds of pretty much same prefab variations and also loose the ability to edit the initial prefab and transfer the changes to derivatives.

What I'm starting to consider is introducing a "Data Map" structure in every entity that requires high level of parameter customization. Every parameter would be set through methods like Set/GetFloat("key", "value"), Set/GetFloatArray, Set/GetInt, etc. So basically a dictionary that maps a string to a predefined set of data types. When a prefab of such entity would be drag-dropped into a field of another component, an editor tool would separate the "Data Map" from the prefab, allow the game designer to tweak the values of the keys and eventually serialize it to json. During runtime uppon instantiation of a prefab with a "Data Map" a manager would check the deserialized overrides and override the "Data Map" with the tweaked values if needed.

Though to me this sounds overly complicated and maybe some of you had a similar situation and came up with a simple solution? Maybe it's worth trying the ECS approach? Thanks.

An example: Let's say there are prefabs: Axe, Sword, Bow with a bunch of parameters configured, say Damage, Durability, etc. There are many other components that can accept a weapon prefab and once it's dropped, the designers want to have "on the spot editing" say, okay, for this situation here the Axe prefab needs to be a little different and have Damage+3. Creating a new prefab means that the link to the initial Axe prefab is lost and there are now two Axe prefabs that need to be managed - this is the problem we're trying to address.

# Answer
Though I'm still not 100% clear on what your designers need, here's one approach that should get you easy customization while maintaining prefab connections. The limitation is that you still need unique prefabs for each distinct thing you're going to store *outside* of a scene.

Core concept is either the "Decorator" pattern, or maybe the "Mutator" pattern. Either way I'll call them Mutators.

First, you need a base class that will be modified. This class has the various values you want to allow designers to set.

```
public class WeaponBase : MonoBehaviour {
    // values designers set directly *tied to the prefab*
    public float BaseDamage = 1.0f;
    public float BaseDurability = 10.0f;
    public int handsRequired = 1;

    // cached values built up from mutators below this object
    private float modDamage = 0.0f;
    private float modDurability = 0.0f;

    void Start () {
        WeaponMutator[] mutators = GetComponentsInChildren<WeaponMutator>();
        for(int i=0; i<mutators.Length; i++)
        {
          modDamage += mutators[i].getModDamage();
          modDurability += mutators[i].getModDurability();
          handsRequired = Mathf.Max(handsRequired, mutators[i].getHandsRequired());
        }
    }
    // update cache values in Update() if you want them to be changeable real-time.
}

```

Then, you need a 'mutator' script, which gets placed on a "CustomizeWeapon" prefab somewhere. In that script, you store values:

```
public class WeaponMutator : MonoBehaviour {
    // values designers set directly *in the scene hierarchy*
    public float ModDamage = 0.0f;
    public float ModDurability = 0.0f;
    public int ModHandsRequired = 1;

    public float getModDamage(){
        return ModDamage;
    }
    // ditto for getModDurability, getHandsRequired, etc.
}

```

(These could be merged, but I think to make the purpose clear for your designers, keeping them separate is helpful.)

Then for each core weapon type you *do* want individual prefabs for, you can use just the `WeaponBase` script if that's sufficient. If not, you can do WeaponMutators to define it as you need.

Your prefabs are then fairly simple. A standard 2-handed axe prefab might be:

* Axe (contains all the generic axe data in a `WeaponBase` instance)
    + 2H (GameObject with a `WeaponMutator`, just defines handsRequired as '2')

Then in your scene if the designers want to make some guard's 2H axe really strong, they could just drag-drop your WeaponMutator prefab under 2H, rename it, give it values:

* **Axe**
    + **2H Modifier**
        - NatalyaBuff (another WeaponMutator with ModDamage = 5.0f)

(Bolded to show which part is still linked to a prefab.)

There are of course many variations on this style of composition, and what I describe here is standard "fits in a StackOverflow answer" clunky.

If I were implementing this myself, I would probably build this using lists of ScriptableObjects in place of Mutator prefabs, perhaps something like what's described here. But it depends a lot on what kind of UX your designers will be happy with.

Hope this gets you headed in the right direction.
> 2 votes

# Answer
*(For example)* Have a script named PrefabDatabase. Define an Enum called PrefabType that covers all your prefabs. Then define a Dictionary\< PrefabType, GameObject \>. Assign all your prefabs to this dictionary.

There is an issue here though. You can't initialize dictionaries in inspector; here comes the solution:

```
 [System.Serializable]
 public struct EnumPrefabPair
 {
      public PrefabType type;     //For "TL;DR"ers, this is an enum that has a value for all prefabs...
      public GameObject prefab;   //...and this will be the prefab referance.
  }

  public EnumPrefabPair[] typesAndReferances;

```

Initialize this array in inspector and then in your Awake(), run a foreach loop on it to pass values to your dictionary.

Then you can simply referance your prefab by enum value.
> 2 votes

# Answer
What you can do is just replace the current prefab with a new prefab for that moment.for an example

```
var prefab1 : GameObject;
var prefab2 : GameObject;

// Prefab to use
private var prefab : GameObject;

function Start ()
{
   prefab = prefab1;
}

function Update ()
{
   // Use the first prefab when pressing 1 and the second prefab when pressing 2..
   if ( Input.GetKeyDown ("1") )
      prefab = prefab1;
   if ( Input.GetKeyDown ("2") )
      prefab = prefab2;

   if ( /* Something happens ?? */ )
      Instantiate (prefab, transform.position, Quaternion.identity);
}

```

Referred from : link
> 0 votes

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


# Question
Title: How to allow multiple bullets on screen at once
Using my universities API, I'm making a basic 2D game where pacman can shoot ghosts

I have a bullet class but at the moment, I only have one instance of the bullet

could anyone help edit this code/give me hints so that whenever I click i add a new bullet to the screen and after a certain amount of time it is deleted

```
void Bullet::update(int elapsedTime, Input::MouseState* mouseState, Player* pacman)
{

    if (mouseState->LeftButton == Input::ButtonState::PRESSED && !shooting)
    {
        setX(mouseState);
        setY(mouseState);
        shooting = true;
    }
    if (shooting)
    {
        float xDistance = mouseX - position->X;
        float yDistance = mouseY - position->Y;
        float hypotenuse = sqrt((xDistance * xDistance) + (yDistance * yDistance));

        position->X += elapsedTime * ((xDistance) / hypotenuse) / 2;
        position->Y += elapsedTime * ((yDistance) / hypotenuse) / 2;
        currentTime += (float)elapsedTime / 1000;

        if (currentTime >= maxTime)
        {
            setPosition(pacman->getPosition()->X + pacman->getRect()->Width / 2, pacman->getPosition()->Y + pacman->getRect()->Height / 2);
            currentTime = 0;
            shooting = false;
        }

    }
    else
    {
        setPosition(pacman->getPosition()->X + pacman->getRect()->Width / 2, pacman->getPosition()->Y + pacman->getRect()->Height / 2);
    }
}

```

and the bullet is loaded here

```
Texture2D* bulletTex = new Texture2D();
bulletTex->Load("Textures/bullet.png", false);
Vector2* bulletPos = new Vector2(pacman->getPosition()->X, pacman->getPosition()->Y);
Rect* bulletRect = new Rect(0.0f, 0.0f, 5, 5);
bullet = new Bullet(bulletPos, bulletRect, bulletTex);

```

Thanks in advance

# Answer
> 5 votes
It looks like your bullet class is doing too much work.

You are right to load the bullet texture only once, but you need one instance of a Bullet per Bullet on the screen. It is good that you are passing the bulletTex into the bullet so that all of these bullets can share the texture.

Your bullet should not be reacting to mouse input at all. In real life, bullets don't shoot themselves. Once a bullet is fired, it will just go in one direction until it hits something or, in the case of your game, time out. Instead, the bullet creation code needs to be higher up the chain. I suggest creating a shoot() method in your player that looks like this (bulletlist would be a std::vector of all bullets on the screen).

```
void Player::shoot()
{
   Vector2* bulletPos = new Vector2(this->getPosition()->X, this->getPosition()->Y);
   Rect* bulletRect = new Rect(0.0f, 0.0f, 5, 5);
   Bullet * bullet = new Bullet(bulletPos, bulletRect, bulletTex);
   bulletList.push_back(bullet);
}

```

then in your main game loop you can check if the mouse is pressed and call shoot() if it is. You can also add logic to the shoot function to add a delay that won't let the user shoot until x seconds have passed since the last shot so that you don't just get a steady stream of bullets.

Once a bullet is created, it's position is no longer dependent on the Player's position. Instead, it has a velocity vector that it will travel on until it hits something or times out. So in Bullet::Update() you do not need to check the player's position to determine where the bullet should be.

Lastly, "killing" your bullets after x seconds is easily done in the update() call. Every frame, update will be called and elapsed time is passed in. In your Bullet class you can add an timeTillDeath integer. Every update call you can subtract elapsedTime from timeTillDeath. Once timeTillDeath \<= 0 the bullet is considered dead and should be removed from the bullet list.

# Answer
> 1 votes
Use **vector** to hold multiple Bullet instances. It's also easy and safer to use.
**Documentation:** http://www.cplusplus.com/reference/vector/vector/

---
Tags: c++, 2d
---


# Question
Title: Does Google Play allow an account to log in to the same game on 2 devices?
I'm developing an online Android game with Unity. I want all Google Play accounts to have only one session logged in at a time.

Do I need to write my own code to disconnect an existing session on new login attempts, or does Google Play already handle this?

---

**Edit:**

An idea popped to my mind. I can save the logged in device's state to a a file on Google's Saved Games cloud, and write an instance-specific identifier to that file that indicates who has logged on last. And checking file constantly on all instances will allow me to disconnect instances whose identifier doesn't match the one on the file on the cloud.

Do you think this is a good idea? I mean, fetching file from cloud every second or so?

# Answer
> 1 votes
I just found this as an explanation of one of the members of ConflictResolutionStrategy enum in GooglePlayGames.BasicApi.SavedGame namespace in SDK:

```
    /// <summary>
    /// Choose the version of the saved game that existed before any conflicting write occurred.
    /// Consider the following case:
    /// - An initial version of a save game ("X") is written from a device ("Dev_A")
    /// - The save game X is downloaded by another device ("Dev_B").
    /// - Dev_A writes a new version of the save game to the cloud ("Y")
    /// - Dev_B does not see the new save game Y, and attempts to write a new save game ("Z").
    /// - Since Dev_B is performing a write using out of date information, a conflict is generated.
    ///
    /// In this situation, we can resolve the conflict by declaring either keeping Y as the
    /// canonical version of the saved game (i.e. choose "original" aka <see cref="UseOriginal"/>),
    /// or by overwriting it with conflicting value, Z (i.e. choose "unmerged" aka
    /// <see cref="UseUnmerged"/>).
    /// </summary>

```

So i think the answer of my question is "yes".

# Answer
> -1 votes
According to Google Developers Guide, Google Play Services will not check or sign out other instances of the app on other devices. You will have to sign other users out manually using your own code.

---
Tags: unity, android, google-play, google-play-services
---


# Question
Title: Change in direction should slow down object and accelerate in new heading (2D grid-based)
I'm trying to implement some sort of faux space physics in my 2D game. I have a top down view of my space ship. You can change direction and set a speed up to a maximum which then accelerates the ship in that direction according to the ship's engine acceleration amount.

I have code working fine with getting the ship to slowly start moving in that direction and increase speed up until the max speed is met.

### Update

While the answers have been slightly helpful, it's not getting me to my final solution. I cannot seem to transform the theories into working code. Here are some more parameters:

1. We're working with a 2D grid
2. The ship has a single engine where you can set the power from 0 to 1 to indicate full power.
3. The engine has a max speed
4. There is a fake space-friction where if you no longer apply power to the ship, it will eventually stop.

### Problem

The problem I'm having is when I change direction. If I'm travelling in one heading at 300 speed, then change the heading to the opposite, I'm now instantly travelling at the set speed instead of slowing down, and getting back up to that speed in that direction.

### Desired state

### Current Code

```
public void Update(Consoles.Space space)
{
    var GameTimeElapsedUpdate = (float)SadConsole.Engine.GameTimeElapsedUpdate;

    Graphic.PositionOffset = viewPortMaster.Position;

    // Update the engine
    ShipDetails.Engine.Update();

    // Degrade the current velocity with friction??
    if (velocity.Length() < 0f)
    {
        var accelerationFrame = ShipDetails.Engine.GetAccelerationFrame();

        if (velocity.X > 0)
            velocity.X -= accelerationFrame;
        else if (velocity.X < 0)
            velocity.X += accelerationFrame;

        if (velocity.Y > 0)
            velocity.Y -= accelerationFrame;
        else if (velocity.Y < 0)
            velocity.Y += accelerationFrame;
    }

    // Handle any new course adjustments
    if (IsTurnRightOn)
        SetHeading(heading + (ShipDetails.TurningSpeedRight * GameTimeElapsedUpdate));

    if (IsTurnLeftOn)
        SetHeading(heading - (ShipDetails.TurningSpeedLeft * GameTimeElapsedUpdate));

    // Handle any power changes
    if (IsPowerIncreasing)
    {
        SetPower(ShipDetails.Engine.DesiredPower + (GameTimeElapsedUpdate * ((ShipDetails.Engine.MaxSpeed / Settings.SecondsForFullPowerAdjustment) / ShipDetails.Engine.MaxSpeed)));

        if (ShipDetails.Engine.DesiredPower > 1.0d)
            ShipDetails.Engine.DesiredPower = 1.0d;
    }

    if (IsPowerDecreasing)
    {
        SetPower(ShipDetails.Engine.DesiredPower - (GameTimeElapsedUpdate * ((ShipDetails.Engine.MaxSpeed / Settings.SecondsForFullPowerAdjustment) / ShipDetails.Engine.MaxSpeed)));

        if (ShipDetails.Engine.DesiredPower < 0.0d)
            ShipDetails.Engine.DesiredPower = 0.0d;
    }

    // Calculate new velocity based on heading and engine

    // Are we changing direction?
    if (vectorDirectionDesired != vectorDirection)
    {
        // I think this is wrong, I don't think this is how I'm supposed to do this. I don't really want to
        // animate the heading change, which is what I think this is actually doing..

        if (vectorDirectionDesired.X < vectorDirection.X)
            vectorDirection.X = Math.Min(vectorDirection.X + (vectorDirectionDesired.X * Settings.SpeedSquareSecond * GameTimeElapsedUpdate), vectorDirectionDesired.X);
        else if (vectorDirectionDesired.X > vectorDirection.X)
            vectorDirection.X = Math.Max(vectorDirection.X + (vectorDirectionDesired.X * Settings.SpeedSquareSecond * GameTimeElapsedUpdate), vectorDirectionDesired.X);

        if (vectorDirectionDesired.Y < vectorDirection.Y)
            vectorDirection.Y = Math.Min(vectorDirection.Y + (vectorDirectionDesired.Y * Settings.SpeedSquareSecond * GameTimeElapsedUpdate), vectorDirectionDesired.Y);
        else if (vectorDirectionDesired.Y > vectorDirection.Y)
            vectorDirection.Y = Math.Max(vectorDirection.Y + (vectorDirectionDesired.Y * Settings.SpeedSquareSecond * GameTimeElapsedUpdate), vectorDirectionDesired.Y);
    }

    vectorDirection = vectorDirectionDesired;

    if (ShipDetails.Engine.Power != 0)
    {

        var force = new Vector2(vectorDirection.X * (float)ShipDetails.Engine.Speed, vectorDirection.Y * (float)ShipDetails.Engine.Speed);
        var acceleration = new Vector2(force.X / ShipDetails.Engine.Acceleration, force.Y / ShipDetails.Engine.Acceleration) * GameTimeElapsedUpdate;

        velocity = new Vector2(velocity.X + acceleration.X, velocity.Y + acceleration.Y);

        Point endingLocation;
        endingLocation.X = (int)velocity.X;
        endingLocation.Y = (int)velocity.Y;
        velocity.X -= endingLocation.X;
        velocity.Y -= endingLocation.Y;

        MapPosition += endingLocation;
    }

    if (this == Settings.GameWorld.CurrentShip)
    {
        var debug = space.GetDebugLayer();
        debug.Clear();
        debug.Print(0 + space.ViewArea.X, 0 + space.ViewArea.Y, $"Ship: {MapPosition}");
        debug.Print(0 + space.ViewArea.X, 1 + space.ViewArea.Y, $"Speed: {ShipDetails.Engine.Speed} Desired: {ShipDetails.Engine.DesiredPower}");
        debug.Print(0 + space.ViewArea.X, 2 + space.ViewArea.Y, $"Heading: {heading} Adjusted: {adjustedHeading}");
        debug.Print(0 + space.ViewArea.X, 3 + space.ViewArea.Y, $"Dir: {vectorDirection.X.ToString("0.00")}, {vectorDirection.Y.ToString("0.00")} DirDes: {vectorDirectionDesired.X.ToString("0.00")}, {vectorDirectionDesired.Y.ToString("0.00")}");
    }

}

```

### ShipEngine Code

```
class ShipEngine
{
    public int Acceleration;
    public int AccelerationBonus;
    public int MaxSpeed;
    public int MaxAfterburner;

    public int Speed { get { return (int)(Power * MaxSpeed); } }

    // This is a 0-1 no power to full power rating where MaxSpeed is full power
    public double DesiredPower { get { return desiredPower; } set { desiredPower = value;  if (value != Power) isDesiredTriggered = true; } }
    public double Power;

    public bool IsAdjusting { get { return Speed != 0; } }

    private double desiredPower;
    private bool isDesiredTriggered;

    public void Update()
    {
        if (DesiredPower != Power)
        {
            var GameTimeElapsedUpdate = (float)SadConsole.Engine.GameTimeElapsedUpdate;
            var accelerationFrame = (((float)(Acceleration + AccelerationBonus) / Settings.SpeedSquareSecond) * GameTimeElapsedUpdate);

            if (DesiredPower > Power)
            {
                Power += accelerationFrame;

                if (Power > DesiredPower)
                    Power = DesiredPower;
            }
            else if (DesiredPower < Power)
            {
                Power -= accelerationFrame;

                if (Power < DesiredPower)
                    Power = DesiredPower;
            }
        }
    }

    public float GetAccelerationFrame()
    {
        return (((float)Acceleration / Settings.SpeedSquareSecond) * (float)SadConsole.Engine.GameTimeElapsedUpdate);
    }

}

```

# Answer
> 7 votes
I'm not familiar with `xna`... but I know maths. And implementing physics without understanding the math behind it is like going into politics without knowing how to lie. So let's get started!

First of all, your way of moving the ship around isn't really physics based. You don't want the player to change the position of the ship directly. What you want to do is let the player **apply acceleration** to the ship, then let the physics **calculate the ship's velocity**, then let the world **change the ship's position** by that newly calculated velocity. Velocity is the difference in the position of the ship in time. If it moved 5 units right and 1 unit up, it moved by velocity of `(5,-1)`. Acceleration is the difference in velocity of the ship - it only influences the ship's position by changing its velocity. If your ship was going 2 units to the left and 1 unit down, meaning the velocity of `(2,1)`, and the player accelerates it in the opposite direction, meaning `(-2,-1)`, it'll stop in place with the next unit of time (be it frame or tick or whatever). In other words, you need to add acceleration vector to the velocity vector and then calculate where the ship will be next.

## Vectors

Imagine an arrow that starts somewhere (origin), points to somewhere (direction) and has a certain length (magnitude). Now describe it with two values - how much X and how much Y is its end from its start. For simplification I'll only talk about X axis which means your vectors point at something that is "that much X" to the right (positive) or to the left (negative).

## Velocity

Now, how the ship's position should change between frames? With velocity vector. Let's assume your ship starts at location (0,0) with velocity (12,0). It means it will change it's position as follows:

```
   Position:   Velocity:
 1 (0,0)       (12,0)
 2 (12,0)      (12,0)
 3 (24,0)      (12,0)
 4 (36,0)      (12,0)

```

## Acceleration

How do we change the direction? You don't want to just change the velocity to `(-12,0)`. That'd mean the ship goes from 100 parsecs right to 100 parsecs left in one "frame". I wouldn't want to be on that ship when it happens. Again, the "length" of the vector is called "magnitude" and in case of velocity it happens to be speed. So you want the magnitude of velocity (ship's speed) to slowly decrease to 0 and then to accelerate to negative 12 (which means it moves in the opposite direction). You can do so by adding acceleration to the velocity, e.g. the acceleration of `(-4,0)`, so now the ship moves as follows (player pressed *left* on a 3rd "frame" then released it on a 9th):

```
   Position:   Velocity:   Acceleration:
 1 (0,0)       (12,0)      (0,0)     # starts in 0,0 going right
 2 (12,0)      (12,0)      (0,0)
 3 (24,0)      (12,0)      (-4,0)
 4 (36,0)      (8,0)       (-4,0)    # starts to slow down
 5 (44,0)      (4,0)       (-4,0)
 6 (48,0)      (0,0)       (-4,0)    # stops
 7 (48,0)      (-4,0)      (-4,0)    # changes direction
 8 (44,0)      (-8,0)      (-4,0)    # starts to go left
 9 (36,0)      (-12,0)     (0,0)     # goes left at steady speed
10 (24,0)      (-12,0)     (0,0)
11 (12,0)      (-12,0)     (0,0)
12 (0,0)       (-12,0)     (0,0)     # passes 0,0 starting point
13 (-12,0)     (-12,0)     (0,0)     # keeps going left with the same speed
14 (-24,0)     (-12,0)     (0,0)

```

So you want to apply an acceleration of `(4,0)` to make the ship gradually gain speed in a positive X direction when the player presses the right arrow and apply an acceleration of `(-4,0)` when left arrow is pressed. Obviously when no keys are pressed you don't apply any acceleration meaning the ship is keeping it's velocity (moving at constant speed in given direction). If you want it to slow down gradually when no key is pressed, add another vector, call it `Drag` and give it direction always opposite to velocity (i.e. towards the back of the ship) until the magnitude of velocity reaches 0. Hopefully you get the idea.

## Code

What I would do (pseudo code, you'll have to fix it, add encapsulation, etc., also it ignores some aspects, e.g. going diagonal is slightly faster than straight left, right, up or down):

```
class Vector {
    x = 0;
    y = 0;

    add(Vector v) {
        this.x += v.x;
        this.y += v.y;
    }

    multiply(Vector v) {
        return new Vector( // return because we don't want to
            this.x * v.x,  // change the existing vector, it's
            this.y * v.y   // only for calculating new ones
        );
    }
}

class Ship {
    position = new Vector;
    velocity = new Vector;
    maxSpeed = 12;

    accelerate(Vector acceleration) {
        this.velocity.add(acceleration);
        if (this.velocity.x > this.maxSpeed)
            this.velocity.x = this.maxSpeed);
        if (this.velocity.x < -1*this.maxSpeed)
            this.velocity.x = -1*this.maxSpeed); // the same for y
    }
}

switch (pressedKey) {
    case 'right': Ship.accelerate(new Vector(4,0)); break;
    case 'left': Ship.accelerate(new Vector(-4,0)); break;
}

Ship.position.add(Ship.velocity); // world updates the ship's position

drag_factor = new Vector(-0.1, -0.1); // 10% force in the opposite direction
drag = Ship.velocity.multiply(drag_factor);

Ship.position.add(drag); // world adds drag

```

# Answer
> 3 votes
In order to do this you need to simulate inertia. This is how I would recommend doing it:

```
class Ship
{
    public Vector2 Pos; //Current ship position
    public Vector2 Vel; //Store current velocity as a vector
    public float Rot; //What direction the ship is facing in radians

    public float Accel; //Maximum acceleration
    public float MaxSpeed; //Maximum velocity

    public void Update(float elapsedTime)
    {
        this.Pos += this.Vel * elapsedTime; //Update our position based on our current velocity
        this.Rot = MathHelper.WrapAngle(this.Rot); //Wrap our heading angle to always be between -Pi and Pi
        if (this.Vel.LengthSquared() > this.MaxSpeed * MaxSpeed) //Keep the velocity vector's length shorter than our max speed
        {
            this.Vel.Normalize();
            this.Vel *= this.MaxSpeed;
        }
    }

    public void ThrustForward(float elapsedTime) //Apply our acceleration to our current velocity
    {
        this.Vel += Vector2.Transform(-Vector2.UnitY * this.Accel * elapsedTime, Matrix.CreateRotationZ(this.Rot));
    }
}

```

# Answer
> 0 votes
Ok it's actually really simple to achieve. First of all as u mentioned, ur engine direction describes the path of movement. This makes it comfortable to work with.

First of all, always store a vector of the direction ur moving.

Next u must have a vector of the lookat of ur engine.

So for now when u start moving, let's say right, the both the direction and lookat of engine vector are pointing to the right. When u now want to turn let.s say to top (90 degree), then u simply turn the lookat engine vector.

Now comes the fun part. Determine with any function how strong to effect the change of direction and break.

first of the direction change.

Depending on ur Speed and change of angle u could slow down and turn the direction vector.

If u want a complete direction change (180 degree), then it's simple math. In ur update just change ur speed slowly. When speed turns to zero, flip the direction vector for 180 degree and start adding speed again.

On a 90 degree turn, it get's a bit more complicated. u need to define a function to calculate how much the ship is allowed to turn according to speed and if it gonna slow down how much. But u can play with the values till it fits what u want.

---
Tags: xna, c#, physics, monogame
---


# Question
Title: Sound isn't playing in Game Maker Studio when interacting with an object
I'm making a small game in Game Maker Studio. I have a piece of code that moves the player to the next room when he touches `obj_star`: this works. I have another line that tries to play sound\_collect when the star is touched, but the game just moves to the next room without playing the sound. This code is in the Step event

My code is as follows:

```
//Get the player's input
key_right = keyboard_check(vk_right);
key_left = -keyboard_check(vk_left);
key_jump = keyboard_check_pressed(vk_space);

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

if (place_meeting(x,y+1,obj_wall))
{
vsp = key_jump * -jumpspeed
}
//Horizontal Collision
if (place_meeting(x+hsp,y,obj_wall))
{
while(!place_meeting(x+sign(hsp),y,obj_wall))
{
    x += sign(hsp);
}
hsp = 0;
}
x += hsp;

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

//Sounds
if (place_meeting(x+hsp,y,obj_star))
{
sound_play(sound_collect)
};
//Next Level
if (place_meeting(x+hsp,y,obj_star))
{
room_goto_next()
};

```

# Answer
I see multiple problems with your code that I can see. First is the inconsistent use of the semicolon as a terminator:

```
if (place_meeting(x+hsp,y,obj_star))
{
  room_goto_next()
};

```

should be:

```
if (place_meeting(x+hsp,y,obj_star))
{
  room_goto_next();
}

```

Also, because the same condition is being checked, you can combine the two if blocks to clean up the code.

```
if (place_meeting(x+hsp,y,obj_star))
{
  sound_play(sound_collect);
  room_goto_next();
}

```

Don't know if this will solve your problem but it will clean up your code. If it doesn't work try using the `audio_sound_play` function.
> 1 votes

# Answer
You should put the sounds as part of the collision event. When it collides with obj\_star You could then say:

```
sound_play(sound_collect);

room_goto_next();

```
> 0 votes

---
Tags: android, game-maker
---


# Question
Title: With Cardboard, reorient player to direction of gaze
This may be a little hard to follow. I have a script set up in Unity, and attached to my CardboardMain object that allows a user to press the button on a Cardboard headset to move in the direction of their gaze. They move only when the button is pressed. Since this game is a seated experience, I want the "virtual seat" to gradually reorient itself in the direction of the user's gaze, in the same way a pilot's seat, and plane would reorient with a turn. This way, whichever direction the user is traveling, it always becomes *forward* in the game, and reality. The idea is that the user's body can remain facing in it's starting orientation, while being able to freely look - and travel around. I'm new to C# and Unity, but I've made enough progress on this project that I cannot give up.

I'm using head.Gaze.direction to drive movement, and it looks like rotating CarboardMain will rotate everything inside of it. The hierarchy looks like this:

CardboardMain \> Head \> Main Camera

So, I think I could apply the needed rotation to the CardboardMain object, right?

This is the code so far, but I'm not sure where to go from here. My first thought was to rotate the scene, but that seems like it could complicate things as the project continues to develop.

```
public class movementScript : MonoBehaviour {
public float sub_speed = 0.03f;

private CardboardHead head;
// Use this for initialization
void Start()
{
    head = Camera.main.GetComponent<StereoController>().Head;
}

void Update() {
    int fingerCount = 0;
    foreach (Touch touch in Input.touches) {
        if (touch.phase != TouchPhase.Ended && touch.phase != TouchPhase.Canceled)
            fingerCount++;

    }
    if (fingerCount > 0)
        transform.position += sub_speed * head.Gaze.direction;

}

```

}

# Answer
> So, I think I could apply the needed rotation to the CardboardMain object, right?

I am not sure if by doing that you will achieve what you were thinking.

But if that is the case, by your comments your current problem boils down to a mere issue of rotating any GameObject towards a given specific direction.

If that is the case, I would suggest you try:

```
void Update() {
    float currentstep = speed * Time.deltaTime;
    Vector3 newDirection = Vector3.RotateTowards(CardboardMain.transform.forward,  head.Gaze.direction, currentstep, 0.0F);
    CardboardMain.transform.rotation = Quaternion.LookRotation(newDirection);
}

```
> 0 votes

---
Tags: unity
---