# Question
Title: Parts of sprite disappear when zoomed out
I'm playing around with making a roguelike and I want to use ascii characters as tiles in the game. I'm using a 256x256 sprite map where each character ends up being a 32x32 box.

This works fine, however the sprites end up being weirdly drawn, especially when zoomed out. Take a look:

As you can see, only the biggest zoom-in has no weird artifacts in it.

I tried playing around with the settings here and that's the best configuration I can get. PPU at 32 or 256 or even 1 doesn't seem to make any difference. Disabling compression doesn't do anything either.

I've also tried using a sprite map where I resized it so every character is 256x256 but it's still the same problem when zoomed out.

# Answer
> 1 votes
You need to enable Mip Maps and filtering on minimisation.

Point filtering drops entire pixels rows and columns when scaling down (zooming out).

The downside of mip maps and filtering is your sprites won't have sharp pixels anymore and will be blended when zoomed out. You can't have it both ways.

# Answer
> 0 votes
I fixed it by using the DeadSimple Pixel Perfect Camera.

---
Tags: unity, graphics, camera, spritesheet, pixel
---


# Question
Title: Using a Compute Shader in Unity to convert a texture to a float array
I have a fairly simple requirement for a compute shader (DirectCompute through Unity). I have a 128x128 texture and I'd like to turn the red channel of that texture into a 1d array of floats. I need to do this very often so just doing a cpu-side for loop over each texel won't cut it.

Initialization:

```
    m_outputBuffer = new ComputeBuffer(m_renderTexture.width * m_renderTexture.height, sizeof(float));
    m_kernelIndex = m_computeShader.FindKernel("CSMain");

```

Here is the C# method:

```
/// <summary>
/// This method converts the red channel of the given RenderTexture to a
/// one dimensional array of floats of size width * height.
/// </summary>
private float[] ConvertToFloatArray(RenderTexture renderTexture)
{
    m_computeShader.SetTexture(m_kernelIndex, INPUT_TEXTURE, renderTexture);

    float[] result = new float[renderTexture.width * renderTexture.height];

    m_outputBuffer.SetData(result);
    m_computeShader.SetBuffer(m_kernelIndex, OUTPUT_BUFFER, m_outputBuffer);

    m_computeShader.Dispatch(m_kernelIndex, renderTexture.width / 8, renderTexture.height / 8, 1);

    m_outputBuffer.GetData(result);

    return result;
}

```

and the entire compute shader:

```
// Each #kernel tells which function to compile; you can have many kernels
#pragma kernel CSMain

// Create a RenderTexture with enableRandomWrite flag and set it
// with cs.SetTexture
Texture2D<float4> InputTexture;
RWBuffer<float> OutputBuffer;

[numthreads(8, 8, 1)]
void CSMain(uint3 id : SV_DispatchThreadID)
{
    OutputBuffer[id.x * id.y] = InputTexture[id.xy].r;
}

```

the C# method returns an array of the expected size, and it usually sort-of-corresponds to what I expect. However, even if my input texture is uniformly red, there'll still be some zeroes.

# Answer
> 1 votes
Ok, thanks to some direction from @DMGregory I reconsidered and solved my own question. The answer was in two parts: I was combining the x and y coordinates (id.x and id.y) strangely, and I was using the wrong input semantic. (SV\_GroupThreadID instead of SV\_DispatchThreadID)

So here's the solution. I also flipped the y axis to match my intuition.

```
// Each #kernel tells which function to compile; you can have many kernels
#pragma kernel CSMain

// Create a RenderTexture with enableRandomWrite flag and set it
// with cs.SetTexture
Texture2D<float4> InputTexture;
RWBuffer<float> OutputBuffer;

[numthreads(8, 8, 1)]
void CSMain(uint3 id : SV_DispatchThreadID)
{
    uint w, h;
    InputTexture.GetDimensions(w, h);

    OutputBuffer[id.x + id.y * w] = InputTexture[float2(id.x, h - 1 - id.y)].r;
}

```

---
Tags: unity, shaders, textures, rendertexture, compute-shader
---


# Question
Title: How to change animation start/end proprieties via script?
Is there a way of changing the start/end proprieties (Transform, Rect Transform, etc..) of an animation via script? Like, I have 5 objects that start at the same position but should end in different positions, so I would like to change the end positions of each one via script.

As I haven't found a way to do this, I created 5 animations for this, but I'd like to just have one animation and change its proprieties in runtime.

# Answer
I'm not sure if that's possible to be honest, but if you want something completely dynamic, why not make a script that handles the animation itself?

Here's an example:

```
public Vector3 startPosition;
public Vector3 endPosition;

float counter = 1f;

public Update() {

    if (counter <= 0f) {

        // Replace 1.0f with another number to change animation's speed
        counter -= 1.0f -Time.deltaTime;

        /* Replace `position` with `localPosition`, if you would
         * like your animation to take place in local space,
         * instead of world space
         *
         * This is doing linear interpolation, if you would like to do
         * something more fancy, you can tweak `counter`, search for
         * "easing functions" for more info
         */
        transform.position = Vector3.Lerp(startPosition, endPosition, counter);

    }

}

public Animate() { counter = 0f; }

```

Add this in a class, make sure to add additional data like rotation or scale (if you want). Attach the script to any object that you want to animate, then change the `startPosition` and `endPosition` from the Inspector (or from a script, if the object is also made dynamically) for each individual object. Even though all objects are doing the same animation, they are moving to different locations.

Edit:

To support `RectTransform` you use the same logic, but you have to play with its anchor, pivot and position. You can read Unity's RectTransform API, but also make sure to read Unity: Designing UI for Multiple Resolutions, which can help you understand which specific value to animate and why (to appear properly on different screen sizes).
> 1 votes

---
Tags: unity, animation
---


# Question
Title: Record video and sound from device camera and show it as a texture
I need to record and show video from a real camera device in iOS/Unity and show that video as a texture in RawImage (Image of what I want)

What I have tried so far:

* **Unity WebCamTexture API**: It shows the camera in a texture but it has two problems! It does not record audio and does not have an API to save video!
* **Camera Capture Plugin**: I bought this plugin but unfortunately it does not have the feature to show video in a texture; it just opens the camera device's application.
* **EverPlay plugin**: I tried this plugin and it seems that it just creates a video from the screen and not the camera
* **Unity Video Capture API**: There is also this API for recording video with sound but unfortunately it is part of Windows Mixed Reality and does not support iOS
* **Using Objective C**: I tried to write the video recording section directly in Objective C, I did it but I could not find a way to embed that in the Unity scene -- I'm not sure it's even possible! (what I tried)

I appreciate any other solutions that can help.

# Answer
> 2 votes
Are you targeting Metal or OpenGL?

I would suggest taking a look at CreateExternalTexture

This lets you basically take an `id<MTLTexture>` (Metal) or `GLuint` pointing to a native texture (OpenGL) and turn it into a Unity texture.

You can use `AVFoundation` to get the video and stream it to a Metal texture. Here is Apple’s example project which does that part.

---
Tags: unity, camera, ios, video
---


# Question
Title: What is the purpose of a "press start" screen?
A lot of games start with their intros and vendor videos, and then show a "Press Start" screen before the actual main menu.

I never quite figures out the purpose of this. Why not go to the main menu directly? The only possible explanation that made sense to me is that when multiple controllers are connected it allows to identify the one that the player wants to use.

# Answer
> 43 votes
The historical reason for this is somewhat different from the current reasoning - previously it was to have a 'safe' screen to go back to which was always resident in memory, so that if the game had gone to a demo loop and the player touched the controller, it could instantly return to the start screen and let interaction commence with no delay.

However typically these days it serves another purpose. For recent generation consoles, the start screen is deliberately user-agnostic. Nothing on the start screen requires knowledge of which user is actively playing the game. You get to the start screen without loading any save data, and without requiring a user to be logged in. So you can get to the start screen quickly and without having to show any TCR compliant messages.

Requiring the user to press start gets you a key piece of information: which controller is the primary controller. It's not necessarily the first or only controller connected, and you might have several equally valid controllers to choose from. You don't know which one the user has actually picked up though until they've pressed a button on it. Once that controller is used, it will remain the primary controller for the rest of the gameplay session.

On XBox 360 (and most likely other consoles), finding out what the primary controller is also typically gets you another bit of information: which user is playing the game. Because each user is bound to a single controller, you know which user is playing, and from that you know which save data to load. Many / most of the content is bound to specific users, so it's important to determine who is playing the game before continuing. If no-one is logged into the console, games will typically prompt at this point for a user to log in, or ask if the player is happy to play as a 'guest', i.e. without saving (because with no user, there's nowhere to save to).

You'll also find that, typically, changing users (by signing out and back in) will cause you to return to the start screen. This is because the relevant user-specific data is loaded after this point in the game, and the start screen is the easiest point in the user interface flow where you know exactly what data is loaded (none).

# Answer
> 36 votes
This is required by the console manufacturer as part of the standard Technical Requirements Checklist (TRC). One reason is to allow the startup screen to loop back to a demo mode if no one has touched the controller, this stops screen burn and makes it easy for a store to simply pop in a game and let it run looping action with no intervention.

Your guess is the secondary purpose, and that's the way it's used =)

# Answer
> 3 votes
As well as the reasons given above, arcade games are also another reason. Usually an arcade game will loop the menu/intro until a coin is inserted to start a game, however when ported to home consoles, the coins are no longer needed so it looks for a button input instead.

# Answer
> 2 votes
I recently added a start screen to my mobile game. The decision came after testing it on an older phone. The game front loads a majority of the assets into memory when the game starts, and was causing a significant delay between launching the app and getting the first feedback loop.

I realize there are many ways to solve this, but I decided to slap a start screen that starts loading the next scene in the background. When the user actually clicks the start button they get their first feedback of a sound and a fade transition. It also seems to reduce the load time, but this could be due to not having to stare at a black screen or stagnant loading screen after launching.

# Answer
> 1 votes
On old arcade systems, pressing the start button, initializes the seed of the random number generator. This seed is used so that every play session is unique. On newer systems, I don't have a clue, I guess it's just a habit.

