# Question
Title: AS3/Flashdevelop - Controlling a 2D character to move around a planet with gravity
With a little help I have managed to create a 2D planet with working gravity that constantly pulls a character towards its center. The only problem now is that I am completely stumped on how to make it so the user is able to make this character traverse the planet as one would expect rather than the simple up/down/left/right we are used to in natural platformers.

It should be noted the planet being traversed will have platforms/layers to jump and fall onto, so the moving and jumping should be in relation to the center of the planet, where the center of the planet acts as "down" would in a traditional platformer (which is why I seem to think I need a complicated way to create this kind of natural movement).

I had the idea of recalculating a new left and right direction to move in every time position is changed but the logic I have to work out to achieve this is beyond my knowledge.

Is this the only way to go or should I try tackling the problem differently? I hope not because I don't think I'd be able to achieve this otherwise.

This is my current code showing how the gravity works, with a simple placeholder for movement that just allows the character to move up/down/left/right on the screen:

```
public function moveChar(event:Event):void
    {
            if (leftPressed)
            {
                character.x -= mainSpeed;
            }
            if (rightPressed)
            {
                character.x += mainSpeed;
            }
            if (upPressed)
            {
                character.y -= mainSpeed;
            }
            if (downPressed)
            {
                character.y += mainSpeed;
            }
        }

public function gravity():void
{
    //tan2(planet.y - player.y, planet.x - player.x)
    angle = Math.atan2((planet1.y + 2245) - (character.y+5), (planet1.x+2245) - (character.x+5));
    gravityX = Math.cos(angle) * gravitationalAcceleration;
    gravityY = Math.sin(angle) * gravitationalAcceleration;

    //distance = Math2.Pythagoras(planet1.x + 50, planet1.y + 50, character1.x + 5, character1.y + 5);
    distance = Math.sqrt((yDistance * yDistance) + (xDistance * xDistance));

    //Calculate the distance between the character and the planet in terms of x and y coordinate
    xDistance = (character.x + 5) - (planet1.x + 2245);//320 to 50
    yDistance = (character.y + 5) - (planet1.y + 2245);//320 to 50

    //Make sure this distance is a positive value
    if (xDistance < 0) {
        xDistance = -xDistance;
    }
    if (yDistance < 0) {
        yDistance = -yDistance;
    }

    //Update the current velocity before new velocity is calculated
    initialXVelocity = finalXVelocity;
    initialYVelocity = finalYVelocity;

    //Send the character into the correct direction
    character.x += gravityX;
    character.y += gravityY;

    //Basic collision detection of the surface, basic stop of gravity
    if (distance <= planet1Radius) {
    trace("hit!");

    if (planet1.x - 2180 < character.x - 5) { //320 to 50
        character.x -= gravityX*1.025;
    }
    else {
        character.x += gravityX*1.025;
    }
    if (planet1.y - 2180 < character.y - 5) { //320 to 50
        character.y -= gravityY*1.025;
    }
    else {
        character.y += gravityY*1.025;
    }
    } else {
    trace(" no hit!");
    }
}

```

edit1: I now have this code thanks to @DMGregory:

```
var characterPosition:Point = new Point();
var planetPosition:Point = new Point();
characterPosition.x = character.x;
characterPosition.y = character.y;
planetPosition.x = planet1.x;
planetPosition.y = planet1.y;

var localUp = normalize(characterPosition - planetPosition);
var localRight = new vector2( -localUp.y, localUp.x);

```

However, I have trouble understanding the syntax I should be using here, and also for when I need to move the character. Should it look something like this:

```
if (rightPressed)
{
    character.x += localRight;
{
if (leftPressed)
{
    character.x -= localLeft;
{

```

# Answer
The math for calculating this local basis in 2D is actually pretty straightforward:

```
  localUp = normalize(myPos - planetCenter);
  localRight = new vector2(-localUp.y, localUp.x);

```

This gives you two perpendicular vectors of unit length, which you can use to apply movement to your character toward/away from the planet or around it tangentially.

**Edit:** as in my previous answer, I'm using vector notation for simplicity. To break it down into componentwise math:

```
localUpX = myPosX - planetCenterX;
localUpy = myPosY - planetCenterY;
var distanceFromCenter : Number = Math.sqrt(localUpX * localUpX + localUpY * localUpY);

// Normalization
localUpX /= distanceFromCenter;
localUpY /= distanceFromCenter;

localRightX = -localUpY;
localRightY = localUpX;

```

Using this, you'd update your movement logic something like...

```
if (leftPressed)
{
    character.x -= localRightX * mainSpeed;
    character.y -= localRightY * mainSpeed;
}

```

If you're unable to translate between vector notation and componentwise operations like this, then I *strongly advise* that you take some time to learn a little linear algebra, also called vector math. It's used a *ton* in games, so familiarity with it will let you do a lot more, and understand a lot more of how game developers talk about solving problems. There are free tutorials & courses online (check Khan Academy or Coursera for instance). Also, my offer in the comments above stands, if you want some coaching on fixing the rest of this code.
> 0 votes

---
Tags: physics, actionscript-3, flashdevelop
---


# Question
Title: Why do I get this error when setting up Android support for Game Maker?
Game Maker asks me to install the Android SDK API 13 for it to work. I opened the SDK Manager and clicked at API 13 but I wasn't able to click the "install packages" button.

I clicked at the obsolete and then I was able to install. But when I pressed "Accept Licence" I wasn't able to click install as an error came out:

```
Package Google Tv Addon, Android API 13, revision 1 (Obsolete) depends on Missing SDK Platform Android, API 13".

```

Any help would be much appreciated.

# Answer
API level 13 isn't the only one you are supposed to install in order to export APKs from Game Maker (Studio, I guess). All you need to do is check this guide out and follow the steps. I did so and Android module worked fine.
> 1 votes

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


# Question
Title: Select all components of certain type in the children Game Objects
I would like to set programatically the material on a Game Object. The problem is that it has several Child Objects, which many have their own sprite.

I came up with this...

```
    foreach(Transform child in enemy.transform) {

        SpriteRenderer _spriteRenderer = child.GetComponent<SpriteRenderer>();

        if (_spriteRenderer) {
            _spriteRenderer.material = ...;
        }

    }

```

...which works, but it is not very pretty. Is there a better way to do this?

**Update:** I know about `GetComponentsInChildren` but I need to also get the GameObject that are disabled

# Answer
See the documentation for `GetComponentsInChildren`:

`public Component[] GetComponentsInChildren(Type type, bool includeInactive = false);`

This states you can use the boolean `includeInactive` in `GetComponentsInChildren` to also get the inactive components. This way you can grab all the transforms. Even inactive ones. So you would probably want to do this:

```
//Create an array of SpriteRenderers
SpriteRenderer[] _spriteRenderers;
void Start ()
{
  _spriteRenderers = transform.GetComponentsInChildren<SpriteRenderer>(true); //This returns an Array
   //Change the material on all the Sprite Renderers.
   for (int i = 0; i < _spriteRenderers.Length; i++)
   {
     _spriteRenderers[i].material = ...;
   }
}

```
> 3 votes

---
Tags: unity
---


title: Problem with stencil in directx 12

text:
# Question
Title: Problem with stencil in directx 12
I'm trying to use stencil buffer in directx 12. I have problem that probably is really easy to solve. So, it's look like dx12 ignore it, ClearDepthStencilView() affect only depth, writing to stencil doesn't work.

D3D12\_DEPTH\_STENCIL\_DESC for PSO:

```
static D3D12_DEPTH_STENCIL_DESC const defaultDepthStencil =
{
    /*DepthEnable*/                         TRUE
    /*DepthWriteMask*/                      ,D3D12_DEPTH_WRITE_MASK_ALL
    /*DepthFunc*/                           ,D3D12_COMPARISON_FUNC_LESS
    /*StencilEnable*/                       ,TRUE
    /*StencilReadMask*/                     ,D3D12_DEFAULT_STENCIL_READ_MASK
    /*StencilWriteMask*/                    ,D3D12_DEFAULT_STENCIL_WRITE_MASK
    /*FrontFace.StencilFailOp*/             ,{ D3D12_STENCIL_OP_REPLACE
    /*FrontFace.StencilDepthFailOp*/        ,D3D12_STENCIL_OP_REPLACE
    /*FrontFace.StencilPassOp*/             ,D3D12_STENCIL_OP_REPLACE
    /*FrontFace.StencilFunc*/               ,D3D12_COMPARISON_FUNC_ALWAYS }
    /*BackFace.StencilFailOp*/              ,{ D3D12_STENCIL_OP_REPLACE
    /*BackFace.StencilDepthFailOp*/         ,D3D12_STENCIL_OP_REPLACE
    /*BackFace.StencilPassOp*/              ,D3D12_STENCIL_OP_REPLACE
    /*BackFace.StencilFunc*/                ,D3D12_COMPARISON_FUNC_ALWAYS }
};

```

DSV heap desc:

```
D3D12_DESCRIPTOR_HEAP_DESC dsvHeapDesc = {};
    dsvHeapDesc.NumDescriptors = 1;
    dsvHeapDesc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_DSV;
    dsvHeapDesc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_NONE;

```

DSV desc:

```
D3D12_DEPTH_STENCIL_VIEW_DESC depthStencilDesc = {};
    depthStencilDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
    depthStencilDesc.ViewDimension = D3D12_DSV_DIMENSION_TEXTURE2D;
    depthStencilDesc.Flags = D3D12_DSV_FLAG_NONE;

```

Resource desc:

```
m_gBuffer[GB_Depth].Dimension( D3D12_RESOURCE_DIMENSION_TEXTURE2D );
m_gBuffer[GB_Depth].Width( m_width );
m_gBuffer[GB_Depth].Height( m_height );
m_gBuffer[GB_Depth].DepthOrArraySize( 1 );
m_gBuffer[GB_Depth].MipLevels( 1 );
m_gBuffer[GB_Depth].Format( DXGI_FORMAT_R24G8_TYPELESS );
m_gBuffer[GB_Depth].SampleCount( 1 );
m_gBuffer[GB_Depth].Layout( D3D12_TEXTURE_LAYOUT_UNKNOWN );
m_gBuffer[GB_Depth].Flags( D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL );

```

Then OMSetRenderTargets() and ClearDepthStencilView() with flags D3D12\_CLEAR\_FLAG\_DEPTH, D3D12\_CLEAR\_FLAG\_STENCIL.

Any idea what's missing?

# Answer
Ok, I found what was wrong. Nsight have problem with stencil buffer on dx12. Every thing works, only Nsight doesn't show correct data for depth/stencil buffer.
> 1 votes

---
Tags: directx, stencil
---


title: reuse texture between quad objects

text:
# Question
Title: reuse texture between quad objects
This question is specific to unity:

I want to spawn multiple blocks, each representing a letter. There will be more than one copy of an alphabet.

I have a big texture which contains all the letters in it. I use a prefab to `Instance` all the Blocks(quads) during `Awake()`. At runtime, I'd like to assign a texture to these quads (identifying the letter). My code looks like this:

```
    void Update () {
            // if there is no active block, spawn it
            if (activeBlock == null) {
                this.getNextBlock (ref this.activeBlock);
    }
    protected Block getNextBlock(ref Block block){
            block = this.deQueueBlock ();
            char letter = LetterMgr.Instance.getNextLetter();
            // based on the letter, index into texture
            // and assign the texture + indices to this block ?
    }

```

How can I reuse this one big texture and index into each letter amidst all these `blocks (quads)` ? I will be rendering this on a mobile, so will need to squeeze all the performance I can. Details:

* 256 x 256 per letter
* 8 columns x 4 rows
* Total Texture Size: 2048 x 2048
* Total number of blocks: ~100

PS: Each of the letters will be moving and will eventually come to rest. So I will have some (around 6-7) actively moving blocks and others will be stationary.

# Answer
> 1 votes
Thanks for your patience, the particle solution below took a bit more fiddling to get working than I'd counted on. ;)

Note that in all of these methods (and the one proposed by lvictorino) the texture is shared - what you're asking for doesn't require duplicating the texture in memory. What can pile up are draw calls, so let's look at how we can minimize those...

## Method 1 - Sharing Materials Per Unique Letter

We can improve on 1 draw call per quad by sharing one material instance among all quads sharing a letter.

My preferred approach to this is to keep a cache of variants on the material, and serve from the cache when we've already constructed the variant we need. So we'll construct a new material for the first three letters in "madam" but we'll reuse existing cache entries for the last two.

If we're not using Z-sorting (opaque/alpha-tested materials) then this will make 1 draw call per *unique* letter, or a maximum of 26 for English text in a single case without punctuation, no matter how many copies of each letter you have.