Also see:

---
Tags: game-design, interface
---


title: Weapon Switching - Unity 3d

text:
# Question
Title: Weapon Switching - Unity 3d
when I switch between weapons by Number \[1 2 3 4\] the weapon don't switch between them but the variable " selected weapon value changed" anyone help me, this my Code and screenshots!

```
    using UnityEngine;
    using UnityEngine.Networking;

    public class weaponSwitching : NetworkBehaviour
   {
      public int selectedWeapon = 0;

   void Start () {

      CmdSelectWeapon();
   }

   void Update () {
      if (!isLocalPlayer)
      {
         return;
      }
    if (Input.GetKeyDown(KeyCode.Alpha1))
    {
        selectedWeapon = 0;
    }
    if (Input.GetKeyDown(KeyCode.Alpha2) && transform.childCount >= 2)
    {
        selectedWeapon = 1;
    }
    if (Input.GetKeyDown(KeyCode.Alpha3) && transform.childCount >= 3)
    {
        selectedWeapon = 2;
    }
    if (Input.GetKeyDown(KeyCode.Alpha4) && transform.childCount >= 4)
    {
        selectedWeapon = 3;
    }
}

[Command]
void CmdSelectWeapon()
{
    int i = 0;
    foreach(Transform weapon in transform)
    {
        if(i == selectedWeapon)
        {
            weapon.gameObject.SetActive(true);
        }
        else
        {
            weapon.gameObject.SetActive(false);
        }
        i++;
        if (i == 4) // this my Gun Effect i don't need to deactivate
        {
            weapon.gameObject.SetActive(true);
        }
    }
 }
}

```

https://i.stack.imgur.com/ZNJDJ.jpg "Weapons Holder"

https://i.stack.imgur.com/zWxB5.jpg "Weapons HolderInspector"

# Answer
I think the probles is that you are not calling the server after you change the Weapon's index, after you change the index, you must deactivate all weapon childs and just activate the one in the index, with **Transform.GetChild**. Also, I cleaned your CmdSelectWeapon, since you are deactivating and activating the same GameObject, you say that there is a gun effect that you don't need to deactivate, you could then avoid the iterator 'i' go there, or you could put another criteria.

```
using UnityEngine;
    using UnityEngine.Networking;

    public class weaponSwitching : NetworkBehaviour
    {
      public int selectedWeapon = 0;

    void Start ()
    {
      CmdSelectWeapon();
    }

   void Update ()
   {
        if (!isLocalPlayer)
        {
            return;
        }
        if (Input.GetKeyDown(KeyCode.Alpha1))
        {
            selectedWeapon = 0;
            CmdSelectWeapon();
        }
        if (Input.GetKeyDown(KeyCode.Alpha2) && transform.childCount >= 2)
        {
            selectedWeapon = 1;
            CmdSelectWeapon();
        }
        if (Input.GetKeyDown(KeyCode.Alpha3) && transform.childCount >= 3)
        {
            selectedWeapon = 2;
            CmdSelectWeapon();
        }
        if (Input.GetKeyDown(KeyCode.Alpha4) && transform.childCount >= 4)
        {
            selectedWeapon = 3;
            CmdSelectWeapon();
        }
}

[Command]
void CmdSelectWeapon()
{
    // Deactivate everyone, then just activate the one.
    for(int i = 0; i < transform.childCount; i++)
    {
        if(i != 4)
        transform.GetChild(i).gameObject.SetActive(false);
    }

    transform.GetChild(selectedWeapon).gameObject.SetActive(true);
 }
}

```

Hope it helps.
> 1 votes

---
Tags: unity, c#, multiplayer, unity-networking
---


title: Prevent Multiplayer Cheating

text:
# Question
Title: Prevent Multiplayer Cheating
I am almost complete developing a small indie-style multiplayer game. While I intend to allow people to cheat in single-player, this is obviously not acceptable in multi-player. Does anyone know of any ways to help stop the average Joe from using something like Cheat-Engine to modify parts of the game? I currently plan to have the client upload a MD5 hash of each setting file the game uses (stored as an XML) to the game server for verification every few seconds, but is there anything I can do to stop things like memory-editors, etc?

# Answer
> 10 votes
If you are worried about locally modified code, then how can you be sure that someone hasn't simply modified your notification code to send a static list of MD5 hashes, the same ones you expect? In fact, you don't even need code modification to do this, you just need a fairly basic proxy (assuming no SSL, but even that could be faked with a bit more effort).

The only way to do what you want is to have a server and simply not trust the client at all. All calculations should be handled on the server and all actions verified as being at least somewhat possible. For instance, don't allow the client to say that they want to move to one side of the map when you know they were on the other side a moment ago. Without a server in the middle doing everything that is vital to the game, it is **impossible** to not have cheating, because someone smart will *always* find a way around anything you can build into the client. Even with one, it is still possible if you don't think through all the different ways to manipulate the situation slightly. For instance, the movement validation I mentioned before: If you do a simple point to point calculation people may still be able to teleport through walls.

So the question is, how average is 'average Joe'? You've already mentioned code editing and memory editors. That's above what I would personally consider the average level, and if you do want to be worried about that level then a separate trusted server which does all the heavy lifting is required and the client will boil down to essentially just being display and input devices.

# Answer
> 13 votes
> The client is in the hands of the enemy. (The Laws of Online World Design)

Really, the only way to beat most cheats is to have the client be a "thin client", that is: To only act as an input and output device, and to never give it more information than it precisely needs.

This won't stop automation and this won't stop passive information gathering and analysis, but you can design your game such that these don't have a significant impact.

This won't stop people hacking each other via malformed messages relied by the server - your client needs to guard against messages from the server same as you would guard your web sites from SQL injection attacks.

Since you also want to use the same client for the single-player game, a solution would be to run a local server in a separate process/thread and treat it internally as a client/server setting. The "cheats" would then work on the server side. Minecraft does something similar, though it's by no means the first game to split the game engine from its interface in such a way.

Suggested reading:

# Answer
> 2 votes
In a basic multiplayer game cheating in the kind of Cheat-Engine simply won't work. The clients are only sending the data and the actions you designed it do to. Usually thats not much more than what the player "did", e.g. in what direction he is running, if he is shooting and so on. So the changes he does to the memory will only affect his own game, but the other players will see no change, a so called desync. Most games detect desyncs like that and remove the desynced player from the game.

Now there are also other ways of cheating, but those are all about how your game is designed.

To protect from the easiest hacks, which is faking network messages, the server should check those package for their sanity. "That guy just jumped 5 screens? Thats impossible, deny package." (Note that you can also go the fully synchronized route -that means everything is synchronized and only "What buttons did the player press."-kind of messages are send- which makes faking network messages useless by design.)

The last way of cheating in multiplayer are visiblity hacks, thats modifying the client so that it shows data to the player which he doesn't know. Examples for this are not showing the fog of war, being able to look through walls, displaying a minimap or other things. These are impossible to prevent.

# Answer
> 1 votes
To prevent basic Cheat Engine hacks that manipulate the values of your variables then you have to hide those values. Typically Cheat Engine is used to identify the memory location of interesting variables (say the amount of gold or life or upgrade level of an ability) by doing a search for the known value of said variable, play more of the game and cause the value to change, then Cheat Engine would do a new search from the outcome of the previous search for the new value. This allows the cheater to zoom in on the memory location of the value, now they can change the value of that memory location using Cheat Engine.

For example, I have 245 GOLD... with Cheat Engine I do a search for 245 and find many memory locations. Then I play some more and bring my gold up to 314, I then search the previous search output for the value 314 and easily find the memory location for where GOLD is stored.

The way to prevent this is to never have the real value stored in a memory location. For example, I store the value in an object that has to calculate the real value on demand when it is required. So lets say that the player has 245 GOLD. If they do a search for a memory location with the value 245, they might find many but none of them will be the memory location of where the gold value is actually stored, that is because you do not store the value 245 for gold. When the game needs to know how much gold, it will ask the object that holds the value for it, which will calculate it on demand.

So the question now is: How exactly do you store a value in a way that does not reveal it? This gets a little tricky and ugly and I'm sure there are many ways it can be done. What I like to do is store a boolean array (or byte array). The length of the array can be anything, but let's say it is 13. Then you have a counter that represents how many times does 13 go into that actual value. So if we want to represent 245 then the counter would have a value of 18. Now the array would have all booleans set to true for the remainder of 245 / 13... basically the modulus. In this case that's 11, so the first 11 booleans in the array would be set to true, the rest set to false. To retrieve the value all you need to do is multiply the counter by the array length, then add 1 for each boolean set to true (stopping at the first false). Now the number 245 would never be stored anywhere and would be hard to find the memory location that would need to be manipulated to alter the gold amount. You might want to set the array length to different sizes (maybe randomly pick a number between some reasonable range) when this object is created.

EDIT: This is useful for multiplayer and single player. There is cheating that can also be done in multiplayer, where the values in the packets can get altered. This would require different techniques to prevent, like signing each packet.

---
Tags: networking, multiplayer, security, anti-cheat
---


# Question
Title: Unity UNET, problems spawning and then destroying that instantiated prefab
I am very new to networking, and have ran into an issue, read below.

I have multiplayer system setup, where players can spawn, they can pick up weapons and drop them, there is an object representing a pickup with network identity component attached and local player authority enable, the player can come up to it and press "E", which will destroy the pickup object, then the player can press I to to "drop" that weapon, which instantiates it infront of the player, now this is what should happen, and it works on single player, but when there's 2 players, for second player(client only) it doesn't work as it should.

I have 1 script weapon manager and another small, Pickup (on pickup object child with trigger).

Below is the code and according description of my attempt so far:

***Below is PickUp script (on 1st child of pickup object with trigger enabled)***

```
private void OnTriggerStay(Collider other)
{
    if (other.CompareTag("Player"))
    {
        if (Input.GetKeyDown(KeyCode.E))
        {
            //Call pickup function on player, passing the weapon id and parent gameobject
            other.GetComponent<WeaponManager>().PickUpWeapon(weaponID, transform.parent.gameObject);
        }
    }
}

```