If we need to use Z-sorting, then your draw calls can be as high as one per letter instance (imagine a stack of AZAZAZAZAZ layered in front of one another - there's no way to batch the As together without drawing a Z out of order), as bad as the naive method, but these pathological cases are relatively rare.

(Also, even the best solutions here can still create many draw calls in this case if layered with other, unrelated materials - so there's only so much we can do)

Here's an example class that does this:

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

[RequireComponent(typeof(Renderer))]
public class CachedMaterialSlice : MonoBehaviour {

    struct VariantDefinition
    {
        public Material baseMaterial;
        public byte tilesX;
        public byte tilesY;
        public short index;
    }

    static Dictionary<VariantDefinition, Material> _materialCache = new Dictionary<VariantDefinition, Material>();

    static Material GetMaterialVariant(VariantDefinition definition)
    {
        Material variant;
        if(_materialCache.TryGetValue(definition, out variant) == false)
        {
            variant = Instantiate<Material>(definition.baseMaterial);
            var scale = new Vector2(1f / definition.tilesX, 1f / definition.tilesY);
            variant.SetTextureScale("_MainTex", scale);
            variant.SetTextureOffset("_MainTex", Vector2.Scale(scale,
                new Vector2(definition.index % definition.tilesX, definition.index / definition.tilesX)));

            _materialCache[definition] = variant;
        }
        //Debug.Log("Cache size: " + _materialCache.Count);
        return variant;
    }

    public byte tilesX = 8;
    public byte tilesY = 8;
    public short index = 0;

    void FetchMaterialVariant()
    {
        var renderer = GetComponent<Renderer>();
        var definition = new VariantDefinition();
        definition.tilesX = tilesX;
        definition.tilesY = tilesY;
        definition.index = index;
        definition.baseMaterial = renderer.sharedMaterial;

        var fetchedMaterial = GetMaterialVariant(definition);
        if (fetchedMaterial != null)
            renderer.sharedMaterial = fetchedMaterial;
    }

    void OnValidate()
    {
        FetchMaterialVariant();
    }

    void OnDeserialize () {
        FetchMaterialVariant();
    }
}

```

Note that this version never prunes old entries from the cache. If you're using a fixed-size alphabet that's probably not a big deal, but something to keep an eye on.

## Method 2: Manipulating UVs

We draw all the quads with a single material, manipulating the UVs of each quad to select just the part of the texture we want.

On the surface this would still be at least 1 draw call per unique letter, since although there's only one material there are many different sets of vertex data (and different transforms per instance), but this situation is very friendly for Dynamic Batching so the engine will very likely automate combining your quads into one mesh for rendering each frame. (Profile to make sure, of course)

Just like Materials, we'll want to cache these Meshes so we only create as many unique instances as are really needed, but I'll elide that here and focus on just the Mesh manipulation bit:

```
    void UpdateMesh()
    {
        var filter = GetComponent<MeshFilter>();

        if (_mesh == null)
        {
            _mesh = Instantiate<Mesh>(filter.sharedMesh);
            filter.sharedMesh = _mesh;
        }

        Vector2[] uv = new Vector2[4];

        Vector2 scale = new Vector2(1f / tilesX, 1f / tilesY);

        uv[0] = Vector2.Scale(scale, new Vector2(index % tilesX, index / tilesX));
        uv[2] = uv[0]; uv[2].x += scale.x;
        uv[3] = uv[0]; uv[3].y += scale.y;
        uv[1].x = uv[2].x; uv[1].y = uv[3].y;

        _mesh.uv = uv;
    }

```

This should still give 1 draw call even in the nasty AZAZAZAZ case described earlier - because all the letters use one material, the engine should be able to sort them when constructing the draw call. Interleaving with unrelated materials will still increase your count though.

## Method 3: Abuse of Particle Systems

I wrote this version up while I'd briefly forgotten that Dynamic Batching was a thing. So... profile that solution first, as it's very likely going to give equal or better performance for quite a bit less work.

That said, this approach has a certain cuteness... Here we use the fact that Unity's ParticleSystem can draw clouds of thousands of particles drawing from different parts of a shared spritesheet, and we trick that into drawing our quads for us.

First, the class you put on (otherwise empty) letter GameObjects parented to your ParticleSystem:

```
public class ParticleQuad : MonoBehaviour {

    [SerializeField]
    int _spriteIndex;

    float _particleValue = 0;
    bool _isInList = false;

    public int spriteIndex
    {
        get { return _spriteIndex; }
        set
        {
            _spriteIndex = value;
            _particleValue = _spriteIndex + 0.5f;
        }
    }

    public void MarkRemoved()
    {
        _isInList = false;
    }

    public float GetParticleValue()
    {
        return _particleValue;
    }

    void OnValidate()
    {
        spriteIndex = _spriteIndex;
    }

    void OnEnable()
    {
        if(!_isInList)
            transform.parent.GetComponent<ParticleQuadManager>().Register(this);
        _isInList = true;
    }
}

```

Now, configure the ParticleSystem as follows:

* Enable only the Renderer and Texture Sheet Animation subcomponents. Disable Emission/Shape (we'll be driving these manually)
* Configure the Texture Sheet Animation subcomponent with the number of rows and columns in your whole texture (include empty space). Keep the curve as its default.
* Set the Start Color and Start Size to the appropriate values for your quads (variable colours/sizes can be supported, I just haven't shown that functionality here)
* Set the Max Particles value to the max you'll actually use.

Then attach this script:

```
using UnityEngine;
using System.Collections.Generic;
using Particle = UnityEngine.ParticleSystem.Particle;

[RequireComponent(typeof(ParticleSystem))]
public class ParticleQuadManager : MonoBehaviour {

    ParticleSystem _system;
    Particle[] _particles;
    public List<ParticleQuad> _quads = new List<ParticleQuad>();
    Particle _blank;
    int _lastParticleCount;

    void OnValidate()
    {
        if (_system == null)
            _system = GetComponent<ParticleSystem>();
        UpdateBlankParticle();
    }

    void UpdateBlankParticle()
    {
        _blank = new Particle();
        _blank.startLifetime = _system.textureSheetAnimation.numTilesX * _system.textureSheetAnimation.numTilesY;
        _blank.startSize = _system.startSize;
        _blank.startColor = _system.startColor;
    }

    void Start()
    {
        _system = GetComponent<ParticleSystem>();
        _particles = new Particle[_system.maxParticles];
        UpdateBlankParticle();
    }

    public void Register(ParticleQuad quad)
    {
        _quads.Add(quad);
    }

    void LateUpdate()
    {
        // Remove any quads that have been deleted.
        _quads.RemoveAll((quad) =>
        {
            if (quad == null)
                return true;

            if(quad.enabled == false)
            {
                quad.MarkRemoved();
                return true;
            }

            return false;
        });

        // Match all particles to the current quad positions.
        for(int i = 0; i < _quads.Count; i++)
        {
            Particle p = _blank;
            p.position = _quads[i].transform.localPosition;
            p.lifetime = p.startLifetime - _quads[i].GetParticleValue();

            _particles[i] = p;
        }

        // Wipe unneeded particles.
        for(int i = _quads.Count; i < _lastParticleCount; i++)
        {
            Particle p = _blank;
            p.lifetime = float.PositiveInfinity;
            _particles[i] = p;
        }

        _system.SetParticles(_particles, Mathf.Max(_quads.Count, _lastParticleCount));

        _lastParticleCount = _quads.Count;
    }
}

```

Now the particle versions of the quads will track the movement of the corresponding GameObjects, all drawn in one pass barring any sorting with unrelated materials. A silly way to do it, but it does work. ;) I make no guarantees it performs well - profile and see, but my bet's on the UV modification + Dynamic Batching approach winning.

# Answer
> 0 votes
Your quads may be game objects and have a `MeshRenderer`.

MeshRenderer components give you access to the renderer Material. And the Material gives you access to the texture via SetTexture. So once you have Instantiated your new object you can set your Texture doing:

```
MeshRenderer object_renderer = my_new_game_object.GetComponent<MeshRenderer>();
object_renderer.material.SetTexture(my_texture);

```

---
Tags: unity, textures, optimization, uv-mapping
---


title: Get world position of touch on objects

text:
# Question
Title: Get world position of touch on objects
In my Unity3d game, I want to get the world position that was touched, when I touch a specific object, regardless of all objects that are in front of it.

How would I do that, I only know Camera.ScreenPointToRay(...), but for some reason that does not work properly?

---

OK - one cannot answer the question with the information I provided.

In order to determin the point, where the Ray hit the object, I used `RaycastHit.transform.position` (which refers to the Transform object that was hit) as opposed to `RaycastHit.point` (which refers to the `Vector3` in world space, where the `RaycastHit` happened).

# Answer
I've worked out a system that prints the position the mouse is hovering over. You will probably want to write a function that doesn't update every frame. When you click it spits out an `Vector3` of the position in worldspace you are hovering over with your mouse in Screen space.

```
using UnityEngine;
using System.Collections;

public class check : MonoBehaviour
{
    void Update()
    {
        RaycastHit hit;
        // Cast a ray from the mouse position to the world
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        //When the ray hits anything, print the world position of what the ray hits using hit.point
        if (Physics.Raycast(ray, out hit)  && Input.GetMouseButtonDown(0)))
            print(hit.point);
    }
}

```

You can now Instantiate GameObjects with `Instantiate(yourGO,hit.point,Quaternion.identity);`
> 0 votes

# Answer
Camera.ViewportToWorldPoint allows you to get the place you clicked on the screen as a point in world space.
> 1 votes

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


title: Collectiion was modified(monogame)

text:
# Question
Title: Collectiion was modified(monogame)
I did use this...and when i changed Screens it gave me this error : Collection was modified; enumeration operation may not execute.

```
foreach(var screen in ScreenList)

```

Inside Base Screen

```
  public void HideScreen()
    {
        Enabled = true;
        Visible = true;
        alpha = 0;
        fade = Fade.Out;

    }

    public void Show()
    {
        Enabled = true;
        alpha = 1;
        fade = Fade.Out;
    }

```

And in Screen manager

```
 public static void ChangeScreen(BaseScreen CurrentScreen, BaseScreen TargetedScreen)
    {
        TargetedScreen.HideScreen();
        AddScreen(CurrentScreen);
        RemoveScreen(TargetedScreen);
        CurrentScreen.Show();
    }

```

# Answer
> 0 votes
This error typically happens when you remove an item from a collection during the `foreach` loop. So to simplify what's happening in your code is something like this:

```
foreach(var screen in ScreenList)
{
    if(whatever)
        ScreenList.Remove(screen);
}

```

There's a few different ways to solve this.

The first simple way is to make a copy of the list before you enumerate it.

```
foreach(var screen in ScreenList.ToArray())

```

The downside of this approach is that the copy operation can be a performance hit if the list is large.

The second is to use a `for` loop instead.

```
for(var i = 0; i < ScreenList; i++)
{
    var screen = ScreenList[i];

    if(whatever)
    {
        ScreenList.RemoveAt(i);
        i--;
    }
}

```

The downside of this approach is that it's more complicated because you have to make sure you don't skip over one of the items. I'm not even sure I've got this one right.

The third approach is to have some way to mark the items for removal and remove them later.

```
foreach(var screen in ScreenList)
{
    if(whatever)
        screen.IsRemoved = true;
}

ScreenList.RemoveAll(i => i.IsRemoved);

```

The downside is that you have to add an extra property to your objects.

The last approach is to hold the removed items in another list temporarily and remove them later.

```
var removedList = new List<Screen>();

foreach(var screen in ScreenList)
{
    if(whatever)
        removedList.Add(screen);
}

foreach(var screen in removedList)
    ScreenList.Remove(screen);

```

The downside of this approach is the extra memory allocation of another list.

I've used all of these in various situations and I'm still not completely happy with any of them. I'll let you decide which approach is better for you.

---
Tags: monogame
---


# Question
Title: Who should be contacted to request permission, for commercial songs (and cost ballpark)
While playing to Fifa, it occurred to me that there is probably a license that EA pay to musicians to play their songs in their game.

Does anyone know if there is a standard license for indie games, to be able to play commercial songs in the game? Either for the intro and for the game itself, like FIFA does.

I did a brief search and the suggestion is to contact the publisher of the specific group/singer; but 90% of the time they probably won't even read such email. Is this the only way?

Of course this won't apply for free music that is distributed to be freely used for any use; my question is specifically for commercial music from decently known artists.

# Answer
Usually "decently known" musicians sell all their copyrights to the record label. So these are the people you need to contract when you want a license. Such record deals are usually exclusive, so the artist themselves could not sell you the rights even if they want to. Unless it's a lesser known artist, expect to pay a very large amount of cash for the rights to their music.

You should also definitely get a lawyer for the license negotiation to make sure you are buying exactly the rights you need.
> 2 votes

# Answer
Disclaimer: I am not a lawyer and this is not valid legal advice. Do not quote me on this please.

If you are developing a game you can use some commercial music but there are conditions. First off, you have to credit the artist, then you have to protect the content enough to prevent it being re-distributed by your game players. All this is on condition that your game is non-commercial and you are making no money at all from it.

If you plan to go the legal commercial route then you need to contact the person who composed the music, their record label and the company that distributed the music. It is never one person.

If you do get the rights to use the music then you may have to pay a huge load of cash for it depending on the companies. Some might let you use it for free. Depending on the company that is.

Honestly you'd be better off just composing your own or using Royalty free assets. With content, even if you modify it and the owners take you to court they could be able to prove you plagiarized their content.
> -3 votes

---
Tags: legal, copyright, music
---


# Question
Title: How to access the currently touched instance of the Prefab?
I have a prefab which is instantiated in the Scene and what I am trying to do is to disable with a *touch* or `timeCounter` but sometimes it disables all the instances of the prefab and sometimes 2 or 3 of them.

I want to disable particular object which I have touched currently.

when i am passing the *collider* in `Destroy(hit.collider)` it works perfect but how to handle it *null* is passed as parameter.

Here is my code:

```
 void Update () {
     blastingTimeCounter -= Time.deltaTime;

     if (blastingTimeCounter <= 0) {
         DestroySquare (null);
     }

     for (int i = 0; i < Input.touchCount; i++) {
         if (Input.GetTouch (i).phase == TouchPhase.Stationary) {
             hit = Physics2D.Raycast (Camera.main.ScreenToWorldPoint (
                 Input.GetTouch (i).position),
                 Vector2.zero);
             if (hit.collider != null) {
                         DestroySquare (hit.collider);
             }
         }
     }
  }

  void DestroySquare(Collider2D collider){

     if(collider == null)
     {

     }
     else{
     collider.gameObject.SetActive (false);
     blastingTimeCounter = blastingTime;
     }
   }

```

# Answer
Finally find out the solution and it works..

```
 void DestroySquare(Collider2D collider){

 if(collider == null)
 {
      GameObject obj = (GameObject)gameObject;
        obj.SetActive (false);

      //blastingTimeCounter = blastingTime;  this was changing in all the instances of a prefab

    obj.GetComponent <BlackSquare2>().blastingTimeCounter = blastingTime; // correct

 }
 else{
 collider.gameObject.SetActive (false);
 //blastingTimeCounter = blastingTime;  this was changing in all the instances of a prefab

  collider.gameObject.GetComponent <BlackSquare2>().blastingTimeCounter = blastingTime; // correct

       }
}

```

I Just want to know why `blastingTimeCounter = blastingTime` is changing in all the instances of a prefab?

while doing this `collider.gameObject.GetComponent <BlackSquare2>().blastingTimeCounter = blastingTime;` it will reset `blastingTimeCounter` correctly.
> 0 votes

# Answer
I think what you're trying to do is something like this:

```
void DestroySquare() {

    if (hit != null) {
        hit.transform.gameObject.SetActive(false);
    } else {} // Do nothing
}

```
> 0 votes

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


title: Unity3d multiplayer canvas

text:
# Question
Title: Unity3d multiplayer canvas
so I am making multiplayer game and I stuck on one thing, I have blood overlay canvas in my scene(you know, in fps games if somebody shoots you your screen becomes red and this stuff), and when I shoot enemy, his screen becomes red, but mine also.

thats what i ahve now: if raycast hits enemy, player script calls: `ColorController.MakeItred();` color controller is attached to this canvas image, here is its code:

\`

```
 void Start () {
       if (current == 100 || current == 0)
        {
        opacity = 0;
        }
    }

// Update is called once per frame
void Update () {
          image = GetComponent<Image>();
    image.color = new Color32(reds, greens, blues, opacity);

    if (current == 0)
    {
        opacity = 0;
    }
    if (!playing)
    {
        if (opacity > 0)
        {
            StartCoroutine(toLower());
        }
        }
    if (opacity == 255)
    {
        playaudio();

    }

}

public static void MakeItred()
{
    opacity = 255;

}
public static void MakeItOff()
{
    opacity = 0;

}
 void playaudio()
{
    AudioSource audio = GetComponent<AudioSource>();
    audio.Play();
}
private IEnumerator toLower()
{
    playing = true;
    opacity -= 1;

    yield return new WaitForSeconds(interval);
    playing = false;
}`

```

btw thats function in player code that calls *colorcontroller.makeitred*,

`[ClientRpc]
 public void Rpcdoit()
 {
 ColorController.MakeItred();
 }`

-Nick thanks.

# Answer
You method `makeItRed` is a `static` method which sets a variable which is most likely also declared as `static`. Static variables share their value between all instances of the class. Call the method on one instance of `ColorController` and you affect them all.

So make `opacity`, `MakeItred` and `MakeItOff` non-static variables and have the raycast hit code (which you did not post) call `GetComponent<ColorController>().MakeItred()` on the object where the raycast-hit was successful.

Also, the ColorController component should check if the `gameObject` it is assigned to is the local player and only then affect the overlay graphic.
> 1 votes

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


# Question
Title: Smooth movement from point A to point B in a tile-based game
I'm currently very new to XNA, and I'm trying to get a grasp on movement. Currently, I have a function that checks for keypresses, and moves my character from point A to point B instantly:

```
private KeyboardState currentKeyboardState;
private KeyboardState previousKeyboardState;

...

public void CaptureKeyboardInput()
{
    currentKeyboardState = Keyboard.GetState();

    // Move the character's sprite to the left on the screen. The movement
    // distance is determined based on the scale of the sprite texture.
    if (currentKeyboardState.IsKeyDown(Keys.A) && previousKeyboardState.IsKeyUp(Keys.A))
    {
        Position += new Vector2(-Scale.X, 0);
    }

    // Move the character's sprite to the right on the screen. The movement
    // distance is determined based on the scale of the sprite texture.
    if (currentKeyboardState.IsKeyDown(Keys.D) && previousKeyboardState.IsKeyUp(Keys.D))
    {
        Position += new Vector2(Scale.X, 0);
    }

    // Move the character's sprite upwards on the screen. The movement
    // distance is determined based on the scale of the sprite texture.
    if (currentKeyboardState.IsKeyDown(Keys.W) && previousKeyboardState.IsKeyUp(Keys.W))
    {
        Position += new Vector2(0, -Scale.Y);
    }

    // Move the character's sprite downwards on the screen. The movement
    // distance is determined based on the scale of the sprite texture.
    if(currentKeyboardState.IsKeyDown(Keys.S) && previousKeyboardState.IsKeyUp(Keys.S))
    {
        Position += new Vector2(0, Scale.Y);
    }

    previousKeyboardState = currentKeyboardState;
}

```

While this works, it looks very unclean, and feels unnatural as well. Ideally, I'd like to move it from point A to B at a certain speed. I've already looked around, and I've found this question, but I couldn't figure out how to implement it correctly. How can I implement smooth movement from point A to B in my tile-based game with what I have?

# Answer
> 1 votes
You can accomplish this by using linear interpolation.

https://msdn.microsoft.com/en-us/library/bb197807.aspx

```
float speed = 0.1f;   //value between 0 - 1
Position = Vector2.Lerp(Position, DesiredPosition, speed);

```

Another way to do it is to incorporate a time value, while keeping track of the start and end positions. This ensures the movement will be the same regardless of framerate.

```
Vector2 StartPosition;
Vector2 EndPosition;
float Timer;
float Speed = 1;

...

void Update()
{
    var deltaTime = (float)gametime.ElapsedGameTime.TotalSeconds;

    if (Timer <= 0)
    {
        Timer += deltaTime * Speed;
        Timer = MathHelper.Min(Timer, 1);
        Position = Vector2.Lerp(StartPosition, EndPosition, Timer);
    }
}

public void CaptureKeyboardInput()
{
    currentKeyboardState = Keyboard.GetState();

    if (currentKeyboardState.IsKeyDown(Keys.A) && previousKeyboardState.IsKeyUp(Keys.A))
    {
        StartPosition = Position;
        EndPosition += new Vector2(-Scale.X, 0);
        Timer = 0;
    }

    ...
}

```

# Answer
> 0 votes
Welcome to XNA! First off, I'l strongly advise you to switch to Monogame. It uses the same bindings as XNA and your workflow will not change much. Plus it is under active maintenance.

Also, before you rush into making a game you should check out some tutorials on sprite animation and frame independent movement.

On to your question then. I've posted the correct code.

C# code:

namespace Tiled { public class Tiled : Microsoft.Xna.Framework.Game { Vector2 viewportPosition;

```
    public Tiled () {
        IsFixedTimeStep = true;
    }

    protected override void Update (GameTime gameTime) {
        GamePadState gamePadState = GamePad.GetState(PlayerIndex.One);
        KeyboardState keyState = Keyboard.GetState();
        float scrollx = 0, scrolly = 0;

        if (keyState.IsKeyDown(Keys.Left))
            scrollx = -1;
        if (keyState.IsKeyDown(Keys.Right))
            scrollx = 1;
        if (keyState.IsKeyDown(Keys.Up))
            scrolly = 1;
        if (keyState.IsKeyDown(Keys.Down))
            scrolly = -1;

        scrollx += gamePadState.ThumbSticks.Left.X;
        scrolly += gamePadState.ThumbSticks.Left.Y;

        float scrollSpeed = 8.0f;

        player.X += (int)(scrollx * scrollSpeed);
        player.Y -= (int)(scrolly * scrollSpeed);

        base.Update(gameTime);
    }
}

```

}

---
Tags: c#, xna, movement
---


# Question
Title: Tracking small moving targets in Vuforia
I am trying to track up to two small moving objects the size of a small toy car (about 7x4x4 cm / 3x2x2”) from a 75cm / 2ft distance. I’m aware that the distance/size ratio is about 20, which is off by factor compared to the by Vuforia recommended ratio.

I've tried frame markers and while frame markers are super fast close up, they don't work well at a distance. I'm hesitant to use expensive object recognition on moving targets. I’ve tried black and white QR codes and AR markers as image targets but Vuforia seems to have trouble recognizing them, even though the QR code has a five star rating.

I’m considering two more options:

1) an optimized 4x4cm color image target

2) add LEDs to the objects and track the LEDs, for example like this: https://www.youtube.com/watch?v=IoL0bIGk\_uE

My questions:

1) Are there specific tips for creating small image targets (I have read the generic image target optimizations tips assume not all those tips apply to small targets)

2) Is there an easy way to track LEDs in Vuforia?

# Answer
I would say that the object recognition is your best chance to get this working. I never read anything about LED recognition in Vuforia. For my experience I think small image targets work besser as coloured ones instead of black and white. You could create them with this tool http://www.brosvision.com/ar-marker-generator/ They worked pretty good for me compares to QR-Codes.
> 1 votes

---
Tags: unity, augmented-reality, vuforia
---


# Question
Title: How to improve my graphics on HTML5 canvas?
I am making my own army fighting simulator. Designer have made an 3D model with Blender and textured it, made animations. I have made sprites from that model and did programming. But the result is not as good as I expected. You can look at armyfight.com/simulator.html (refresh until it loads all images properly if it didn't at first time) and when you maximally maximize, you can see there are units moving. But I want to be them clearly visible, with details, high resolution like in flash-games and also that when they are really small units, would be understandable.

Is it possible on canvas?

Or it is my mistake and I must do somehow more HD sprites? I'm stuck now, and I don't know to improve the graphics..

# Answer
> 1 votes
Just draw them larger. Also don't hesitate to have the sprites overlap vertically. The sprites are rendered from a 45° angle, so it is just natural that the soldiers in the front-row overlap the lower bodies of the soldiers in the row behind them. All you need to keep in mind in that case is that you need to draw them in the correct order from back to front.

The scale of the drawn image is controlled by the last two arguments to the function `context2d.drawImage`. Make them equal to the 4th and 5th argument to keep source-resolution and target-resolution the same. In your case you are controlling these with the variable 'unit\_width'.

Another thing which can affect the scale of images (in fact the scale of the whole canvas) is the global transform setting of the canvas context , which can be changed with `context2d.transform`, `context2d.SetTransform` or `context2d.scale`. There is a huge blob of minified Javascript code in the beginning of your sourcecode which includes the string "transform" a few times, so it might also affect the scaling of the canvas somehow.

# Answer
> 0 votes
In addition to Philipp's answer:

Typically, you'll try to minimize the scaling done to your images, as the renderer may not be doing a good job in pixel interpolation/stretching.

So what you can do is have multiple size images for your character, that you do yourself offline: you'll see the result right away and you'll be able to either improve the image in Photoshop or ask your artist to do it.

Then, depending on the zoom level, you change the texture that is used to match as much as possible the size of the sprite on the screen.

This is called mipmaping.

When designing a game, you can't think of a single item at a time, you have to plan ahead and make sure everything fits together. Making fine details to you character may be looking good when up close, but when scaled really tiny, you lose the details, for instance, the sword gets barely visible. If the intention is to display a model both up-close and very tiny, instead of starting your graphics design from the up-close detailed view, then scaling it down, you could go the other way around: start from the tiny view, and make sure all of the main features of your soldiers are distinguishable. For instance, if the sword looks really like noting, how about an axe instead? Then as you detail the bigger images/LoD, you can add more details to it.

---
Tags: graphics, html-canvas
---


# Question
Title: Interact with texture / flat surface (Unity)
I don't know exactly how to put this into words, so googling did nothing really for me.

Imagine a bowling game. On the oldern bowling lanes there was only a scheme of the pins above the lane, lighting up all the pins that are still standing, while the ones that already fell, were not lit anymore.

How can I achieve this in Unity? Is there any way to do this, without having to make something stupid like creating hundreds of textures, with all the possible combinations and swap them out?

I'm still very new to Unity, so I'd love to know the best approach to something like this.

Thank you very much in advance

# Answer
> 1 votes
This depends very much on how you are displaying the pin status to the user. If you are using the UI features it could be as easy as setting up a prefab using a game object with an Image Component and a custom script that controls the Image component's image based on the status of an associated pin.

In a 2D Game you can create a prefab with a sprite for the pin statuses and render them over a background at the appropriate location.

If you are attempting to create a texture that gets applied to a mesh, you could do something similar and render that to a texture to be applied to the mesh whenever the pin status changes.

References:

---
Tags: textures, unity
---


title: WebGL color quantization

text:
# Question
Title: WebGL color quantization
I'm making a WebGL game in a 90s DOS games style. I'm trying to use a shader which would quantize colors to get reduced colors look. I found this solution: Palette reduction to pre-defined palette, however I only get 4 colors when I apply the shader (as in the picture). Any help would be greatly appreciated.

# Answer
> 3 votes
Unless you have a specific 256 colors palette in mind, you could just use the "8-bit truecolor" as described at 8-bit color Wikipedia page.

To do that, you need to map R and G channels onto 8 values (3 bits each), and B onto 4 values (2 bits). Those 8 bits together make up 256 possible colors.

Provided your gl\_FragColor is already determined, the lines below will map its color to one of 256 values:

```
vec3 color_resolution = vec3(8.0, 8.0, 4.0);
vec3 color_bands = floor(gl_FragColor.rgb * color_resolution) / (color_resolution - 1.0);
gl_FragColor = vec4(min(color_bands, 1.0), gl_FragColor.a);

```

The `min` clamping in the last line might not be necessary, this depends on the color buffer's format, you might keep it if unsure or take a look at https://stackoverflow.com/questions/26786711/will-the-fragment-shader-automatically-clamp-the-color-value-to-its-range.

---
Tags: webgl
---


title: Trouble applying a texture to a cube

text:
# Question
Title: Trouble applying a texture to a cube
Currently working on applying a texture to a cube and I am at a road block. I am using UV coordinates to apply the texture. Currently using 24 uv coordinates with indices. I am using glDrawElement and draw all 36 vertices. The cube in itself renders but the texture looks blurry and not accurate.

```
const GLfloat vertices[] = {

   -0.5f,  0.5f, 0.0f,  // Top Left
   -0.5f, -0.5f, 0.0f,  // Bottom Left
    0.5f, -0.5f, 0.0f,  // Bottom Right
    0.5f,  0.5f, 0.0f,  // Top Right

  -0.5f,  0.5f, -1.0f,  // Top Left     (back)
  -0.5f, -0.5f, -1.0f,  // Bottom Left  (back)
   0.5f, -0.5f, -1.0f,  // Bottom Right (back)
   0.5f,  0.5f, -1.0f   // Top Right    (back)

};

const GLfloat color[] = {

    0.0f, 0.0f, 1.0f,
    0.0f, 0.0f, 1.0f,
    0.0f, 0.0f, 1.0f,
    0.0f, 0.0f, 1.0f
};

const GLfloat texCoord[] = {

    1.0f, 1.0f, 0.0f,
    1.0f, 0.0f, 0.0f,
    0.0f, 0.0f, 0.0f,
    0.0f, 1.0f, 0.0f

};

const GLfloat uvCoord[] =
{

    0.0f, 1.0f,  // Top Left
    0.0f, 0.0f,  // Bottom Left
    1.0f, 0.0f,  // Bottom Right
    1.0f, 1.0f,   // Top Right

    0.0f, 1.0f,  // Top Left
    0.0f, 0.0f,  // Bottom Left
    1.0f, 0.0f,  // Bottom Right
    1.0f, 1.0f,   // Top Right

    0.0f, 1.0f,  // Top Left
    0.0f, 0.0f,  // Bottom Left
    1.0f, 0.0f,  // Bottom Right
    1.0f, 1.0f,   // Top Right

    0.0f, 1.0f,  // Top Left
    0.0f, 0.0f,  // Bottom Left
    1.0f, 0.0f,  // Bottom Right
    1.0f, 1.0f,   // Top Right

    0.0f, 1.0f,  // Top Left
    0.0f, 0.0f,  // Bottom Left
    1.0f, 0.0f,  // Bottom Right
    1.0f, 1.0f,   // Top Right

    0.0f, 1.0f,  // Top Left
    0.0f, 0.0f,  // Bottom Left
    1.0f, 0.0f,  // Bottom Right
    1.0f, 1.0f   // Top Right

};

const GLuint indices[] =
{
    // Front
    0, 1, 3,
    1, 2, 3,

    // Back
    4, 5, 6,
    4, 6, 7,

    // Left
    4, 5, 1,
    1, 0, 4,

    // Right
    3, 6, 2,
    7, 6, 3,

    // Top
    7, 4, 3,
    4, 0, 3,

    // Bottom
    1, 2, 5,
    2, 5, 6

};

const GLuint VERTEX_POS  = 0;
const GLuint COLOR       = 1;
const GLuint TEX_POS     = 2;
const GLuint UV_POS      = 3;

GLuint VAO;
glGenVertexArrays(1, &VAO);
glBindVertexArray(VAO);

    const int SIZE = 4;

    GLuint VBO[SIZE];
    glGenBuffers(SIZE, VBO);

    // Handles position
    glBindBuffer(GL_ARRAY_BUFFER, VBO[0]);
    glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
    glVertexAttribPointer(VERTEX_POS, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), nullptr);
    glEnableVertexAttribArray(VERTEX_POS);

    // Handles Color
    glBindBuffer(GL_ARRAY_BUFFER, VBO[1]);
    glBufferData(GL_ARRAY_BUFFER, sizeof(color), color, GL_STATIC_DRAW);
    glVertexAttribPointer(COLOR, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), nullptr);
    glEnableVertexAttribArray(COLOR);

    // Handles Texture Coordinates
    glBindBuffer(GL_ARRAY_BUFFER, VBO[2]);
    glBufferData(GL_ARRAY_BUFFER, sizeof(texCoord), texCoord, GL_STATIC_DRAW);
    glVertexAttribPointer(TEX_POS, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), nullptr);
    glEnableVertexAttribArray(TEX_POS);

    // Handles uv Coordinates
    glBindBuffer(GL_ARRAY_BUFFER, VBO[3]);
    glBufferData(GL_ARRAY_BUFFER, sizeof(uvCoord), uvCoord, GL_STATIC_DRAW);
    glVertexAttribPointer(UV_POS, 2, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), nullptr);
    glEnableVertexAttribArray(UV_POS);

    GLuint EBO;
    glGenBuffers(1, &EBO);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW);

    GLuint Texture;
    glGenBuffers(1, &Texture);
    glBindTexture(GL_TEXTURE_2D, Texture);

    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);

    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);

    int texWidth;
    int texHeight;
    unsigned char * image = SOIL_load_image("brick_texture1.jpg", &texWidth, &texHeight, 0, SOIL_LOAD_RGB);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, texWidth, texHeight, 0, GL_RGB, GL_UNSIGNED_BYTE, image);
    glGenerateMipmap(GL_TEXTURE_2D);
    SOIL_free_image_data(image);

```

In the loop:

```
        glDrawElements(GL_TRIANGLES, 36, GL_UNSIGNED_INT, 0);

```

vertex shader:

```
#version 400 core
layout (location = 0) in vec3 position;
layout (location = 1) in vec4 color;

layout (location = 2) in vec2 texCoord;
layout (location = 3) in vec2 uvCoord;

out vec4 out_color;
out vec2 out_texCoord;
out vec2 out_uvCoord;

 uniform mat4 MVP;
 uniform mat4 rotation_matrix;

 void main()
 {
  out_color    = color;
  out_uvCoord  = uvCoord;
  out_texCoord = vec2(texCoord.x, texCoord.y);
  gl_Position  = MVP * rotation_matrix * vec4(position, 1.0f);
 }

```

Fragment Shader:

```
  #version 400 core

  in  vec4 out_color;
  out vec4 Output_Color;
  in  vec2 out_texCoord;
  out vec2 Output_texCoord;

  in vec2 out_uvCoord;

  uniform sampler2D Texture;

 void main()
 {

   Output_Color = texture(Texture, out_uvCoord);
 }

```

The finale product:

I do not know what the problem might be.

# Answer
> 0 votes
The 5th "stride" argument in all of your 4 `glVertexAttribPointer` calls is specified as `3 * sizeof(GLfloat)`, while in your case it should be 0, as you are using separate buffers per vertex attribute (see https://www.opengl.org/sdk/docs/man/html/glVertexAttribPointer.xhtml).

That argument is non-zero for cases when you interleave those attributes in a single buffer, which is an interesting optimisation, see https://www.opengl.org/wiki/Vertex\_Specification\_Best\_Practices, but I'd just change those arguments to 0 for now.

You're also using glDrawElements, which forces a different topology than you probably want to have, as the cube's faces share vertex positions, but not necessarily vertex uv mappings.

What the `glDrawElements(GL_TRIANGLES, 36, GL_UNSIGNED_INT, 0);` call is doing, is taking only `uvCoord` with indices from the 0-7 range (as that's what your `indices` array contains) which don't correspond to the correct texture coordinates at most faces.

You'll find a good explanation of mesh topologies at http://alfonse.bitbucket.org/oldtut/Illumination/Tut09%20Mesh%20Topology.html, the whole tutorial is a great read.

To cut the long story short :)

1. Define vertices as:

```
const GLfloat vertices[] = {
  -0.5, -0.5, 0.5, 0.5, -0.5, 0.5, 0.5, 0.5, 0.5,
  -0.5, -0.5, 0.5, 0.5, 0.5, 0.5, -0.5, 0.5, 0.5,

  0.5, -0.5, 0.5, 0.5, -0.5, -0.5, 0.5, 0.5, -0.5,
  0.5, -0.5, 0.5, 0.5, 0.5, -0.5, 0.5, 0.5, 0.5,

  0.5, -0.5, -0.5, -0.5, -0.5, -0.5, -0.5, 0.5, -0.5,
  0.5, -0.5, -0.5, -0.5, 0.5, -0.5, 0.5, 0.5, -0.5,

  -0.5, -0.5, -0.5, -0.5, -0.5, 0.5, -0.5, 0.5, 0.5,
  -0.5, -0.5, -0.5, -0.5, 0.5, 0.5, -0.5, 0.5, -0.5,

  -0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, -0.5,
  -0.5, 0.5, 0.5, 0.5, 0.5, -0.5, -0.5, 0.5, -0.5,

  -0.5, -0.5, 0.5, -0.5, -0.5, -0.5, 0.5, -0.5, -0.5,
  -0.5, -0.5, 0.5, 0.5, -0.5, -0.5, 0.5, -0.5, 0.5
};

```

(This does what your indices sort of did, but in an explicit way)

2. Define uvCoord as:

```
const GLfloat uvCoord[] = {
  0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f,
  0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f,

  0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f,
  0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f,

  0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f,
  0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f,

  0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f,
  0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f,

  0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f,
  0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f,

  0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f,
  0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f
};

```

so each face has the same uv mapping.

3. Replace the

```
glDrawElements(GL_TRIANGLES, 36, GL_UNSIGNED_INT, 0);

```

call with

```
glDrawArrays(GL_TRIANGLES, 0, 36);

```
4. Comment out the indices binding (`GLuint EBO;...` and 3 following lines)

Hopefully it works, if it does then try to experiment with the `uvCoord` definition to obtain the texture mapping you need.

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


# Question
Title: Destructible objects for multi-player game in Unity
I'm using SmartFoxServer for a 3D multi-player shooter game in Unity

I need to add some destructible objects in the game, so I tried these assets:

It works for a single player but I'm not sure how to notify the server to run the same destructions for other players

# Answer
> 0 votes
There are for sure more that one way to achieve this. I am not familiar with smartfox server's setup to help you on that regard & there is no point on writing about all the possible routes you could take since this topic may result in a huge discussion.

No matter what way of networking setup you do you should have to 'simulate' that destruction on the client.

**Assuming that you have a function that destroys a house for whatever reason on your clientside code:**

```
void Demolish(Object objectToDemolish, Type demolishType) {
// Do clientside gameengine stuff
}

```

**To continue here I will assume the following scenario is happening in your game:**

**1)** There are two players in the game and each player character is a tank
**2)** player 1 fires at a house **2.5)** player 1 needs to notify the server for either the destruction or the firing based on the architecture of the game
**3)** the house is destroyed on player 1's client
**4)** player 2 is notified on the event
**5)** the house is destroyed on player 2's client