***Below is WeaponManager script (on player)***

```
public void PickUpWeapon(int id, GameObject go)
{
    CmdDestroyObj(go);

    //... (other code, not relevent)
}

[Command]
void CmdDestroyObj(GameObject obj)
{
    RpcDestroyObj(obj);
}

[ClientRpc]
void RpcDestroyObj(GameObject obj)
{
    // HERE obj is NULL   (!!ERROR!!)
    Destroy(obj);
}

```

Above in RpcDestroyObj() obj is null

```
void Update(){
  if(isLocalPlayer)
  {
    if (Input.GetKeyDown(KeyCode.I))
    {
       if (slots[currentActiveSlot] != null)
       {
          CmdDropWeapon();
       }
    }
  }
}

```

Then here's CmdDropWeapon() function:

```
[Command]
void CmdDropWeapon()
{
    RpcDropWeapon();
}

```

Here's RpcDropWeapon() function:

```
[ClientRpc]
void RpcDropWeapon()
{
    GameObject _drop = (GameObject)Instantiate(drops[currentGun.GetComponent<WeaponStats>().id], transform.position + transform.forward, Quaternion.identity);
    _drop.GetComponent<Rigidbody>().AddForce(transform.forward * 25000f * Time.deltaTime);

    CmdDestroyWeaponHeld() //Destroy currently held weapon (don't pay attention, not relevent to current problem

    currentGun = null;

    if (isLocalPlayer)
    {
        GetComponent<PlayerSetup>().playerUIInstance.GetComponent<PlayerUI>().SetInventorySlotFill(currentActiveSlot, -1);
        emptyHanded = true;
    }
}

```

On single player (so host & client), everything works besides destroying the pickup prefab that is Instantiated.

On multiplayer, second player (client only), can pick up and drop weapons as well as the originally spawned weapon is destroyed, but destroying the newly instantiated (so after player drops it) pickup object doesn't work.

(In the console there are no errors when UnityEditor is the Lan host/server, when 2 players are playing and I try picking up and dropping weapons several times from client side)

Why is this not working? I would appreciate any help/assistance in getting this right and sync over network for all players.

My guess is that, rpc function Instantiates the drop prefab but it's kind of different on all clients, so the server or another client doesn't have exactly the same object in the scene which means it will not find it and return null.

Let me know if you need any additional information.

Thanks a lot in advance!

# Answer
On UNET, when you Instantiate and Destroy Objects (or deactivate, if such the case), you must make use of **Spawn** and **Unspawn** respectively, so those objects appear / dissapear on the other clients.

You still need to make use of Instantiate and Destroy, but you must add hat extra step. The given examples are from a tiny UNET test I've made:

```
[Command]
private void CmdShoot()
{
    shoot.Cast();
    shoot.currentBullet.GetComponent<Bullet>().scoreRetrieved = OnScoreMade;
    NetworkServer.Spawn(shoot.currentBullet);
}

public void OnDie()
{
    playerGUI.gameObject.SetActive(false);
    NetworkServer.UnSpawn(playerGUI.gameObject);
}

```

Hope it helps.
> 1 votes

---
Tags: unity, networking, multiplayer, unity-networking, unet
---


# Question
Title: How do I find a component, deferring to the children or parent if there is none?
I'm trying to create a function in C# in Unity that will take a GameObject and a Component, and return an attached Component from the base, child, or parent elements.

If the target GameObject does not contain the requested Component, I wish to look to any children. If there are no children, or the children do not contain the requested Component, I wish to look to the parent.

How do I find a component, deferring to the the children or parent if there is none?

# Answer
> 1 votes
I just thought of making an extension method, as you proposed. But took consideration of the priority, I didn't know about **GetComponentInParent**, but it does internally what I am suggesting here, which is looking recursively upwards, just in case you wanted to know how that method works.

What you could take from here is passing an enumerator value indicating the desired priority, since maybe you want to first look for children, then for parents, or viceversa.

```
public enum SearchPriority
{
    Parents,
    Children
}

public static class TransformExtensions
{
    public static T GetComponentsDepthSearch<T>(this UnityEngine.Component _object SearchPriority _priority = SearchPriority.Children) where T : UnityEngine.Component
    {
        T component = _object.GetComponent<T>();
        if(component != null) return component;
        else
        {
            switch(_priority)
            {
                case SearchPriority.Parents:
                {
                    Transform current = _object.transform.parent;

                    while(current != null)
                    {
                        component = current.GetComponent<T>();
                        if(component != null) return component;
                        else current = current.parent;
                    }
                }
                break;

                case SearchPriority.Children:
                {
                    foreach(Transform child in _object.transform)
                    {
                        component = child.GetComponent<T>();
                        if(component != null) return component;
                    }
                }
                break;
            }
        }

        return component;
    }
}

```

Here I am using the keyword **this** so the method is extended (also, since a Component extends the method, any component can access that method), and also constrains, so the expected value is from UnityEngine's **Component**.

**NOTE:** If you wanted to get a component implementing a certain interface, passing that interface type, maybe the constrain would be good to avoid.

Hope it adds something more to your solution.

# Answer
> 0 votes
I have created said functionality with the following static method:

```
public static T GetCombatComponent<T>(GameObject go)
{
    T _ret;
    _ret = go.GetComponent<T>();

    if (_ret == null)
    {
        _ret = go.GetComponentInChildren<T>();
    }

    if (_ret == null)
    {
        _ret = go.GetComponentInParent<T>();
    }

    return _ret;
}

```

This appears to work, and can be called as follows:

```
DamageListener _dl = CombatMethods.GetCombatComponent<DamageListener>(c.gameObject);

```

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


# Question
Title: How do I keep a PHP server running forever?
I'm making a web game RTS, it's mostly create units, manage resources, attack with army, and level up factories. I have created the basics of the game using Javascript, PHP, and MySQL databases. I use the database to store player credentials and stats, and PHP as a server-side logic (like retrieve the right player and attack with X units). On the client side I use HTML/CSS and javascript.

---

My problem is that I need to keep adding resources based on the factories level (ex. 10 gold every min, when mine-factory = lvl.1). The only answers that I have found, is to modify the PHP file to run an infinite loop and keep connecting to the database to add those resources 24/7. I think the server also needs to handle attack travel (when units arrive at the enemy castle and the fight is over) and some other logic, but I don't have physical access to the server, and keep connecting to the database to add resources doesn't seem a good idea. I'm willing to make a server using other languages, or use other way to store data that keeps changing, so I can avoid multiple connections to the database. If you know a better way to do it, or something that can put me on tracks I will appreciate it.

# Answer
> 8 votes
One way to do this is not to change the actual values in the database in realtime. When the player logs on, you see how long it's been, and how much stuff he should have if he were earning during the time he was logged off, then update the value accordingly.

One benefit of this is that if a player never logs on again, you're not spending server time and resources updating his information.

If these values are needed at times when the user is logged off (say when he gets attacked) you just check the time since it was last updated, and add the accumulated value for that time frame.

# Answer
> 1 votes
I think you are facing the wrong direction, if you want to build a RTS you have to build a serverside application that handle the game's processes and a clientside app to be shown to the users.

If you have a good PHP level maybe you should read about sockets and websockets, that would make it really easy, i've been building a MORTS based on websockets nodejs/javascript using socket.io, you can have a peek here, it's not even finished, but it could give you an idea.

The idea is that your server is running constantly and the players connect to it when they log in, so the information is updated in realtime.

Of course, you could build your own services and a daemon that updates the game status every 0.3/1/2/5/10 secs but IMHO that's a waste of time.

About your "hosting services doesnt provide....", there are lot of hosting services that provides you with node.js or lets you run daemons, even shell access.

# Answer
> 0 votes
Just like @Almo's answer, you only need to calculate the resources once someone needs to know those resources, and not incrementally. For instance, if I gain 5 coin every second that I have a coin factory up and running, then someone comes along to try to steal that coin, then all I need to do is calculate how many seconds have passed since it was last updated and multiply that by the coin amount to find out how much coin they have at that moment.

If you absolutely need to update every user at a certain frequency, then spawn a thread and update the users in a separate thread.