on **step 3** since the house demolition occurs on the same client from where the event (**step 2**) is triggered it is fairly easy to find your house game object call your function with it as a parameter and the same goes with the demolition type.

However, player 2 will have be notified from the server with certain data in order for the client to know what to do. By using those data you will have to find the game object that needs to be demolished on the second client.

For example:

```
Object findGameObject(objectId) {
  // should return a game object based on its object id
  return GameObjectHolder.getById(objectId);
}

void HandleServerMessage(message) {
  switch(message.code) {
    case "object_destroy"
      Demolish(findGameObject(message.data.objectId), message.data.type);
      break;
    // other networking related procedures here
    defaults:
      break;
  }
}

```

Now whether player 1 will also notified by the server or by the client itself is another story, that is based on your architecture.

**case authoritative server:** you do not notify the server from firing client 1 for the destruction, but you notify it for the firing.

**action:** that means that the server will calculate where that firing will destroy an object. If it does, all clients will be notified of the destruction from the server, including client 1.

**case non authoritative server:** you do notify the server on destruction, so that the server skips that calculation. Plus you want an immediate response on the game UI, so that it does not appear laggy.

**action:** call the firing client 1's destruction method on collision between the bullet & the object. All other clients should be notified through server anyway. Just make sure not to try to destroy twice the same object.

# Answer
> 1 votes
On the most basic level, if your destruction algorithm is deterministic then the server can notify each client and the result should be the same.

The more complicated manner is that this system is notify independent of your other systems. It will probably be best for you to handle destruction in the same way.

E.g., if you are calculating trajectories and impacts at the client initiating the event, then you should do the same for your destruction. If your client notifies the server and the server makes the calculations, do the same for destruction.

If may also be worth investing your current methodology and consider changing if it is not up to the task.

# Answer
> 0 votes
I am guessing that in your case, clients are sending all their shots to the server, and the server is broadcasting them back to clients.

Basically, your clients should simulate the physics (animations and sounds as well) based on objective information coming from the server. This data can be differently structured:

* One approach is sending data about who is shooting, from which position and which direction. Then every client could simulate the bullet trajectory and check for collisions for further physic interactions. One problem here would be to make sure that all physics simulations done by the clients would end up being the same. But, this is probably one of the easiest solution.
* You might also do a part of physics in the server side, checking not only for player collisions, but also for collisions against walls/objects. This requires extra programming in the server side depending on the technologies you are using.
* You can handle the destruction physics on the server side and send the simulation to the clients, but this is probably overkill in terms of CPU and bandwith. The benefit would be making sure that every client renders the same.

Points to be considered:

* Latency compensation techniques: the information that you send/receive might be out of date, so performing as many calculations as possible in the server side should be the most accurate. You can find a good article about this here.
* Security: if you let all the physics be done in the client-side, hackers can easily make wall-hacks, for instance.

---
Tags: unity, multiplayer, client-server, smartfox
---


# Question
Title: My character wont shoot when I use GML in Gamemaker
So I was trying to make a top down shooter in Gamemaker and I decided to convert it from Drag and Drop to GML.

I was trying to make my character shoot a projectile when I press mouse left button but for some reason I dont know why I cant get it working.

```
    // Shooting
if keyboard_check (vk_space)
    {if (alarm[0] = -1)
    alarm[0] = 2}

if (alarm [0] = 0)
    {instance_create (x,y,obj_bullet)
    instance_create (x,y,obj_gunshell)
    instance_create (x,y,obj_gunfire)
    audio_play_sound (snd_shoot1,1,false)
    audio_play_sound (snd_shoot2,1,false)
    }

```

Its set on vk\_space for now but it doesnt work when I change it to mouse\_check\_button (mb\_left)

# Answer
> 1 votes
The reason it isn't working with `mouse_check_button(mb_left)` is simply because this function checks whether left mouse button is being pressed continuously. You need to check if mouse button is pressed just once per time: use `mouse_check_pressed(mb_left)`, it'll work fine.

# Answer
> 2 votes
have you tried to do something like this?

```
if keyboard_check (vk_space) || mouse_check_button(mb_left) {...}

```

I think this should work just fine. Let me know if it doesn't

---
Tags: game-maker
---


title: Unity too many batches

text:
# Question
Title: Unity too many batches
There are 64k cubes, 64k-1 's materials are assigned to sharedMaterial of first cube. But unity is not batching them together. Only cubes themselves are batched.

* Static color(but different per cube)
* Dynamic position and rotation per cube

How can I force unity to batch them all so it sends all cube data with only an array then draw once instead of drawing 64k times?

Each cube has a constructor as:

```
public class Test : MonoBehaviour {
    public static System.Random r { get; set; }
    // Use this for initialization
    public static Material m=null;
    void Start () {
        if (r == null)
            r = new System.Random();
        sayac++;
        if (m == null)
            m = GetComponent<Renderer>().sharedMaterial;
        else
            GetComponent<Renderer>().material = m;
        GetComponent<Renderer>().material.color = new Color((float)r.NextDouble(), (float)r.NextDouble(), 1);
        var mesh= GetComponent<MeshFilter>().mesh;
        var vertices  = mesh.vertices;
        var colors  = new Color[vertices.Length];
        var i  = 0;
        while (i < vertices.Length)
        {
            colors[i] = new Color((float)r.NextDouble(), (float)r.NextDouble(), (float)r.NextDouble());
            i++;
        }
        mesh.colors = colors;
        mesh.UploadMeshData(false);
        mesh.Optimize();
    }

}

```

and they are instantiated from a cube as:

```
    for(int i=0;i<1024*64;i++){
        var pos = new Vector3(i % 64, (i /64) % 64, (i / 4096) % 64);
        pos*=2.5f;
        var cu = Instantiate(ref_cu, pos, Quaternion.identity);
        cu .name = "cube_" + i;
    }

```

After deleting 'material.color' lines, batching has started. But now cubes are not easily seen as with different colors. I need them different colored but not changing. Static color but different per cube. How it looks now:

its not easy to see individual cubes.

```
public class Test : MonoBehaviour {
    public static System.Random r { get; set; }
    // Use this for initialization
    public static Material m=null;
    void Start () {
        if (r == null)
            r = new System.Random();
        sayac++;
        if (m == null)
            m = GetComponent<Renderer>().sharedMaterial;
        else
            GetComponent<Renderer>().material = m;

    }

}

```

# Answer
> 5 votes
To answer your original question about why Unity wasn't dynamic batching in this case...

The renderer.material property has a getter that silently creates a unique copy of the material the first time you access it.

This is convenient when you want to change the colour/texture of one instance without that change affecting every other instance in the game. Like this line from your code above:

```
    //                       ↓ Copy happens when you access .material here
    GetComponent<Renderer>().material.color = new Color(
                         (float)r.NextDouble(),
                         (float)r.NextDouble(),
                         1);

```

But once the material has been copied this way, Unity can no longer batch this instance together with other instances using other copies of the material, even if they differ by just a colour parameter.

To avoid copying when accessing a material, you can use renderer.sharedMaterial, but that won't get you unique colours per cube instance.

Your idea of modifying the vertex colours to get unique colours in one batch will work, but you'll need to use a material that reads & displays those vertex colours. This is a different subject from batching, so I recommend posting a new question about rendering vertex colours (or better yet, search to see whether one has already been asked & answered — there's a good chance there's at least one answer to your question already available)

---
Tags: unity, batching
---


# Question
Title: Why does transforming a Vector3 by a Quaternion result in reversed Z?
I'm trying to transform the vector (1, 0, 0) by an orientation unit quaternion, which in XNA should be:

```
Vector3 v = Vector3.Transform(Vector3.Right, Orientation);

```

But this results in the Z value reversed from its expected value—for example, transforming Vector3.Right by Orientation (0.6532815, -0.270598, 0.270598, 0.6532815) results in the vector (0, 0.7071, -0.7071) when it *should* result in the vector (0, 0.7071, 0.7071).

I found another implementation here:

```
Quaternion o = Orientation;
Vector3 oV = new Vector3(o.X, o.Y, o.Z);
Vector3 v = 2 * Vector3.Cross(oV, Vector3.Right);
v = Vector3.Right + o.W * v + Vector3.Cross(oV, v);

```

But that results in the same problem. Reversing the Z value is trivial, but I'm worried that if I don't find a solution to this now the problem will manifest some other way down the road. Especially since, up until now, I thought I was playing by XNA's rules in my game engine (same coordinate system, same handedness).

For reference, this code I wrote *does* produce the expected result in my engine:

```
Vector3 v;
Quaternion o = OrientationGlobal;
double y = Math.Atan2(2 * (o.W * o.Z + o.X * o.Y), 1 - 2 * (o.Z * o.Z + o.Y * o.Y)); // yaw about global Z axis
v.Z = MathHelper.Clamp(2 * (o.W * o.Y - o.Z * o.X), -1, 1);
double m = Math.Sqrt(1 - v.Z * v.Z);
v.X = (float)(m * Math.Cos(y));
v.Y = (float)(m * Math.Sin(y));

```

What am I missing?

# Answer
> 1 votes
Both XNA and Fabian Giesen’s implementation behave correctly. Transforming vector `(1, 0, 0)` by quaternion `(w=0.6532815, x=-0.270598, y=0.270598, z=0.6532815)` does resut in `(0, 0.7071, -0.7071)`. It also does in Unreal Engine, in my own quaternion implementation, as well as in Wolfram Alpha.

Wolfram Alpha also gives the 3×3 matrix equivalent of the quaternion. You can see that multiplying this matrix by `(1, 0, 0)` will also result in `(0, 0.707107, -0.707107)` since it’s trivially the first column of the matrix:

```
|  0         -1  0        |
|  0.707107   0  0.707107 |
| -0.707107   0  0.707107 |

```

There is most certainly a bug in your code above, since every other implementation basically disagrees with it, but it’s hard to understand where, as I have no idea how you derived the formulas. But the use of `atan2` immediately followed by `sin` and `cos` indicates it was probably just some test code so I suggest you just throw it away and trust the XNA implementation.

Ultimately, the problem probably comes from how you build your quaternion. I’d have a look there.

# Answer
> 1 votes
For posterity...it ended up being a simple handedness issue, but only around the Y (pitch) axis. I had it stuck in my head that positive pitch increases Z and negative pitch decreases Z, which isn't true in a right-hand system. Lesson learned!

---
Tags: xna, vector, quaternion
---


# Question
Title: How to desing an RPG system with regard to PVP
When you design a RPG system focused on PVE, one usually goes "mob of level X has Y hp and Z damage". How about when we do PVP with multiple classes?