However, you also asked another question, which is how to keep the service running while you are away. I presume you are running this while connected directly to the machine over SSH(since you don't go into detail on how you are launching the process, I can only make assumptions). Doing so means that signing out of SSH will kill the process. You can look into using nohup or other forms of keeping a process alive after you sign out(screen, tmux, etc) but there are a number of security concerns there as you will be running the process under your user account, which presumably also has sudo access. Personally, I've always gone the route of setting up a daemon, complete with limited system user to restrict access to any hackers. It is a bit fiddly to get set up the first time, but once running, will run forever.

---
Tags: javascript, server, php, html, mysql
---


title: Smooth rotation for a bone?

text:
# Question
Title: Smooth rotation for a bone?
I'm trying to make my character bone "chest" rotate smoothly when face enemy and get back to his stand. Can anyone help me with this ?

```
public Transform Target;
public Vector3 Offset;

Animator anim;
Transform chest;

public float rotation_speed;
public bool aim_at_traget = false;

void Start()
{
    anim = GetComponent<Animator>();
    chest = anim.GetBoneTransform(HumanBodyBones.Chest);
}

void LateUpdate()
{
    if (aim_at_traget == true) {
    // smooth rotation to face target
    chest.LookAt(Target.transform.position);
    chest.rotation = chest.rotation * Quaternion.Euler(Offset);
    }
    else {
        // get back to you stand smoothly
    }
}

```

# Answer
> -1 votes
In LateUpdate(), I would change the code to be this:

```
if(aim_at_target == true) {
   Quaternion rot = Quaternion.LookRotation(Target.transform.position - transform.position);
   chest.rotation = Quaternion.Slerp(chest.rotation, rot, Time.deltaTime *
   YOUR_SMOOTHNESS_VALUE);
}

```

Not sure what 'Quaternion.Euler(Offset)' is exactly but you probably can just multiply it in the second parameter of Quaternion.Slerp().

I did not test this, so may have a small mistake, I'm just giving you an idea to proceed and make it a smooth rotation.

---
Tags: unity, bones
---


# Question
Title: How do I get a delay in motion to happen? (Unity)
I want the cockpits rotation to lag behind that of the cameras, so I wrote this code:

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

public class Delay : MonoBehaviour {
    public Transform BodyRot;
    public Transform CurrentRot;
    public Vector3 changeInRot;
    public float divideRot;
    Vector3 BodyTarget;
    Vector3 CurrentInitialRot;

    // Update is called once per frame
    void Update () {
        Vector3 BodyTarget = BodyRot.rotation.eulerAngles;

        Vector3 CurrentInitialRot = CurrentRot.rotation.eulerAngles;

        changeInRot = BodyTarget -= CurrentInitialRot;

        if(CurrentInitialRot != BodyTarget)
        {
            RotateFinal();
        }

    }

    void RotateFinal()
    {
        CurrentInitialRot += changeInRot / divideRot;
        transform.rotation = Quaternion.Euler(CurrentInitialRot);
    }
}

```

But it glitches out frequently. (DivideRot is how many times to divide the distance between the target and current position, so that it takes time to rotate)

# Answer
> 2 votes
Don’t rely on `eulerAngles` for animating rotation. Use Quaternion.RotateTowards instead. Your divideRot also does not take frame rate into account, which can cause jittery animation.

```
transform.rotation = Quaternion.RotateTowards(transform.rotation, BodyRot.rotation, someSpeed * Time.deltaTime);

```

Where `someSpeed` is the speed you want to rotate in degrees per second. So try starting with 360 and adjust up or down from there.

---
Tags: unity, c#, rotation, transformation
---


# Question
Title: Patterns on preserving players progress across all player's devices
I'm writing cross platform game that is requested to store player progress across all their devices. I'm not talking about implementation details, but overall picture;

What are the patterns for preserving player progress in the least intrusive/distruptive way?

* Logging in requires players to make account or share their facebook/gmail address; It is strong entry-obstacle when someone wants "just to try the thing up"
* I can make account for player *after* they played a bit... This way, the user already tried the game and if he like to have his progress saved, they can make an account now. If not - the progress will be saved only locally
* I can experiment with some information taken directly from device (when playing from mobile, for example); I believe I can easily access their gmail on Android, and use it for account merging later on
* I can give them codes that unlock their progress. They can type them on different machines
* They can manually move save file; I don't need to keep it online
* They can move save file via cloud provider (like Dropbox/Skybox/GoogleDrive)
* Anything else...?

# Answer
On each platform, keep the save game stored in a cloud storage system keyed to an id specific to that user (even before they’ve explicitly asked to save it in the cloud). For example, their Google Play player id on Android, or a guid that you generate and store in their iCloud account for iOS. Using their gmail account is a nonstarter if they don’t have a gmail address. They can then move across devices on the same platform, or delete and reinstall without needing a separate login that way.

The cloud storage solution should allow multiple identity providers for a single account (eg. Google Play id vs iCloud id, but only one of each type). I’ve used Amazon Cognito for this purpose. Then, when the user moves cross-platform, they can choose to link accounts (possibly resolving conflicts at this time). How they link the accounts can be as simple as a temporary id generated on one device and displayed on the screen that you then enter on the other, with a server component that controls the connection, or even a QR code that the other device can scan (although that would require integrating a QR code reader into your app for the best integration, and only works with mobile devices).

Note that throughout this whole process they’ve never needed to explicitly log in anywhere in your app. You *could* also allow logging in via email, or Facebook, or what have you. This allows them to move across platforms without needing both devices present. I would be remiss if I didn’t suggest still using a third-party service for logging in. You don’t want to get into the business of storing passwords.
> 4 votes

---
Tags: game-design, cross-platform, progression
---


title: Making read from and write to databases

text:
# Question
Title: Making read from and write to databases
I want to make a few simple databases for a sports game using Unity2D(C#).

One is a read-only google sheet where it takes the players from the pool and adds them into the game at the start.

Another one is a read and write database where all 30 team's players will be saved as well as current stats( a lot of numbers), I don't know if i should make this online or local saves. I want to keep the cost at a minimal.

Generally new to making databases, can someone point me in the right direction?

# Answer
> 1 votes
From past experience, I would say the easiest database system to manage would be SQLite. If you want to retain the data from your Google Sheet, you can convert them to a SQLite database with this extension for Chrome: https://chrome.google.com/webstore/detail/convert-google-sheets-to/dhddhidmheohikpdhlhoefjkihdhngdh

You could make both into SQLite databases and then reference them from Unity. There are plently of tutorials out there to help you do this. To get started, use this one: https://answers.unity.com/questions/743400/database-sqlite-setup-for-unity.html

If you want the database to be server-side, it wouldn't be difficult to use Web-Sockets to query and add to the database. A node-js server is probably the best way to go about this. Hope this has answered your question.

---
Tags: unity, networking, databases
---


# Question
Title: how do I create a delay or cooldown timer?
I want to know if I am in the right tracks in building a function that gives you 2 secs of rest before you can attack again

```
int attackRate = 2000;
int timeElapse = 0
public void cooldown() {
      if (timeElapse < attackRate) {
          // do somthing here
          timeElapse++;
        } else {
           timeElapse = 0
      }

```

when creating this it doesnt seem to work. am i missing something?

# Answer
> 2 votes
No, this has to be called 2000 times to fire. That's way too much. Let's say you call this only once per frame and you run the game at 60 fps. That means this needs around 33.3 seconds to allow the player to attack again. It would be a lot better if you used timestamps:

```
long lastAttack = 0;
long cooldownTime = 2000; // 2000 milliseconds

public void cooldown() {
    long time = System.currentTimeMillis();
    if (time > lastAttack + coolDownTime) {
        // Do something
        lastAttack = time;
    }
}

```

---
Tags: java
---


# Question
Title: Is it a good idea and a logic to create adventure game with one scene?
I mean instead messing with loading scenes and passing variables between the scenes to make one scene and using in the hierarchy empty game objects for each part in the game for example empty game object name main menu and all the childs of it will be main menu objects.

Or instead making a new scene to make one empty gameobject and all it's childs will be like scenes.

# Answer
If it's a way that you like to work, then go for it. You don't need our permission to give it a try. ;)

One note if you're working in a team though: coordinating work between multiple people on a single scene can be challenging. If you're using version control, scenes are usually set up for exclusive checkout, since merging changes can get tricky. That means one person working on a given scene can block other folks who need to make edits there.

(It can get hairy enough that I know one Unity game studio used to assign physical totem objects to each of their scene files: you weren't allowed to work on a particular scene unless you had the totem at your desk)

Splitting your game into multiple scenes can make this collaboration a little easier, but other workflows (like breaking the scene contents up into multiple independent prefabs) can help with this.
> 1 votes

# Answer
It's a tricky question because all of it depends on the project. But there is one thing that should be considered.

The DATA.

Scene loading allows you to free your RAM memory from objects that are not active. In other words, if you have all of the objects on 1 scene, all of them will be loaded into RAM.

If you consider that and you see that you can't allow your game to take a lot of RAM memory, for example, 4GB. Then you would need to unload data/destroy objects and save their state anyway.

Usually while making the game the main factor between choosing to use multiple scenes or 1 scene depends on the type of the gameplay.

1. If you want it to be like a lot of AAA games that don't have these load screens and they load, for example, terrain in chunks - then you shouldn't consider using multiple scenes. But instead make your own loading methods.
2. This one is quite the opposite. If your gameplay can be interrupted and it's based on the chunks of story/levels... you can say for sure that you can use multiple scenes to make your life easier.

P.S. Clarification: many AAA games use 2 option as well. I didn't mean that AAA game should use option 1 always. Examples can be taken from many RTS games.
> 1 votes

---
Tags: unity
---


# Question
Title: Best way to get elapsed time in miliseconds in windows
I'm trying to do it using two FILETIMEs, casting them to ULONGLONGs, substracting the ULONGLONGs, and dividing the result by 10000. But it's pretty slow, and I want to know if there is a better way to do it.I use c++ with visual studio 2008 express edition. This is what I'm using:

```
FILETIME filetime,filetime2;
GetSystemTimeAsFileTime(&filetime);
Sleep(100);
GetSystemTimeAsFileTime(&filetime2);
ULONGLONG time1,time2;
time1 = (((ULONGLONG) filetime.dwHighDateTime) << 32) + filetime.dwLowDateTime;
time2 = (((ULONGLONG) filetime2.dwHighDateTime) << 32) + filetime2.dwLowDateTime;
printf("ELAPSED TIME IN MS:%d",(int)((time2-time1)/10000));

```

# Answer
> 13 votes
Use QueryPerformanceCounter.

```
long long milliseconds_now() {
    static LARGE_INTEGER s_frequency;
    static BOOL s_use_qpc = QueryPerformanceFrequency(&s_frequency);
    if (s_use_qpc) {
        LARGE_INTEGER now;
        QueryPerformanceCounter(&now);
        return (1000LL * now.QuadPart) / s_frequency.QuadPart;
    } else {
        return GetTickCount();
    }
}

// Somewhere else...
    // ...
    long long start = milliseconds_now();
    // ....
    long long elapsed = milliseconds_now() - start;

```

# Answer
> 7 votes
Generally timeGetTime() is best for timing game logic - GetTickCount isn't quite high enough resolution, and QPC & RDTSC are a lot more trouble than they are worth for that purpose.

For profiling on the other hand, either RDTSC or QPC can be quite worthwhile. I prefer RDTSC over QPC, though microsoft recommends QPC.

The four common time functions I use on win32:

GetTickCount() returns the current time in milliseconds relative to some arbitrary zero (usually, though not always system boot time), as a 32 bit integer (so it wraps every 49 days or so). It is usually the fastest method to measure a time. Unfortunately it is low resolution - typically it only updates 64 times per second. Contrary to popular rumor, calling timeBeginPeriod(1) will not increase its resolution on any system I've tested that on. There is also a 64 bit variant if you're worried about it wrapping.

timeGetTime() returns the current time in milliseconds relative to some arbitrary zero, as a 32 bit value (so it wraps after 49 days or so). It's not as fast as GetTickCount, but still pretty reasonable. It can be accurate to a single millisecond, though that may require calling timeBeginPeriod(1) first. Using timeGetTime requires linking against winmm.lib and including Mmsystem.h.

QueryPerformanceCounter() returns the current time in arbitrary units as a 64 bit integer. You can figure out what the units are by calling QueryPerformanceFrequency(), and the units will not change (absent a reboot). The underlying implementation of this varies widely, and each implementation has its own quirks and bugs that may occur on some hardware, making this obnoxious to use in widely deployed applications. Some implementations are very slow, others are reasonable, though none are as fast as GetTickCount or even timeGetTime. Typically timing resolution is better than 1 microsecond, though not necessarily much better.

RDTSC is an x86 / x64 assembly language opcode that returns the current time in units of CPU cycles (ie as a 64 bit integer. On some compilers it can be accessed as an intrinsic (\__rdstc), on others you'll need inline asm. Its speed varies a bit between CPUs but is usually pretty reasonable - typically significantly faster than QueryPerformanceCounter but not as fast as GetTickCount. Unfortunately it has a few quirks - not as many as QueryPerformanceCounter, but still a lot more than the lower resolution time functions. It can sometimes run backwards on multicore CPUs when you switch cores due to imperfect synchronization between cores, the units are difficult to figure out, and the units can change in mid-timing due to power management changing the rate of the CPU clock.

Note that each of these four methods can drift relative to the other three - there is no clear authoritative flow of time.

# Answer
> 3 votes
To answer your question : there is no "best" solution to measure time. Every method has its own advantages/disadvantages. It all depends of your needs.

Here is several questions you should ask yourself before choosing one solution :

* **timer resolution**. Do you really need a precise timer (\< 1ms) or can you live with something less precise (eg : 10ms precision) ?
* **cpu cost**. some methods will require more cpu than some others. generally more precise timers require more cpu. also, calling some methods can have consequences for the other applications (eg : calling `timeBeginPeriod(1)` in win32 stress the os and reduce laptop battery life)
* **works with SMP**. some methods use specific CPU data (eg: number of cycles elapsed) and can have some problems in multiprocessor environments.
* **works with CPU that have power saving feature.** Some cpu have ability to change frequency over the time, which can cause some trouble to some timing methods.

For the example you give, I would use a combination of `QueryPerformanceCounter() / QueryPerformanceFrequency()`.

Also please note that in the example you give `sleep(100)` can actually wait more than 100ms. So even with very precise timer it can returns some results other than 100ms.

# Answer
> 0 votes
I just did some benchmarks, and there is pretty much no good reason to use timeGetTime anymore. QueryPerformanceCounter is very slightly faster, and much more precise.

Then there's GetTickCount, which is nearly instantaneous, since all it does is read back some value that the OS changes during process scheduling. The value stays the same for over 15ms at a time, and is not recommended for anything besides very coarse timing.

# Answer
> -1 votes
Take a look at the **GetTickCount()** function it's return value is the number of milliseconds that have elapsed since the system was started.

```
unsigned int Last = 0;
unsigned int Now = 0;
Last = GetTickCount();
//...Run your functions..
Now = GetTickCount();
printf("Elapsed Time in Milliseconds: %i",(Now-Last));

```

---
Tags: c++, windows
---


# Question
Title: How to find and manipulate a line on a mesh?
In Unity I currently have a script that allows me to "grab" a vertex, move it, and then update the mesh accordingly. How would I grab a line (which is basically grabbing two vertices I think) and move it?

I have read the manual (the scripting reference on Unity's site) but I can't really seem to figure out how to go about doing it. I got a lot of help with the initial script that lets me grab and move a vertex but I, unfortunately, am in need of guidance on how to extend its functionality to do what I described above.

For reference here are how things currently are working. Linked it because it says my gif is too big. Below is the functionality I'd like to add (hover over for text for further explanation).

So how would I go about doing this? Also for the sake of keeping my project stable, I'm using Unity 5.3.2f1 but converting new to old code shouldn't be that big of a deal (or so I hope). Also I'mn doing this all at runtime.

# Answer
Well, this might not be the cleverest solution to your problem, but it might get job done:

You have the fuctionality to grab a vertex; great. Now create a Vertex struct, that will store a Vector3, called position. You could select a vertex by pressing left-shift and the right mouse button and add all the selected vertices to a list. Then, you could say the "G" key let's you move all the selected vertices by the mouse movement you are applying to the vertex you have selected now.

Alternatively, you could use this method, where you detect the edges of a mesh, and once you have those, you can just do Edge.v1 and Edge.v2 to obtain the vertices (It's a little harder to understand though)
> 0 votes

# Answer
You might have some luck by using **RaycastHit.triangleIndex**(there's an example of how to use it in Unity Documentation) which returns indices of triangle hit with raycast. Having 3 verties that were hit you'd just have to guess which two of those three is most relevant to your click.
> 0 votes

# Answer
The high level solution I suggest will have resource on the net for each piece, I will just give the high level solution I can think of off the top of my head. Im sure there are faster versions.

1. For each line (point a and point B), you need to test the following.
2. test that the line segment (A-\>B) is firstly not parallel to ray cast.
3. Create a plane based on ray cast and the line segment, the plane can be defined by a point (point a) and 2 vectors, in this case and the perpendicular vector (cross) of line segment (a-\>b) and ray cast.
    4. Test the ray cast against the plane. this will give you a point on the plane (point c).
    5. Test that the point is in between A and B by doing a dot prod \< 0 where A-\>B dot A-\>C and B-\>A dot B-\>C \< 0

What this test does is, you need to get the point on the plane where your ray cast hits. You then test on that plane if the point is between the points on the plane that define your line segment.

The pieces of code for each test can be found on the net, but start simple, define the point on plane test, then move on to the test of between points.
> 0 votes

---
Tags: unity, c#, 3d-meshes, dynamic-mesh
---


# Question
Title: When is transform width in code not equal to the transform width in inspector?
I've come across a strange case in Unity's UI where the width of a RectTransform isn't the same as what is being reported. I have a transform which is 50 by 50 with no scaling, it is a root object of the canvas yet when I use the information that I get from the transform in code to draw from the bottom left edge of the transform to the top right it doesn't reach all the way!

```
Gizmos.color = Color.red;
Vector2 pos = new Vector2(transform.position.x, transform.position.y);
Gizmos.DrawLine(pos - transform.sizeDelta, pos + transform.sizeDelta);

Vector3[] corners = new Vector3[4];
transform.GetWorldCorners(corners);

Gizmos.color = Color.magenta;
Gizmos.DrawLine(corners[3], corners[0]);
Gizmos.DrawLine(corners[0], corners[1]);
Gizmos.DrawLine(corners[1], corners[2]);
Gizmos.DrawLine(corners[2], corners[3]);

```

The first section should draw a line from the bottom left to the top right according to what the transform reports are the width and height however they don't reach across the entire transform. Using `GetWorldCorners` the actual corners can be found and drawn around, with that data you can extract that **the actual width is 60** (150.2 - 30.2 = 120 / 2 = 60)!

Why? Is this a bug or an I missing something obvious here?

# Answer
> 1 votes
This is because RectTransform.sizedelta only query the width and height values with no scaling applyed. You most likely have scaling from your canvas or a parent game object.  Tested in Unity 5.6.1f1

---
Tags: unity, gui, debugging
---


# Question
Title: What are valid ranges of space dimensions used in OpenGL?
I want to know what the valid ranges of all the spaces in OpenGL are.

Specifically:
Maximum and Minimum Clip space X, Y, and Z (`gl_Position`)
Maximum and Minimum `gl_FragCoord` X, Y, and Z
Maximum and Minimum `gl_FragDepth` value

# Answer
> 1 votes
There's no real limit to any of these. Of course floats have maximum values (I think around 10^308), but if you have problems with that, then reconsider what you're doing.

If the depth falls out of the specified range by `glDepthRange` (or \[0,1\] by default), then it will get clipped due to depth buffer issues, but it can have any value.

---
Tags: opengl, glsl
---


# Question
Title: Difference between Unity's Camera.ScreenPointToRay and Camera.ScreenToWorldPoint?
What is the difference between Unity's `Camera.ScreenPointToRay` and `Camera.ScreenToWorldPoint`. And where we can use these. I've watched some tutorial and documentation but I didn't get a clear understanding.

# Answer
> 2 votes
ScreenPointToRay returns a ray, basically something pointing in the direction of the mouse from the location of the camera.

ScreenToWorldPoint point actually returns a 3d position under the mouse.

---
Tags: unity, unityscript
---


# Question
Title: How do I determine the slope of a curve?
I am making a 2D game where the character rides on the curve of a graph. I need to find out whether the player is going uphill or downhill and calculate speed accordingly.

The problem is that I am not sure how to determine the slope of the curve on the point that the character is at.

Here is an example of what some of the curves look like:

# Answer
Since you use a quadratic Bezier curve to interpolate between threee consecutive points, you can simply use the derivative of the Bezier curve to find the tangent to the curve at a point.

The derivative of the quadratic Bezier curve interpolating between the points `p0`, `p1` and `p2` is

```
B'(t) = 2(1 - t)(p1 - p0) + 2t(p2 - p1)

```

Simply plug in the value of `t` for the point at which the slope is to be calculated to get a vector `tangent` in direction of the tangent. The slope of the curve at that point is `tangent.y / tangent.x`.
> 2 votes

# Answer
Differentiate it

If your curve is based on a static formula, then just plug that into Wolfram|Alpha, find the one labelled as "Derivative" and that should give you a formula, which determines the slope of the curve at x. Plug the x position of the player in the curve's coordinate system and you get the slope. A value of 5 for instance means it goes up 5 units if you go 1 unit on the x axis.

If you can't do that, because it's procedural, then fake it. Pick a very small value (\>0.001 will do it) and get the height of the curve at the player's position, then add this small value to the x coordinate and get the height there too. Subtract the former from the latter and divide by the small value. This is a good estimate (derivation is basically this but with a distance of 0). This won't really work if you predefine the heights, since that wouldn't leave you with enough precision.
> 0 votes

---
Tags: physics, movement, physics-engine, curves, beziers
---


title: LibGDX play sound when hovering button

text:
# Question
Title: LibGDX play sound when hovering button
I'm trying to make a button that plays a sound when hovering above it with the cursor

So far I created a class which extends the scene2d TextButton and I'm adding a FocusListener. The problem is that the sound is played a lot of times when hovering because this event fires not only once but as long as the button is focused.

```
//When button is hovered
this.addListener(new FocusListener() {

        public boolean handle(Event e) {

            SoundManager.play(hoverSound);

            return true;
        }
});

```

I also tried to make a variable soundPlayed which toggles if the sound is played once but this leads to the sound playing only one time because I don't know how to detect if the button is not focused anymore so i can reset the variable.

Thanks for the help.

# Answer
I'm assuming you want to play the sound only once during the whole time of the hover.

Since SoundManager does not track sounds it plays, you want to set a flag preventing from playing the sound twice. Then, you should use *enter* and *exit* functions provided by *ClickListener* to reset the flag when you go outside of the actor (your button).

```
public void enter(InputEvent event, float x, float y, int pointer, Actor fromActor)
{
    if (!soundPlayed)
    {
        SoundManager.play(hoverSound)
        soundPlayed = true;
    }
}

public void exit(InputEvent event, float x, float y, int pointer, Actor toActor)
{
    soundPlayed = false;
}

```

This way, sound will be played only once during hover, and can be replayed if mouse isn't hover anymore
> 2 votes

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


title: HLSL registers and slots

text:
# Question
Title: HLSL registers and slots
I'm learning DirectX11 and since I'm beginning to write some shader code I don't understand the difference between binding slots and HLSL registers. The shader model 5.0 introduced the keyword `register`, that I assumed is a synonym for slot but it's not.

What I know: I know that a register is 4 floats (16 bytes), and that a variable cannot straddle two registers so padding is added according to HLSL packing rules. I also know that if I compile two shaders (say, vertex and pixel shader) in from the same file the register specified are by shader usage so if I use register b0 two times everything compiles fine if resources are accessed by each shader indipendently.

but what about this:

```
cbuffer Transform : register(b0)
{
    float4x4 worldMatrix;
};

cbuffer clipPlane : register(b1)
{
    float4 clipPlane;
};

```

I bind my resources to the shader like this:

```
Game::GetInstance()->GetDeviceContext()->PSSetConstantBuffers(0, 1, &mCameraConstantBuffer);
Game::GetInstance()->GetDeviceContext()->PSSetConstantBuffers(1, 1, &mLightsConstantBuffer);

```

But if a register is 4 floats shouldn't the two resource overlap? What about sampler and shader resource registers?

Can someone provide me with a reference about the structure of these registers? MSDN documentation is really of no help sometimes.

# Answer
> 1 votes
You are confused in the meaning of the "register" keyword in HLSL. With that keyword you are only defining a binding slot for the DX11 API. It has no relation with register such as a float4 on which you can execute instructions (General Purpose Register, GPR).

So your example is perfectly valid, `register(b0)` will only say that that whole constant buffer will be bound with `PSSetConstantBuffers(0, ...)` The other constant buffer will be bound on slot 1.

They will not overlap, because they are not even necessarily nearby in memory. Binding a constant buffer (or any other resource) only moves around their "descriptors" which point to the main resource.

In DX11, you are given a fixed amount of slots that you can bind resources onto. You can bind up to 15 constant buffers, 16 samplers, ~128 textures, 8 render targets/UAVs. In Vulkan/DX12 this decision is left to the developer.

---
Tags: directx11, hlsl
---


title: Unity tutorial sync var not working

text:
# Question
Title: Unity tutorial sync var not working
I tried to make a simple miltiplayer game with the unity tutorial. The Code of the Player looks like this:

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

 public class PlayerController : NetworkBehaviour {

     public GameObject bulletPrefab;
     public Transform bulletSpawn;

     public Camera cam;

      // Update is called once per frame
     void Update () {
         if (!isLocalPlayer) {
             return;
         }

         float x = Input.GetAxis ("Horizontal") * Time.deltaTime * 150.0f;
         float z = Input.GetAxis ("Vertical") * Time.deltaTime * 3.0f;
         transform.Rotate (0, x, 0);
         transform.Translate (0, 0, z);

         if(Input.GetKeyDown(KeyCode.Space)){
             CmdFire();
         }

     }

     void Start()
     {
         cam.gameObject.SetActive(false);
         if(isLocalPlayer)
         {
             cam.gameObject.SetActive(true);
         }

     }

     [Command]
     public void CmdFire(){
         GameObject bullet = (GameObject)Instantiate (bulletPrefab, bulletSpawn.position, bulletSpawn.rotation);
         bullet.GetComponent<Rigidbody> ().velocity = bullet.transform.forward * 6.0f;

         // Spawn the bullet on the client
         NetworkServer.Spawn(bullet);

         Destroy (bullet, 2f);
     }

     public override void OnStartLocalPlayer ()
     {
         GetComponent<MeshRenderer> ().material.color = Color.blue;
     }
 }

```

The Code of the health class like this :

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

 public class Health : NetworkBehaviour {

     public const int maxHeath = 100;
     [SyncVar(hook="OnChangeHealth")] public int currentHealth  = maxHeath;

     public RectTransform healthBar;
     public RectTransform publicHealthBar;

     private int maxHealthBarSize;

     public bool destroyOnDeath;

     private NetworkStartPosition[] spawnPoints;

     void Start(){
         if (isLocalPlayer) {
             spawnPoints = FindObjectsOfType <NetworkStartPosition>();

             maxHealthBarSize = (int) healthBar.sizeDelta.x;
         }
     }

     public void TakeDamage(int amount){

         if (!isServer) {
             return;
         }

         currentHealth -= amount;

         if (currentHealth <= 0) {

             if (destroyOnDeath) {
                 Destroy (gameObject);
             }
             else {
                 currentHealth = maxHeath;
                 RpcRespawn ();
             }

         }

     }

     void OnChangeHealth(int health){
         if(isLocalPlayer)
         {
             healthBar.sizeDelta = new Vector2(((float)health / maxHeath) * maxHealthBarSize, healthBar.sizeDelta.y);
         }
     }

     [ClientRpc]
     void RpcRespawn(){
         if (isLocalPlayer) {

             Vector3 spawnPoint = Vector3.zero;
             if (spawnPoints != null && spawnPoints.Length > 0) {
                 spawnPoint = spawnPoints [ Random.Range (0, spawnPoints.Length) ].transform.position;
             }

             transform.position = spawnPoint;
          }
     }

 }

```

But the health bar is only updating on 1 client. This means : A shoots B -\> B's Healthbar updates -\> B shoots A -\> A's healthbar doesn't update.Does anyone know howw to fix the issue? (Is it unity or me?) Probably me :)

# Answer
> -1 votes
I don't fully understand the code here but it doesn't seem that you are doing anything if the player is not local...

```
void OnChangeHealth(int health){
     if(isLocalPlayer)
     {
         healthBar.sizeDelta = new Vector2(((float)health / maxHeath) * maxHealthBarSize, healthBar.sizeDelta.y);
     }
 }

```

Should you not be calling something or whatever to update the other client(s)?

---
Tags: unity, multiplayer
---


# Question
Title: Game Maker 8 high score table pixel size
How big is the high score table in Game Maker 8? I wanted to make a background image for the table but each time I do the background is either too big or too small and makes it blurry.

# Answer
I measured the width and height of the highscore window (by taking a screenshot), and found out these measurements:

* **Table with borders:** 360 x 400 pixels;
* **Table with no borders:** 366 x 429 pixels.

I tested these sizes by creating two background images, and they weren't resized at all, no glitches were visible due to resize.
> 0 votes

---
Tags: game-maker
---


# Question
Title: Access a ID3D11Texture2D in another thread
I created a `ID3D11Texture2D` texture on a thread with DirectX graphics and I passed its pointer to a worker thread. I'm assured that the creator thread will no longer reference nor use the texture. I now need the worker thread to copy the resource

```
pContext->CopyResource(..);

```

What's the correct way of doing this in the worker thread?

In other frameworks like CUDA or OpenGL I would just push/restore the creator thread's context into the worker thread, but I'm not sure if that applies in DirectX.

# Answer
> 2 votes
Methods on the DirectX 11 Device are thread-safe, but methods on the DirectX 11 DeviceContext are not.

**In other words, the application must manage the thread-safety when sharing the immediate context between threads.**

See MSDN: Introduction to Multithreading in Direct3D 11

---
Tags: directx, directx11, multithreading
---


title: Calculate polygon points from image

text:
# Question
Title: Calculate polygon points from image
I'm new to OpenGL, so please excuse my brevity and/or lack of technical knowledge of the subject.

I need some help with rendering a polygon on an OpenGL canvas (using C# w/ Tao). I understand that I will need to tessellate the polygon points so it'll draw correctly, but technicality aside, what's the best method to get usable XY points from the image below so I can draw the polygon shape?

# Answer
> 2 votes
If you want to vectorize the polygon, one way is to first find all the edges by tracing along boundaries between adjacent differing pixels, then perform a relaxation/simplification step that optimizes the resulting polygon by merging connecting segments, using something like Ramer-Douglas-Peucker

An example method, although they use a different policy for curve simplification that generates Bezier splines, is the algorithm detailed at Potrace: a polygon-based tracing algorithm. This seems to be the algorithm that Inkscape uses.

Usually, however, in games we'd render a picture such as your example plane image as a raster texture.

If you want the advantages of vectors, you could consider generating a distance field representation of the image, which allows for low-resolution raster storage of a vector texture

Improved Alpha-Tested Magnification for Vector Textures and Special Effects

---
Tags: c#, opengl
---


# Question
Title: How to save a global reference of an instantiated gameobject?
In my game, when I instantiate a particular prefab, I need to show a GUI window, then let player do some actions, finally close that window and update the caller `GameObject` with the info inserted from user.

So my question is: how to save the reference of the `GameObject` caller to update it at the end of the user action.

Consider that I call some sub functions and I don't want to pass a `GameObject` through all functions.

Is there a way to save a gameObject reference in a global variable ? I'm using a static class for that purpose.

# Answer
C# doesn't allow global variables (i.e.: variables outside classes).

The only way to mimic a global variable is to use a `static` class, as you already did.
> 3 votes

# Answer
What's wrong with passing a `GameObject` reference through these functions?

You need it at the end and the only place you can get it is the previous invoker in your chain of methods. When you instantiate the UI, pass the `GameObject` to it, store it in the UI handler class, and when do, do the update thing you need to on that saved reference.
> 0 votes

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


title: How to create a scope for a sniper

text:
# Question
Title: How to create a scope for a sniper
I am developing a first-person shooter/strategy game using the Lightweight Java Game Library, which has support for OpenGL. I would like to create a sniper which I need to magnify the screen and project an image onto the back of the scope. I have tried using gluPerspective() for zooming in and out, but it just makes the screen go black. I am thinking about using glReadPixels for grabbing pixel data from the zoomed in image, but I'm not sure what to put in field 'data'. explanation of glreadpixels here I'm also not sure how to get the data from glReadPixels and put it back onto the back of the scope.

EDIT: I'm not doing full screen zooming, I'm showing the image on the back of the scope.

Anyone know how to do this?

# Answer
There is a great tutorial (c++) on how to create a camera for opengl on:

http://www.dhpoware.com/demos/glCamera3.html

It has functionality for zooming in and out. I've used it for my implementation in LWJGL.
> 3 votes

# Answer
If you want to render the scope full-screen, just change the projection accordingly, and add the crosshair onto the picture.

If you want to render the world in the scope when the gun is being held down, you have to do the same, but render to texture this time, and then project this texture on the gun's scope.
> 1 votes

# Answer
1. Create A Framebuffer **x**
2. Draw the world except the player on it
3. Copy the Framebuffer into another buffer **y**
4. Draw the player on framebuffer **y**
5. Convert **x** to a texture then shade it on the scope in **y**
> 1 votes

---
Tags: opengl
---


# Question
Title: What settings should I set for the Sprint in the Input Manager?
This script is attached to Player object:

```
using UnityEngine;
using System.Collections;

[RequireComponent (typeof (Rigidbody))]
[RequireComponent (typeof (BoxCollider))]

public class PlayerController : MonoBehaviour {

    public float walkSpeed = 6;
    public float runSpeed = 10;
    public float strafeSpeed = 5;
    public float gravity = 20;
    public float jumpHeight = 2;
    public bool canJump = true;
    private bool isRunning = false;
    private bool isGrounded = false;

    public bool IsRunning
    {
        get { return isRunning; }
    }

    void Awake () {
        GetComponent<Rigidbody>().freezeRotation = true;
        GetComponent<Rigidbody>().useGravity = false;
    }

    void FixedUpdate () {
        // get correct speed
        float forwardAndBackSpeed = walkSpeed;

        // if running, set run speed
        if (isRunning) {
            forwardAndBackSpeed = runSpeed;
        }

        // calculate how fast it should be moving
        Vector3 targetVelocity = new Vector3(Input.GetAxis("Horizontal") * strafeSpeed, 0, Input.GetAxis("Vertical") * forwardAndBackSpeed);
        targetVelocity = transform.TransformDirection(targetVelocity);

        // apply a force that attempts to reach our target velocity
        Vector3 velocity = GetComponent<Rigidbody>().velocity;
        Vector3 velocityChange = (targetVelocity - velocity);
        velocityChange.y = 0;
        GetComponent<Rigidbody>().AddForce(velocityChange, ForceMode.VelocityChange);

        // jump
        if (canJump && isGrounded && Input.GetButton("Jump")) {
            GetComponent<Rigidbody>().velocity = new Vector3(velocity.x, Mathf.Sqrt(2 * jumpHeight * gravity), velocity.z);
            isGrounded = false;
        }

        // apply gravity
        GetComponent<Rigidbody>().AddForce(new Vector3 (0, -gravity * GetComponent<Rigidbody>().mass, 0));
    }

    void Update() {
        // check if the player is touching a surface below them
        checkGrounded();

        // check if the player is running
        if (isGrounded && Input.GetButtonDown("Sprint")) {
            isRunning = true;
        }

        // check if the player stops running
        if (Input.GetButtonUp("Sprint")) {
            isRunning = false;
        }
    }

    void checkGrounded() {
        /* ==============
         * REMEMBER
         * ==============
         * If you change the size of the prefab, you may have
         * to change the length of the ray to ensure it hits
         * the ground.
         *
         * All obstacles/walls/floors must have rigidbodies
         * attached to them. If not, Unity physics may get
         * confused and the player can jump really high
         * when in a corner between 2 walls for example.
         */
        float rayLength = 0.7f;
        RaycastHit hit;
        Ray ray = new Ray(transform.position, -transform.up);
        //Debug.DrawRay(ray.origin, ray.direction * rayLength);
        // if there is something directly below the player
        if (Physics.Raycast(ray, out hit, rayLength)) {
            isGrounded = true;
        }
    }
}
There are some parts in the script it's using "Sprint" For example:

// check if the player is running
        if (isGrounded && Input.GetButtonDown("Sprint")) {
            isRunning = true;
        }

        // check if the player stops running
        if (Input.GetButtonUp("Sprint")) {
            isRunning = false;
        }

```

But "Sprint" is not defined in the editor input: Edit \> Project Settings \> Input:

I can change the size in the Input Manager to 19 and it will duplicate the Cancel so I changed the name to Sprint. But what should be the config for the Sprint ? It's now the Cancel config. Config I mean the settings for each property.

When running the game before added the Sprint I'm getting this exception:

ArgumentException: Input Button Sprint is not setup. To change the input settings use: Edit -\> Project Settings -\> Input PlayerController.Update () (at Assets/My Scripts/Character1/PlayerController.cs:62)

My question is what settings should I set for the Sprint in the Input Manager ?

# Answer
I'm not sure you can use key combinations as input, so you may need to set up two buttons and then check for a GetButton on the shift during a GetButtonDown on the W.

Input manager configuration:

```
Sprint
  Positive Button: w
Shift
  Positive Button: left shift
  Alt Positive Button: right shift

```

That will allow either shift to be used. If you don't want that, leave the Alt Positive Button blank. Negative buttons and other alt buttons can be left blank. All the other settings should be fine.

Then your code would look something like this:

```
if (isGrounded && Input.GetButton("Shift") && Input.GetButtonDown("Sprint")) {
    isRunning = true;
}

if (Input.GetButtonUp("Shift") || Input.GetButtonUp("Sprint")) {
    isRunning = false;
}

```

Or, as @DMGregory pointed out, the code can be simplified to one line:

```
isRunning = isGrounded && Input.GetButton("Shift");

```

This has slightly different behavior, since it triggers when holding `w` first and then beginning to hold `shift`, whereas the first code example only triggers when you hold `shift` first. I don't know exactly what controls you want, but the second code example is probably better.

## Edit

It turns out I was overthinking this. You already have `W` assigned to your Vertical axis, which you are using. Just have isRunning equal the state of the shift key.

```
//Sprint
//  Positive Button: left shift
//  Alt Positive Button: right shift

isRunning = GetButton("Sprint");

```
> 1 votes

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


# Question
Title: How to render images/textures in shape/polygon form?
I'm working with SFML right now, and upon finishing the tutorials I still do not know how to give a shape a texture or image -- not just a solid color/outline.

The only thing I know can take an image is a sprite, but thats *way* to simple, as it only allows you to render rectangular images in a rectangluar way!

**What are the techniques for rendering images onto shapes, and *only* inside the shape?** It would be great if some of you could provide some resources or SFML-specific stuff!

# Answer
I don't think you can do this directly using SFML. It looks like the shape class will not support texture mapping; allegedly it is a planned feature for the next version (discussion).

Depending on the kind of visual effect you are going for -- I didn't find your description entirely clear -- you could do something like using a shape to mask a sprite, as described in this post (scroll down a ways, there's an image with the example result), or you could use OpenGL directly to render a series of texture-mapped triangles with the image mapped appropriately using texture coordinates.

Note that while sprites are rectangular in their nature, you can achieve the visual result of a non-rectangular image by including transparency (typically via the alpha channel of the image), and that may be all you need to achieve your desired visual result.
> 3 votes

# Answer
SFML has been updated since this question was originally answered and you can now add textures to shapes easily. The shape class has the `setTexture()` and `setTextureRect()` methods. `setTexture()` takes a pointer to an `sf::Texture`. See the documentation.

```
Sf::Texture texture;
if (!texture.loadFromFile("mytexture.png"))
{
    std::cerr << "failed to load";
}
sf::RectangleShape myRect{ sf::Vector2f(width, height) };
myRect.setTexture(&texture);
myRect.setTextureRect(sf::IntRect( x, y, width, height ));

```
> 3 votes

---
Tags: c++, rendering, sfml
---


# Question
Title: Building Levels... Any tips for nice 'level enclosure'? To avoid having to make un-used parts of a level map
Hi everyone I have made myself a little SWAT action FPS style game. I have the basis of the code very well set up (by my standards!) and can easily add enemies where I want that all act differently by ticking different options in them. I have set up a mission list and can complete them etc. The whole game is almost ready to build several levels with and then hopefully have anend product that resembles a real PC game.

But this is unchartered waters for me. Normally I can overlook all the rough edges as I am just learning, but I am really happy with this and want to try making it into a full game.

My problem: The edge of the level. I've made a 'training level' that is very small. Its 60mx60m gamemap . The level works fine but I have these edges where you can fall off the world. I could of course put a brick wall, or an invisible wall, but I thought I would ask you knowledgable folks here at gamedev for some advise and options.

Could I somehow dump my level on top of an image or plane of images to give illusion of being in a city? or would I need to create buildings in 3d just for background objects? (if not I can always give in for now and use a big brick wall lol)

Here's a screenshot to show what I mean. I understand this question will give rise to opinion based answers, but I'm really low on ideas so anything better than an invisible wall or a brick wall would be very welcome.

thanks for reading

# Answer
Why not let the simpletons just fall?

Eh. My more "sanitized" response would be, sometimes, it can be a whimsical choice to allow the less genre-savvy individuals fall off the map.... Not that you'd have to go that way....

Of course, if falling off a map is not a "thing" anywhere else in the game so far, then that will of course have to be prevented. That means a wall, a bounding box, a wall, ... something, to block going from Point A, to Point -Z (see what I did there?).

I do/would have my own preference in making a wall, invisible or not. But there is also psychological value in making tutorial levels feel open, not enclosed; so including some visual plane that doesn't constrain the openness.

This above even applies in 2d/tile-based games, of which I'm more familiar at developing this moment -- certain game-makers might allow adding parallaxed backgrounds for just such an effect.
> 1 votes

---
Tags: unity, level-design, levels
---


# Question
Title: How to get the previous value from string array c#(Unity)
I have this example data

> Data: P ,B ,B ,T ,P

This must be something like this

But what is happening to me is this

here's my code

```
string[,] table = new string[104, 6];
string newPreviousValue = "placeholder";
int xIndex = -1;
int yIndex = 0;
if (result.Equals(newPreviousValue) &&  yIndex < table.GetLength(1) - 1)
{
    yIndex += 1;
    table[xIndex, yIndex] = result;
}

else
{
     xIndex += 1;
     yIndex = 0;
     table[xIndex, yIndex] = result;
}

```

So you won't get confuse the `result` variable is the **data** generator. What could be missing on my condition?

I tried doing something like this

`if (result.Equals(newPreviousValue) && result.Equals(newPreviousValueTie) && yIndex < table.GetLength(1) - 1)` but what's happening here is they're all in y axis falling in line .

# Answer
> 1 votes
So you mean every tie must not move to X axis ? If that's the case you can do it something like this :

Inside of your

```
if (result.Equals(newPreviousValue) &&  yIndex < table.GetLength(1) - 1)
{
    yIndex += 1;
    table[xIndex, yIndex] = result;
}

```

You recode like this

```
if (result.Equals(newPreviousValue) &&  yIndex < table.GetLength(1) - 1)
{
     var newResult = previousValue.Contains(scoreboardWinner[2]);
     if (newResult == previousValue.Contains(scoreboardWinner[2]))
     {
           yIndex += 1;
           table[xIndex, yIndex] = result;
     }
     else
     {
         yIndex += 1;
         table[xIndex, yIndex] = result;
     }
}

```

Maybe that will do.

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


# Question
Title: How do I let game maker know that recieved json data is an array?
In python I created an array called `lobbyList = ["Awesome","Funny","Epic"]`

I sent this array to Game maker studio 1.4 using JSON, I made a variable called RecievedData and made the following script

```
var name = argument0;
var data = argument1;

RecievedData = json_decode(data);
show_message(RecievedData); //Let's me know data has been recieved

```

I can recieve data fine, but when I `show_message(RecievedData)` it returns 4, when I do `show_message(data)` it gives me a string of `["Awesome","Funny","Epic"]`

So how do I tell game maker that this is an array and not just a number or string? I want to draw this array coming from the server into a lobby list but for the life of me, I can't figure out how say this is an array.

# Answer
> 1 votes
This Fixed my problem, my dad helped me after reading a lot about ds maps and lists in the manual.

```
var name = argument0;
var data = argument1;

show_message(data);

resultMap = json_decode(data);
global.lobbyList = ds_map_find_value(resultMap,"default");

listLength = ds_list_size(global.lobbyList);
    show_message(listLength);

```

---
Tags: networking, python, game-maker
---


# Question
Title: Is it possible to have two trigger zones around the same GameObject in unity?
I have created a trigger zone to make sure that only only gameobject passes through it at a time. The moment the gameobject1 entered the trigger zone, it is given a particular tag but I am not how to stop other gameobjects from entering the zone. Is it possible to have two trigger colliders attached to a same object like an outer and inner trigger such that only one gameobject is allowed to pass through the inner one while all other gameobjects wait at the outer one.

# Answer
> 2 votes
If you need to have multiple trigger zones around your GameObject, you can add empty GameObjects as children of that GameObject and add the colliders to those children. You can then assign different tags to those child objects to be able to differentiate between outer and inner trigger zones in your code.

# Answer
> 1 votes
You can try updating the tag of your trigger object and in the other gameobjects OnTriggerEnter set the move speed to 0 and the position to the position of your trigger.

# Answer
> 1 votes
I would have made this trigger a solid collider and edit the Layer Collision Matrix (found in Edit\>Project Settings\>Physics) to make it not interact with gameObject1, given a special layer.

More info on Layer Collision Matrix: https://docs.unity3d.com/Manual/LayerBasedCollision.html

---
Tags: unity, gameobject, collider
---


# Question
Title: Simulate wind affecting a boat using a 2D physics engine like Box2D or SpriteKit?
I'm looking for a way to simulate the forces created by wind and how it affects a boat.

In a nutshell: if wind hits a boat (sailing yacht), the bow is aligning with the wind and if the wind is strong enough, the boat will then slowly start to move.

I am not looking for a correct simulation of sails or alike. Just wind as it would affect a boat during maneuvers at slow speed.

Here's what I have tried:

* Make the boat just one body and apply a force: this does not take into account the heavier stern versus the lighter bow.
* Make the stern a heavy body and the bow a lighter one and connect them with a fixed joint: this will make the boat rotate if the same force is applied to both bodies but ignores the fact that once the boat is aligned with the wind, the force should be reduced.
* Create many (thousands) of very small objects with little mass and apply a force to them, simulating the wind "particles" and let them hit the boat: this kills performance on slower devices.

Maybe I am missing a very simple solution that would work good enough?

# Answer
I think you can make this very simple by using the difference in angle between the boat and the wind direction.

Lets say the wind is going from the west (left) to the east (right) we can represent this as a vector(1,0)

```
Vector2 wind = Vector2(1,0);

```

Now, our boat direction can also be represented as a vector. lets say its facing north(up) that would equate to vector(0,1)

```
Vector2 boatDirection = Vector2(0,1);

```

We can now use the Vector2 method angle to get the difference between these 2 angles in a range -180 to 180.

```
float angleDifference = wind.angle(boat);

```

If we now turn this to an absolute value(0 to 180) and then - 90 this will give us a range of -90 to 90. 0 being sideways to the boat and -90 and 90 being full on front/back. We can then further reduce this to a 0-1 range by dividing by 90.

```
float appliedWindStrength = (Math.abs(Math.abs(angleDifference)-90) / 90f);

```

Now we have the strength multiplier we can use to modify the forces applied on the boat.

Using this 0-1 range we can then couple it with the smaller lighter stern and larger heavier aft.

```
stern.applyForce(x*appliedWindStrength);
aft.applyForce(x*appliedWindStrength);

```

I haven't had a chance to test this myself yet. Will update when I get the time.
> 1 votes

---
Tags: physics, box2d, spritekit
---


# Question
Title: Exporting a simple mesh from Blender for reading in Assimp
I'm trying to create some simple assets for using in my rendering engine. What I'm trying to do is to generate simple low poly models and then importing them into my application using Assimp. I can successfully import models I find on the web so everything works fine application-wise. But since I'm a total noob at Blender (I managed to learn some interface basics through tutorials) I just seem able to export a model with geometry information (vertex positions) and that's it. My models don't have normals or uv-cordinates, and no textures whatsoever. What I'm asking is a simple workflow to create and export a very simple mesh to a obj or collada format that I can read into my code.

# Answer
> 1 votes
This is more of a Blender than a gamedev question. OBJ supports both normals and UV maps, which are exported by default in the OBJ exporter.

Blender will auto-calculate the normals. UV maps are edited by Unwrapping the Mesh.

For example, from an empty Scene, I can:

1) Add \[Shift-A\] -\> Mesh -\> Monkey
2) Edit Mode \[Tab\]
3) Menu \[Space\] -\> type "Unwrap", \[Enter\]
4) File -\> Export -\> OBJ, (check "only selected item")

and I get a monkey.obj with UVs and Normals

---
Tags: models, blender, uv-mapping, assimp, import
---


# Question
Title: Python 3: How can I make my Text-based game windowed?
I've been making a text-based RPG in Python, and I'm a bit lost in transitioning from a console to a window.

I'm not trying to do anything fancy (I think). I'd like my text to display normally, as it would in the console.

This is a good example: http://inventwithpython.com/blogstatic/esotera.png?27f655

However, I'd like to load images so that my different locations have corresponding backgrounds (I.e. When the character enters a tavern, the background is a tavern).

I have Pygame installed, but I really have no idea where to go from here, and I can't find any tutorials for text-based games like this.

My game code is here if you'd like to take a look:

https://gist.github.com/NervousTumbleweed/f42f325982f2sf2549b528ce0156j34a

# Answer
You can use Python's `pygame` library, which is used to make video games, and handles GUI as well. Here's a small example (Nerd Paradise PyGame Tutorial):

```
import pygame

pygame.init()
screen = pygame.display.set_mode((400, 300))
done = False

while not done:
        for event in pygame.event.get():
                if event.type == pygame.QUIT:
                        done = True

        pygame.display.flip()

```

Using this example, you can create your own window, and draw graphics into it. To draw a simple rectangle you use

```
pygame.draw.rect(screen, (0, 128, 255), pygame.Rect(30, 30, 60, 60))

```

Once you get used to it, you can learn how to draw Sprites and text and complete something similar to the screenshot you provided, including images as background. Take a look at Nerd Paradise's tutorial for more in-depth of `pygame` and what you can do with it.
> 1 votes

---
Tags: gui, python, text-based
---