Lets say we go Diablo, so we have STR/DEX/INT/VIT, how do you balance those between classes? Do I say:

* I want a fight to last 10 rounds on average (lets assume its turn based)
* barb starts with 300 hp, demon hunter 250 hp, wizard 200 hp

And now try to manipulate DPS / health using stats/skills so it matches the "10 round on average" by giving mage a mana shield an a lil bit more damage per fireball than barbarians melee attack? How would You approach this?

# Answer
As Alexandre commented, the best way to go about this is lots of work and testing. There is no simple solution or algorithm that can give you this answer. The tiniest change to any skill, stat, or other variable will directly affect the gameplay.

Your best bet is to just give it whatever values you think will lead to the gameplay you want and tweak them as you see necessary.
> 1 votes

---
Tags: game-design, architecture, rpg
---


# Question
Title: Cannot find declaration of element nifty JME
I'm new to nifty. I am trying to learn how to create nifty GUI in JMonkey Engine game. I'm going through tutorials and tried to run project. Project runs fine but I get following error when I tried to edit xml:

**Cannot find declaration of element nifty**

Below is my start.xml code:

```
<nifty xmlns="http://nifty-gui.sourceforge.net/nifty.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://nifty-gui.sourceforge.net/nifty.xsd http://nifty-gui.sourceforge.net/nifty.xsd">
<useStyles filename="nifty-default-styles.xml" />
<!-- Screen Codes here-->
</nifty>

```

I guess most possible reason is that above namespace might have been deprecated and already been replaced. Or there might be other steps that I have to perform in JME SDK to make it recognize nifty tag. Please Help.

# Answer
> 1 votes
Try the following, tested in JMonkey SDK 3.0:

```
<?xml version="1.0" encoding="UTF-8"?>
<nifty xmlns="http://nifty-gui.sourceforge.net/nifty-1.3.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://nifty-gui.sourceforge.net/nifty-1.3.xsd http://nifty-gui.sourceforge.net/nifty-1.3.xsd">
    <useStyles filename="nifty-default-styles.xml" />
</nifty>

```

---
Tags: jmonkeyengine, nifty-gui
---


# Question
Title: Having issue's with a confusing access violation? - C , OpenGL 3.3+ , SDL 2.0+
Hello this code seems so well done and yet I'm getting this weird access violation error when I use anything but 0 in glShaderSources 2nd argument :

```
glShaderSource( fragshader, 0, fragfilebuff, NULL );

```

If I use lenofstr or any other number then 0 it calls up an error like this :

I have no idea for the life of me why this is happpening I've updated my drivers , I've even tried messing around with glewInit(); too see if it's something to do with that but no luck what so ever.

This nvidia dll has some problem with my code and I don't know why?...

```
void LoadShaders(const char *fragshaderfn, const char *vertshaderfn)
{
    FILE *fragfile;
    const GLchar *fragfilebuff[256] = { 0 };
    fopen_s(&fragfile, fragshaderfn, "r");

    fread(fragfilebuff, sizeof(char), sizeof(char) * 256, fragfile);
    printf(fragfilebuff);

    GLsizei lenofstr = strlen(fragfilebuff);
    printf("this is the length -> %d", lenofstr);

    GLuint fragshader = glCreateShader(GL_FRAGMENT_SHADER);

    glShaderSource(fragshader, 0,
        fragfilebuff, NULL);

    glCompileShader(fragshader);

};

```

Here's the complete source :

```
#include <SDL.h>
#include <GL/glew.h>
#include <SDL_opengl.h>
#include <stdio.h>
#include <conio.h>

#define SCREEN_HEIGHT 480
#define SCREEN_WIDTH 640

SDL_Renderer *mainrenderer;
SDL_Window *mainwindow;
SDL_Event event;
bool running = true;

void LoadShaders(const char *fragshaderfn, const char *vertshaderfn)
{
    FILE *fragfile;
    const GLchar *fragfilebuff[256] = { 0 };
    fopen_s(&fragfile, fragshaderfn, "r");

    fread(fragfilebuff, sizeof(char), sizeof(char) * 256, fragfile);
    printf(fragfilebuff);

    GLsizei lenofstr = strlen(fragfilebuff);
    printf("this is the length -> %d", lenofstr);

    GLuint fragshader = glCreateShader(GL_FRAGMENT_SHADER);

    glShaderSource(fragshader, lenofstr,
        fragfilebuff, NULL);

    glCompileShader(fragshader);

};

int main(int argc , char **argv)
{
    SDL_Init(SDL_INIT_EVERYTHING);

    mainwindow = SDL_CreateWindow(
        "C OpenGL Engine",
        300, 300, 640, 480,
        SDL_WINDOW_SHOWN | SDL_WINDOW_OPENGL );

    SDL_GLContext maincontext = SDL_GL_CreateContext(mainwindow);
    SDL_GL_MakeCurrent(mainwindow, maincontext);

    glewExperimental = GL_TRUE;
    GLenum err = glewInit();

    if (GLEW_OK != err)
    {
        /* Problem: glewInit failed, something is seriously wrong. */
        fprintf(stderr, "Error: %s\n", glewGetErrorString(err));
    }
    fprintf(stdout, "Status: Using GLEW %s\n", glewGetString(GLEW_VERSION));

    if (SDL_GL_SetSwapInterval(1) < 0)
    {
        printf("Warning: Unable to set VSync! SDL Error: %s\n", SDL_GetError());
    }

    LoadShaders("ffile.frag", "");

    glClearColor(0.0, 0.0, 0.0, 1.0);

    while (running == true)
    {
        while (SDL_PollEvent(&event))
        {
            switch (event.type)
            {
                case SDL_QUIT:
                    SDL_GL_DeleteContext(maincontext);
                    SDL_Quit();

                    return 0;
                break;
            }
        }

        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );

        SDL_GL_SwapWindow(mainwindow);
    }

    SDL_GL_DeleteContext(maincontext);
    SDL_DestroyWindow(mainwindow);
    SDL_Quit();
    return 0;
}

```

All help would be appreciated I am using C , SDL 2.0 and OpenGL 3.3+ , MSVC 2015 , Win10 64bit

# Answer
```
void glShaderSource(GLuint shader,
    GLsizei count,
    const GLchar **string,
    const GLint *length);

```

Okay, I guess you didn't understand what these values mean. string is an "array"(pointer is more correct since a pointer is not an array) of "char const\*" (I advice you to put all your code in one and only one char const \*.

length is an "array" of int. Each values inside this "array" should be set at the length of the respective "char const\*" in "string".

Count is just the number of char const\* and int you have in both array above.

So, I'd go for that :

```
char const *code = getStringFromFile(path);
int length = strlen(code);
glShaderSource(shader, 1, &code, &length);

```

That should work :)

the getStringFromFile(path) could be done like this:

```
const char *getStringFromFile(char const *path) {
    FILE *file = fopen(path, "ab"); // open the file at the end and binary
    int length = ftell(file); // Ask the size of the file
    fseek(file, 0, SEEK_SET); // return to the beginning of the file
    char *buffer = calloc(length + 1, sizeof(char)); // alloc the buffer with the end 0
    fread(buffer, sizeof(char), length, file); // read the file
    fclose(file);
    return buffer;
}

```

This code may countain error, I didn't test it, but the idea is here
> 4 votes

---
Tags: opengl, sdl, c
---


# Question
Title: Is it illegal to use a commercial song in your game (that you intend to sell)
If I were to buy, say this song: http://www.youtube.com/watch?v=3fumBcKC6RE, strip/find/get the instrumental, and use that instrumental in a game I'm making, as a theme, say for a recurring boss fight, and then sell this game, would this be illegal?

This is hypothetically speaking.

# Answer
> 26 votes
I am not a lawyer and this is not considered legal advice.

**Yes it would be illegal.** You have to contact the owner of the song, and work out licensing details. It is likely to be very expensive.

# Answer
> 7 votes
Just to add to some of the existing answers. As many have already pointed out, using a copyrighted song without securing a proper sync license would be considered a copyright infringement and can get you into trouble.

Getting sync license for a popular song can be pretty pricey or even impossible (unlike mechanical licenses, sync licenses are not compulsory and you are at the mercy of the copyright owner).

If you can't get the sync license for the song you want, few other options are:

1. Hire a musician to re-create the instrumental version and secure the synchronization license with the song publisher.
2. Hire a musician to make a "sound-alike" track. That is, something that sounds close enough without infringing the copyright.
3. Look for similar royalty-free or creative commons music. Check out this directory for many links to royalty-free marketplaces and free music: http://www.safemusiclist.com

Disclaimer: I am musician, not a lawyer. If in doubt, consult an attorney.

# Answer
> 2 votes
Although I'm not a lawyer, my understanding is: The illegality depends on a number of factors, including, but not limited to, the following:

* Jurisdiction (e.g., copyright laws aren't enforceable globally because many countries don't recognize intellectual property rights that were not granted within their borders, plus there are also some countries don't even have copyright laws)
* Permission (when using someone else's copyrighted material, you must first obtain their permission if you don't want to open yourself up to potential litigation {getting sued})
* Court judgement (a judgement must be provided by a court to determine if a violation of someone's intellectual property rights occurred, after which point court-sanctioned penalties may be applied)

In essence, the owner of the intellectual property has to take steps to protect their rights. If apparent violations are permitted, but no attempts are ever made to stop these violations, then others may \[reasonably\] conclude that these are not really violations (e.g., they were used with permission that was granted privately, which is normally how these things are handled).

So, **the answer is: Maybe** -- it might be illegal in that it could be a violation of intellectual property laws, and you'd need to ask someone qualified with the relevant legal expertise (such as a lawyer), on a case-by-case basis, if you were unable to get an answer from the copyright holder.

# Answer
> 2 votes
I also am not a lawyer, but the term is "express permission" so if you go researching that's what you'll need to search on. The common use is something like this: "It means that permission was clearly given, that in lieu of permission there is no permission at all."

In the not a lawyer vein, copyright is not something that must be protected (like trademark) but it is something that can be enforced.

Think of this the other way around, would it be right if the guys who wrote and performed that song started giving away your game for free to anyone who liked their music? Probably not.

# Answer
> 1 votes
Yep, you cannot use any sound without expressed permission from the rightful creator the content. This basically applies to the vast majority of the content you find on the internet.

# Answer
> 1 votes
Might I suggest looking into free alternatives.

There is plenty of Creative Commons licensed content. You can find ones that are licensed without the NC (No Commercial Use) clause. For example CC-BY just requires credit to be given. I'm not sure if the SA, Share Alike license is usable with a commercial game (it might require the game to be under the same license which basically would stop it being commercial, or maybe the license only applies to the song and any changes you make to that song).

Also there are public domain songs available. Most of them will be really outdated (ie older that 75 years), or educational type stuff. They could be used for certain styles of games. Check out: http://www.pdinfo.com/

Archive.org should have stuff for both CC and PD (although I can't get the search to return results for any decent queries related to licensed music).

I have also noticed that indie gamedevs have licensed content from some well known (well for the genre) ambient/trance music producers. Jon Hopkins was used in Vessel and Capsized used music from Solar Fields (They did the Mirror's Edge theme too). Might be worth looking into how the indie devs go about that, maybe a producers have a indie game friendly licensing system.

# Answer
> 0 votes
You should look for some 'open-source' music and/or sounds. Most of them require you to get a license from the author and pay them in some way, but there are some that you might be able to use for just a mention in the credits.

Either way, those musicians would probably be a lot easier to talk to and make a reasonable arrangement with than most mainstream music authors.

# Answer
> 0 votes
Briefly, if the rights holder doesn't specify the release of the rights in written format (on-line or documented to you) you cannot use a music piece in any way, neither commercially nor non-commercially.

* Buying a song only gives the right to listen to that song not to use elsewhere.
* If you use the recording itself, you need to get permission from the sound recording rights owner.
* If you recreate the music you need to get permission from the publisher, or the author, or both.
* Commercial or non-commercial use has nothing to do with what rights you have.
* Instrumental parts are also written and recorded by someone who holds rights to use.
* There may be other parties you need to get permission as well.

# Answer
> 0 votes
I believe you would violate laws not once but plenty of times doing so.

Copyrights laws are mostly approved all over the world. Independently from where you live, they are mostly the same. For more details, google can point you to the correct site for your country.

A song can't be redistributed, in any form or shape, unless approved by whoever retain rights for that song (producer, composer, group, whoever is). Listening on the radio, means that the radio station paid the rights to play it, and you can only listen to it...ripping it, like you do with youtube videos, is a violation

Take out part of the song, is also illegal; "sampling", which is the term used to get a piece of a song to make a loop (like some hip hop artists loved to do in the past), is legal only if you have the authorization; 2nd infraction.

Then you want to strip the instrumental track, which beside being pretty difficult, since the instrumental track is merged with vocals and back chorus, but even if a software does extract it for you; this is yet another infringment of the law; unless you are authorized to do so (in which case, you would get directly the instrumental track from the producer, they record in multiple tracks for flexibility).

At last, after that you broke 3 times the copyright law; you put it in your product, without authorization, which is the 4h and last infraction.

* ripping is illegal
* sampling is illegal
* modify a song to extract the instrumental track is illegal
* use a song or part of it is illegal

Solutions: either make your own loops, hire a musician to write the score or request the artist permission; unless you deal with U2 or Metallica, indie artists are friendly people, that may even end up giving you the rights in exchange of a bit of royalties based on your sales.

# Answer
> -1 votes
The simple fact is that every source of music you use for your game has copyright on it, and believe me, you can get lots of problems with those companies. Especially companies like Universal or VEVO can really get you into trouble.

As said above you can use open-source music and/or soundeffects. Maybe it's a nice thing to buy FruityLoops 9, you can create techno music, and even other cool game music with it: it's not easy but it's worth a try.

If you really want this music you can ask the producers politely for permission, but then I think you should really buy a license...

For the last, but not least: I recommend you to not use music from commericials or anything simular to that. The player is thinking of that "maybe sucking commercial" when he/she plays the game.

---
Tags: legal, game-industry, music, copyright
---


# Question
Title: Scale one object to be cover multiple other objects
I have placed and aligned several objects next to each other. For the sake of understanding, lets just say I placed 10 cubes next to each other. I snapped them all together (Move-\>V-\>Click&Drag). The cubes look great so far. Now I want to make a plane in front of the cubes, that has exactly the width of the cubes altogether.

Now, I can place a new plane in front of the, no problem. I can snap a single edge to the cube on the most right, also no problem.

But now, how can I make the size exactly the same as all the cubes together? Sure, I could eyeball it from top view, an **kind of** make it about the same size, but chances are, it's a little bit too short or too long.

Isn't there a possibility to snap one edge, lock it, and snap another edge making the object scale automatically to the desired width?

# Answer
> 1 votes
I can't think of a way to do exactly that. But maybe you can snap one edge and calculate the exact size you need the large cube to be by adding the sizes and distances (if they're not all snapped to each other) of the smaller cubes.

This could work if you just want it to be static, meaning setting it up once and never resizing or moving the smaller cubes.

If they will be moving around or changing size, I can only think of resizing the larger cube by scripting.

HTH but if it doesn't maybe give a bit more detail about how you'll be using the cubes and you can get better answers.

---
Tags: unity, scale
---


# Question
Title: How to prevent players from getting lost during the onboarding phase of an RPG?
I've created a new RPG and tested it with some players. They like it, but get lost at certain points.

For example, I'm using hotkeys to open modals, `T` to talk, and other buttons that do various things. Moreover, some of the quests aren't entirely clear.

To fix this, I'm trying to think of a good onboarding approach.

I'm implementing three methods for onboarding:

1) **Cutscenes**: The cutscenes, especially the opening scene, will give the backstory and explain where they are

2) **The NPC dialog**: Through conversations with NPCs, they will give hints as to what you should do. Right now, I include, somewhat awkwardly, things like:

> "Hi there, I'm Bob. You can press T to talk".

3) **Onscreen Tooltips**: These blink on screen until the player completes the current onboarding task. For example, the tooltip disappears when the player clicks their minimap:

I'm looking for a more cohesive strategy for onboarding users to the game, or good tutorials for this. Two things I'm weary of are:

* I don't want to be overbearing with help, and am attempting a good Discovery Phase to let the player explore.
* I don't want the player to leave the game out of frustration with being lost

I've seen a lot of techniques for various game genres, and even things like Google apps, where they have a `glowing choice` for the user to click on. I'm a sole developer, and some of these techniques seem quite complicated to implement.

Thanks!

# Answer
Good tutorials are tricky.

**Cutscenes** can be nice, but try to avoid too much infodumping. A long-standing rule of storytelling is "show, don't tell". It is usually better to tell the player almost nothing about the world beforehand and introduce the background as they play. Take, for example, the first hour of *Half Life 2*. There is a short intro cutscene, but it is so cryptic it tells the player absolutely nothing. But then the player walks through the world and learns that the game takes place in a run-down city occupied by a technologically advanced and oppressive power just by looking around and interacting with the environment / having the environment interact with them. This interactive introduction through which the player *experiences* the backstory and the scenario of the game is far more immersive, engaging and most of all **easier to remember** than just telling them all of that in a cutscene.

A good non-interactive intro custcene, on the other hand, should be visually impressive and emotionally engaging, but rather *raise* questions about what is going on than *answering* them. The usual reaction you aim for when writing one is that the player asks "What the heck did I just watch?" after seeing it for the first time but then think "ah, so that's what this was all about" after they played half the game. A good example is the one from the RPG Arcanum from 2001. *There is a knight with a magic sword. There is another knight. They seem to want to fight. Who are they? Where are they? What are they fighting about? No answer. And then one of them... draws a gun?!? What's that travesty!?! Knights are supposed to have swords, not guns. Explain yourself, game!* But after playing the game for a while you realize that this is a world in which a knight can indeed carry either a magic sword or a gun and both are reasonable weapon choices.

**Dialogs**: First of all, it is not bad when tutorials break the fourth wall a bit. When you can do it in-character, great. But sometimes you need to tell the player about the buttons in front of them. You can do that by separating the in-character and out-of-character information visually. For example, have a character say "Talk to me when you need anything" and then have a disembodied screen overlay reading "Press T to talk". When you try to do everything in-character you end up with awkward dialog where people living in your game world talk about buttons which only exist in the real world. This breaks the immersion far more violently than a user-interface where the player is aware that only they see it and it's invisible to the characters in the game.

**Players getting lost:** You should avoid giving the player too much freedom during the discovery phase. Even when you prefer a more open-world experience, you should keep holding the player's hand while they still learn the game mechanics. Introduce one mechanic after another and do not let the player continue to the next before they've shown that they understand it. A common beginner mistake when developing RPGs is throwing the player into a too large scenario (both spatially and narratively) while they are still busy learning controls and mechanics and don't have any attention to spare on understanding the world around them. The first scenarios you put the player into should be small and linear. Have them "earn their freedom". Reward them with gradually larger and more complex scenarios with more freedom of movement and more narrative complexity. Do not set them free completely before they are familiar with all your core game mechanics and the basic story premises.

Also make sure that the player always has something to do and knows what it is. In an open-world RPG a quest-log can be a good tool to achieve this.
> 1 votes

# Answer
Tutorials are hard and I've been trying to find a good way to make them for a while now. My number one recommendation is to look at games that have found a way of fixing this problem. I would start at Portal 1. The games first levels were really all tutorials but no one noticed. I also think that you should watch this Youtube video: https://www.youtube.com/watch?v=BCPcn-Q5nKE I'm not sure if I'm allowed to post this but I did. I hope I helped. Best of luck to your game
> 0 votes

---
Tags: game-design, rpg, tutorials
---


# Question
Title: Can I use my self made piano version of a popular copyrighted song as my game background music?
I am making a game, the theme of the game is kind of romantic, and I, myself, have made a piano version of a modern pop song that would fit with that theme. The song in question is still under copyright, and I'm not the owner of the copyright.

Can I use it as a background in my game? Would there be any legal issue regarding copyright/IP etc?

# Answer
> 4 votes
It's not just the arrangement and interpretation of a song which falls under copyright but also the composition itself. So you will violate the copyright of the original composer. That means you will either have to compose your own song, use a song which was released by the author under free terms or on which the copyright has expired.

When you are looking for well-known, sad-romantic piano song which is in the public domain, then how about Beethoven's For Elise?

# Answer
> 1 votes
You most likely will be violating the copyright. Given that it's for a commercial purpose it won't fall under fair use.

You can get around that by looking who owns the rights to the song and negotiating a license for its use in your game. This would be the "record label" company which you can easily find out with a little bit of research. (For this particular song wikipedia lists Columbia Records and Epic Records both owned by Sony Music Entertainment).

---
Tags: legal, copyright, music
---