# Question
Title: Cannot use imported image with Unity's UI controls
I know this question sounds banal but its a problem.

I received a project and opened it.

Now I try to edit it by adding my own images.

I do the import but the image does not show up when selecting images, for example, for a button:

What is the correct folder in this case?

# Answer
Your png is most likely not set to be imported as a sprite, and the property you want to use it in requires a sprite (background, checkmark and the others are by default sprites).

Click on your png to open up the import settings. The *Texture Type* dropdown menu is the interesting part here. Set it to *Sprite*, apply the changes and your sprite-ified png should now appear as selectable for your UI elements.

While at it, read about how it is possible to use raw textures for UI work (not sprites), and how this affects performance and should only be used in certain situations. Start here: http://docs.unity3d.com/460/Documentation/ScriptReference/UI.RawImage.html
> 4 votes

---
Tags: unity
---


# Question
Title: [Unity]Avoid boucing when ground move down
I have a sphere & a quad, when the quad move down, the sphere fall after and bounce back continuously. I dont want to change my project setting like bounciness, gravity,mass and I need the sphere to move freely to jump between quad. How can I do this, thanks

# Answer
You can play with the physics material of your sphere (or quad, depends on which one makes more sense) in order to remove the bounciness.

If you want to achieve an effect that would not normally be possible in the real life (as in following a moving platform without inertia) you will need an extra layer that will manage this between the two shapes, working closely with the Unity physics engine.

The physics material documentation is here: http://docs.unity3d.com/Manual/class-PhysicMaterial.html

If you want to get more information on this topic you will need to extend your question with a demo of what is happening (video would work) and some info about the object configurations (what components are you using and so on).
> 1 votes

# Answer
not sure how your gravity works in unity but in our jump and run we did years ago we checked if the player touched a moving platform and glued him on it unless the player jumps again. you could do this calling the physic system manually until the player touches the platform again or you just add the player in your scene graph to the platform. it was a very simple game though and didn't use any other physical simulation other than falling down.
> 0 votes

---
Tags: unity, physics
---


# Question
Title: Weird windowed resolution - can't seem to change without changing the name
My game is windowed, and when I set the resolution in the build settings (960x540 - 16:9 - Windows standalone), and build it, it works as intended, but from then on, I can no longer change the resolution (can change it in the editor, and it also saves, but when I build it, it is still the original res (960x540))unless I change the Product Name as well. When I change the product name, I can change the resolution, build it, and it will change, but then it is stuck as well. When I change back to the first name, the resolution automatically change it the resolution for the first name (960x540) (it doesn't show up in the editor, only when you build it.)

So basically:

```
Name1
960x540

Name2
1280x720

Name3
1024x576

etc

```

So you can change the resolution every time you change the name and build it, and that name is stuck with that resolution (no matter what you change it to in the editor later). I am fairly new with unity, so am I missing something very basic here?

Thanks for any help!

# Answer
Normally, once the project is build, if you target windows platforms you will get a dialog to select the resolution at startup.

This is optionally since you can disable it and create your own mechanism for managing screen resolution at runtime using the provided API Screen.SetResolution.
> 1 votes

---
Tags: unity, resolution
---


# Question
Title: Voxel Engine in XNA - Block as Class Renders, Block as Struct Doesn't
Edit: I almost forgot to mention - when I place NEW blocks they render, but nothing triggers the originals to render (I have a button assigned to recalculate/redraw for every block surrounding (and including) the currently moused-over one).

I've got a voxel engine that I've been working on for some time, and while developing core features I wasn't too concerned with performance yet. Everything runs pretty quick, but it was eating memory, so one of the obvious things I could do was change my block from a class to a struct (post-changes code below). The most annoying thing was the lack of null comparisons, as I'd used those all over, so I created an "Air" type and used that instead. However, when I was all done making the changes, all blocks were invisible - mousing over them still shows the name/health of the block, I can still jump on them and watch my coordinates change, but they do not render. If I literally just change the single word "struct" to "class" with no other modifications the blocks render properly again. My guess is something in my block struct isn't valid for use with a struct even though it doesn't generate syntax errors? I'm really not sure where the issue lies here, as I've never used structs for mass data storage like this before (in-memory or on-disk sequential mapping, on the other hand, a lot). If you need to see other code, let me know, but I'd suspect the issue is here or else is a fundamental/conceptual thing that seeing the code won't help find..

```
[DataContract, StructLayout(LayoutKind.Sequential), Serializable]
public struct Block : ICollidable3, ISerializable
{
    private static ulong _nextID = 0;
    [DataMember]
    public ulong ID;

    public bool IsAir
    {
        get
        {
            return Type == BlockType.Get("Air");
        }
    }

    public static Block AirBlock = new Block(Vec3.Zero, BlockType.Get("Air"));

    [DataMember]
    private Vec3 _position;
    public Vec3 Position
    {
        get
        {
            return _position;
        }
        set
        {
            _position = value;
            BoundingBox = new Microsoft.Xna.Framework.BoundingBox(_position - HalfSize, _position + HalfSize);
        }
    }
    public float Size
    {
        get
        {
            return HalfSize * 2;
        }
        set
        {
            HalfSize = value / 2;
        }
    }
    [DataMember]
    public float HalfSize;
    [DataMember]
    public float Yaw;
    [DataMember]
    public float Pitch;
    [DataMember]
    public float Roll;

    [DataMember]
    private BoundingBox _boundingBox;
    public BoundingBox BoundingBox
    {
        get
        {
            return _boundingBox;
        }
        set
        {
            _boundingBox = value;
        }
    }

    public static Plane NegXPlane = new Plane(-1, 0, 0, 0);
    public static Plane PosYPlane = new Plane(0, -1, 0, 0);
    public static Plane PosZPlane = new Plane(0, 0, -1, 0);
    public static Plane PosXPlane = new Plane(1, 0, 0, 1);
    public static Plane NegYPlane = new Plane(0, 1, 0, 1);
    public static Plane NegZPlane = new Plane(0, 0, 1, 1);

    #region Vertices
    static float ao = .65f;

    public LitTextureVertex[] NegXVertices
    {
        get
        {
            if (Flips.HasFlag(Faces.NegX)) return new LitTextureVertex[6]
            {
                new LitTextureVertex(Position + HalfSize * Vec3.NPP, -Vec3.UnitX, Type.TexSideX, NegXOcclusion.HasFlag(FaceCorners.X) ? ao : 0, Type.Material.Reflectivity),
                new LitTextureVertex(Position + HalfSize * Vec3.NPN, -Vec3.UnitX, Type.TexSideY, NegXOcclusion.HasFlag(FaceCorners.Y) ? ao : 0, Type.Material.Reflectivity),
                new LitTextureVertex(Position + HalfSize * Vec3.NNP, -Vec3.UnitX, Type.TexSideW, NegXOcclusion.HasFlag(FaceCorners.W) ? ao : 0, Type.Material.Reflectivity),
                new LitTextureVertex(Position + HalfSize * Vec3.NPN, -Vec3.UnitX, Type.TexSideY, NegXOcclusion.HasFlag(FaceCorners.Y) ? ao : 0, Type.Material.Reflectivity),
                new LitTextureVertex(Position + HalfSize * Vec3.NNN, -Vec3.UnitX, Type.TexSideZ, NegXOcclusion.HasFlag(FaceCorners.Z) ? ao : 0, Type.Material.Reflectivity),
                new LitTextureVertex(Position + HalfSize * Vec3.NNP, -Vec3.UnitX, Type.TexSideW, NegXOcclusion.HasFlag(FaceCorners.W) ? ao : 0, Type.Material.Reflectivity),
            };
            else return new LitTextureVertex[6]
            {
                new LitTextureVertex(Position + HalfSize * Vec3.NNN, -Vec3.UnitX, Type.TexSideZ, NegXOcclusion.HasFlag(FaceCorners.Z) ? ao : 0, Type.Material.Reflectivity),
                new LitTextureVertex(Position + HalfSize * Vec3.NPP, -Vec3.UnitX, Type.TexSideX, NegXOcclusion.HasFlag(FaceCorners.X) ? ao : 0, Type.Material.Reflectivity),
                new LitTextureVertex(Position + HalfSize * Vec3.NPN, -Vec3.UnitX, Type.TexSideY, NegXOcclusion.HasFlag(FaceCorners.Y) ? ao : 0, Type.Material.Reflectivity),
                new LitTextureVertex(Position + HalfSize * Vec3.NNN, -Vec3.UnitX, Type.TexSideZ, NegXOcclusion.HasFlag(FaceCorners.Z) ? ao : 0, Type.Material.Reflectivity),
                new LitTextureVertex(Position + HalfSize * Vec3.NNP, -Vec3.UnitX, Type.TexSideW, NegXOcclusion.HasFlag(FaceCorners.W) ? ao : 0, Type.Material.Reflectivity),
                new LitTextureVertex(Position + HalfSize * Vec3.NPP, -Vec3.UnitX, Type.TexSideX, NegXOcclusion.HasFlag(FaceCorners.X) ? ao : 0, Type.Material.Reflectivity),
            };
        }
    }

    public LitTextureVertex[] NegYVertices
    {
        get
        {
            if (Flips.HasFlag(Faces.NegY)) return new LitTextureVertex[6]
            {
                new LitTextureVertex(Position + HalfSize * Vec3.NNN, -Vec3.UnitY, Type.TexBottomX, NegYOcclusion.HasFlag(FaceCorners.X) ? ao : 0, Type.Material.Reflectivity),
                new LitTextureVertex(Position + HalfSize * Vec3.PNN, -Vec3.UnitY, Type.TexBottomY, NegYOcclusion.HasFlag(FaceCorners.Y) ? ao : 0, Type.Material.Reflectivity),
                new LitTextureVertex(Position + HalfSize * Vec3.NNP, -Vec3.UnitY, Type.TexBottomW, NegYOcclusion.HasFlag(FaceCorners.W) ? ao : 0, Type.Material.Reflectivity),
                new LitTextureVertex(Position + HalfSize * Vec3.PNN, -Vec3.UnitY, Type.TexBottomY, NegYOcclusion.HasFlag(FaceCorners.Y) ? ao : 0, Type.Material.Reflectivity),
                new LitTextureVertex(Position + HalfSize * Vec3.PNP, -Vec3.UnitY, Type.TexBottomZ, NegYOcclusion.HasFlag(FaceCorners.Z) ? ao : 0, Type.Material.Reflectivity),
                new LitTextureVertex(Position + HalfSize * Vec3.NNP, -Vec3.UnitY, Type.TexBottomW, NegYOcclusion.HasFlag(FaceCorners.W) ? ao : 0, Type.Material.Reflectivity),
            };
            else return new LitTextureVertex[6]
            {
                new LitTextureVertex(Position + HalfSize * Vec3.PNP, -Vec3.UnitY, Type.TexBottomZ, NegYOcclusion.HasFlag(FaceCorners.Z) ? ao : 0, Type.Material.Reflectivity),
                new LitTextureVertex(Position + HalfSize * Vec3.NNN, -Vec3.UnitY, Type.TexBottomX, NegYOcclusion.HasFlag(FaceCorners.X) ? ao : 0, Type.Material.Reflectivity),
                new LitTextureVertex(Position + HalfSize * Vec3.PNN, -Vec3.UnitY, Type.TexBottomY, NegYOcclusion.HasFlag(FaceCorners.Y) ? ao : 0, Type.Material.Reflectivity),
                new LitTextureVertex(Position + HalfSize * Vec3.PNP, -Vec3.UnitY, Type.TexBottomZ, NegYOcclusion.HasFlag(FaceCorners.Z) ? ao : 0, Type.Material.Reflectivity),
                new LitTextureVertex(Position + HalfSize * Vec3.NNP, -Vec3.UnitY, Type.TexBottomW, NegYOcclusion.HasFlag(FaceCorners.W) ? ao : 0, Type.Material.Reflectivity),
                new LitTextureVertex(Position + HalfSize * Vec3.NNN, -Vec3.UnitY, Type.TexBottomX, NegYOcclusion.HasFlag(FaceCorners.X) ? ao : 0, Type.Material.Reflectivity),
            };
        }
    }

    public LitTextureVertex[] NegZVertices
    {
        get
        {
            if (Flips.HasFlag(Faces.NegZ)) return new LitTextureVertex[6]
            {
                new LitTextureVertex(Position + HalfSize * Vec3.NPN, -Vec3.UnitZ, Type.TexSideX, NegZOcclusion.HasFlag(FaceCorners.X) ? ao : 0, Type.Material.Reflectivity),
                new LitTextureVertex(Position + HalfSize * Vec3.PPN, -Vec3.UnitZ, Type.TexSideY, NegZOcclusion.HasFlag(FaceCorners.Y) ? ao : 0, Type.Material.Reflectivity),
                new LitTextureVertex(Position + HalfSize * Vec3.NNN, -Vec3.UnitZ, Type.TexSideW, NegZOcclusion.HasFlag(FaceCorners.W) ? ao : 0, Type.Material.Reflectivity),
                new LitTextureVertex(Position + HalfSize * Vec3.PPN, -Vec3.UnitZ, Type.TexSideY, NegZOcclusion.HasFlag(FaceCorners.Y) ? ao : 0, Type.Material.Reflectivity),
                new LitTextureVertex(Position + HalfSize * Vec3.PNN, -Vec3.UnitZ, Type.TexSideZ, NegZOcclusion.HasFlag(FaceCorners.Z) ? ao : 0, Type.Material.Reflectivity),
                new LitTextureVertex(Position + HalfSize * Vec3.NNN, -Vec3.UnitZ, Type.TexSideW, NegZOcclusion.HasFlag(FaceCorners.W) ? ao : 0, Type.Material.Reflectivity),
            };
            else return new LitTextureVertex[6]
            {
                new LitTextureVertex(Position + HalfSize * Vec3.PNN, -Vec3.UnitZ, Type.TexSideZ, NegZOcclusion.HasFlag(FaceCorners.Z) ? ao : 0, Type.Material.Reflectivity),
                new LitTextureVertex(Position + HalfSize * Vec3.NPN, -Vec3.UnitZ, Type.TexSideX, NegZOcclusion.HasFlag(FaceCorners.X) ? ao : 0, Type.Material.Reflectivity),
                new LitTextureVertex(Position + HalfSize * Vec3.PPN, -Vec3.UnitZ, Type.TexSideY, NegZOcclusion.HasFlag(FaceCorners.Y) ? ao : 0, Type.Material.Reflectivity),
                new LitTextureVertex(Position + HalfSize * Vec3.PNN, -Vec3.UnitZ, Type.TexSideZ, NegZOcclusion.HasFlag(FaceCorners.Z) ? ao : 0, Type.Material.Reflectivity),
                new LitTextureVertex(Position + HalfSize * Vec3.NNN, -Vec3.UnitZ, Type.TexSideW, NegZOcclusion.HasFlag(FaceCorners.W) ? ao : 0, Type.Material.Reflectivity),
                new LitTextureVertex(Position + HalfSize * Vec3.NPN, -Vec3.UnitZ, Type.TexSideX, NegZOcclusion.HasFlag(FaceCorners.X) ? ao : 0, Type.Material.Reflectivity),
            };
        }
    }

    public LitTextureVertex[] PosZVertices
    {
        get
        {
            if (Flips.HasFlag(Faces.PosZ)) return new LitTextureVertex[6]
            {
                new LitTextureVertex(Position + HalfSize * Vec3.PPP, Vec3.UnitZ, Type.TexSideX, PosZOcclusion.HasFlag(FaceCorners.X) ? ao : 0, Type.Material.Reflectivity),
                new LitTextureVertex(Position + HalfSize * Vec3.NPP, Vec3.UnitZ, Type.TexSideY, PosZOcclusion.HasFlag(FaceCorners.Y) ? ao : 0, Type.Material.Reflectivity),
                new LitTextureVertex(Position + HalfSize * Vec3.PNP, Vec3.UnitZ, Type.TexSideW, PosZOcclusion.HasFlag(FaceCorners.W) ? ao : 0, Type.Material.Reflectivity),
                new LitTextureVertex(Position + HalfSize * Vec3.NPP, Vec3.UnitZ, Type.TexSideY, PosZOcclusion.HasFlag(FaceCorners.Y) ? ao : 0, Type.Material.Reflectivity),
                new LitTextureVertex(Position + HalfSize * Vec3.NNP, Vec3.UnitZ, Type.TexSideZ, PosZOcclusion.HasFlag(FaceCorners.Z) ? ao : 0, Type.Material.Reflectivity),
                new LitTextureVertex(Position + HalfSize * Vec3.PNP, Vec3.UnitZ, Type.TexSideW, PosZOcclusion.HasFlag(FaceCorners.W) ? ao : 0, Type.Material.Reflectivity),
            };
            else return new LitTextureVertex[6]
            {
                new LitTextureVertex(Position + HalfSize * Vec3.NNP, Vec3.UnitZ, Type.TexSideZ, PosZOcclusion.HasFlag(FaceCorners.Z) ? ao : 0, Type.Material.Reflectivity),
                new LitTextureVertex(Position + HalfSize * Vec3.PPP, Vec3.UnitZ, Type.TexSideX, PosZOcclusion.HasFlag(FaceCorners.X) ? ao : 0, Type.Material.Reflectivity),
                new LitTextureVertex(Position + HalfSize * Vec3.NPP, Vec3.UnitZ, Type.TexSideY, PosZOcclusion.HasFlag(FaceCorners.Y) ? ao : 0, Type.Material.Reflectivity),
                new LitTextureVertex(Position + HalfSize * Vec3.NNP, Vec3.UnitZ, Type.TexSideZ, PosZOcclusion.HasFlag(FaceCorners.Z) ? ao : 0, Type.Material.Reflectivity),
                new LitTextureVertex(Position + HalfSize * Vec3.PNP, Vec3.UnitZ, Type.TexSideW, PosZOcclusion.HasFlag(FaceCorners.W) ? ao : 0, Type.Material.Reflectivity),
                new LitTextureVertex(Position + HalfSize * Vec3.PPP, Vec3.UnitZ, Type.TexSideX, PosZOcclusion.HasFlag(FaceCorners.X) ? ao : 0, Type.Material.Reflectivity),
            };
        }
    }

    public LitTextureVertex[] PosXVertices
    {
        get
        {
            if (Flips.HasFlag(Faces.PosX)) return new LitTextureVertex[6]
            {
                new LitTextureVertex(Position + HalfSize * Vec3.PPN, Vec3.UnitX, Type.TexSideX, PosXOcclusion.HasFlag(FaceCorners.X) ? ao : 0, Type.Material.Reflectivity),
                new LitTextureVertex(Position + HalfSize * Vec3.PPP, Vec3.UnitX, Type.TexSideY, PosXOcclusion.HasFlag(FaceCorners.Y) ? ao : 0, Type.Material.Reflectivity),
                new LitTextureVertex(Position + HalfSize * Vec3.PNN, Vec3.UnitX, Type.TexSideW, PosXOcclusion.HasFlag(FaceCorners.W) ? ao : 0, Type.Material.Reflectivity),
                new LitTextureVertex(Position + HalfSize * Vec3.PPP, Vec3.UnitX, Type.TexSideY, PosXOcclusion.HasFlag(FaceCorners.Y) ? ao : 0, Type.Material.Reflectivity),
                new LitTextureVertex(Position + HalfSize * Vec3.PNP, Vec3.UnitX, Type.TexSideZ, PosXOcclusion.HasFlag(FaceCorners.Z) ? ao : 0, Type.Material.Reflectivity),
                new LitTextureVertex(Position + HalfSize * Vec3.PNN, Vec3.UnitX, Type.TexSideW, PosXOcclusion.HasFlag(FaceCorners.W) ? ao : 0, Type.Material.Reflectivity),
            };
            else return new LitTextureVertex[6]
            {
                new LitTextureVertex(Position + HalfSize * Vec3.PNP, Vec3.UnitX, Type.TexSideZ, PosXOcclusion.HasFlag(FaceCorners.Z) ? ao : 0, Type.Material.Reflectivity),
                new LitTextureVertex(Position + HalfSize * Vec3.PPN, Vec3.UnitX, Type.TexSideX, PosXOcclusion.HasFlag(FaceCorners.X) ? ao : 0, Type.Material.Reflectivity),
                new LitTextureVertex(Position + HalfSize * Vec3.PPP, Vec3.UnitX, Type.TexSideY, PosXOcclusion.HasFlag(FaceCorners.Y) ? ao : 0, Type.Material.Reflectivity),
                new LitTextureVertex(Position + HalfSize * Vec3.PNP, Vec3.UnitX, Type.TexSideZ, PosXOcclusion.HasFlag(FaceCorners.Z) ? ao : 0, Type.Material.Reflectivity),
                new LitTextureVertex(Position + HalfSize * Vec3.PNN, Vec3.UnitX, Type.TexSideW, PosXOcclusion.HasFlag(FaceCorners.W) ? ao : 0, Type.Material.Reflectivity),
                new LitTextureVertex(Position + HalfSize * Vec3.PPN, Vec3.UnitX, Type.TexSideX, PosXOcclusion.HasFlag(FaceCorners.X) ? ao : 0, Type.Material.Reflectivity),
            };
        }
    }

    public LitTextureVertex[] PosYVertices
    {
        get
        {
            if (Flips.HasFlag(Faces.PosY)) return new LitTextureVertex[6]
            {
                new LitTextureVertex(Position + HalfSize * Vec3.NPP, Vec3.UnitY, Type.TexTopX, PosYOcclusion.HasFlag(FaceCorners.X) ? ao : 0, Type.Material.Reflectivity),
                new LitTextureVertex(Position + HalfSize * Vec3.PPP, Vec3.UnitY, Type.TexTopY, PosYOcclusion.HasFlag(FaceCorners.Y) ? ao : 0, Type.Material.Reflectivity),
                new LitTextureVertex(Position + HalfSize * Vec3.NPN, Vec3.UnitY, Type.TexTopW, PosYOcclusion.HasFlag(FaceCorners.W) ? ao : 0, Type.Material.Reflectivity),
                new LitTextureVertex(Position + HalfSize * Vec3.PPP, Vec3.UnitY, Type.TexTopY, PosYOcclusion.HasFlag(FaceCorners.Y) ? ao : 0, Type.Material.Reflectivity),
                new LitTextureVertex(Position + HalfSize * Vec3.PPN, Vec3.UnitY, Type.TexTopZ, PosYOcclusion.HasFlag(FaceCorners.Z) ? ao : 0, Type.Material.Reflectivity),
                new LitTextureVertex(Position + HalfSize * Vec3.NPN, Vec3.UnitY, Type.TexTopW, PosYOcclusion.HasFlag(FaceCorners.W) ? ao : 0, Type.Material.Reflectivity),
            };
            else return new LitTextureVertex[6]
            {
                new LitTextureVertex(Position + HalfSize * Vec3.PPN, Vec3.UnitY, Type.TexTopZ, PosYOcclusion.HasFlag(FaceCorners.Z) ? ao : 0, Type.Material.Reflectivity),
                new LitTextureVertex(Position + HalfSize * Vec3.NPP, Vec3.UnitY, Type.TexTopX, PosYOcclusion.HasFlag(FaceCorners.X) ? ao : 0, Type.Material.Reflectivity),
                new LitTextureVertex(Position + HalfSize * Vec3.PPP, Vec3.UnitY, Type.TexTopY, PosYOcclusion.HasFlag(FaceCorners.Y) ? ao : 0, Type.Material.Reflectivity),
                new LitTextureVertex(Position + HalfSize * Vec3.PPN, Vec3.UnitY, Type.TexTopZ, PosYOcclusion.HasFlag(FaceCorners.Z) ? ao : 0, Type.Material.Reflectivity),
                new LitTextureVertex(Position + HalfSize * Vec3.NPN, Vec3.UnitY, Type.TexTopW, PosYOcclusion.HasFlag(FaceCorners.W) ? ao : 0, Type.Material.Reflectivity),
                new LitTextureVertex(Position + HalfSize * Vec3.NPP, Vec3.UnitY, Type.TexTopX, PosYOcclusion.HasFlag(FaceCorners.X) ? ao : 0, Type.Material.Reflectivity),
            };
        }
    }

    public List<LitTextureVertex> GetVertices()
    {
        List<LitTextureVertex> vertices = new List<LitTextureVertex>();
        if (Facing.HasFlag(Faces.PosX)) vertices.AddRange(PosXVertices);
        if (Facing.HasFlag(Faces.PosY)) vertices.AddRange(PosYVertices);
        if (Facing.HasFlag(Faces.PosZ)) vertices.AddRange(PosZVertices);
        if (Facing.HasFlag(Faces.NegX)) vertices.AddRange(NegXVertices);
        if (Facing.HasFlag(Faces.NegY)) vertices.AddRange(NegYVertices);
        if (Facing.HasFlag(Faces.NegZ)) vertices.AddRange(NegZVertices);
        return vertices;
    }

    #endregion

    [DataMember]
    public bool IsVisible;

    public Block(SerializationInfo info, StreamingContext ctxt)
    {
        _position = (Vec3)info.GetValue("Position", typeof(Vec3));
        ID = info.GetUInt64("ID");
        HalfSize = info.GetSingle("HalfSize");
        Yaw = info.GetSingle("Yaw");
        Pitch = info.GetSingle("Pitch");
        Roll = info.GetSingle("Roll");
        Box bbox = (Box)info.GetValue("BoundingBox", typeof(Box));
        _boundingBox = new BoundingBox(bbox.Min, bbox.Max);
        Flips = (Faces)info.GetValue("Flips", typeof(Faces));
        NegXOcclusion = (FaceCorners)info.GetValue("NegXOcclusion", typeof(FaceCorners));
        PosXOcclusion = (FaceCorners)info.GetValue("PosXOcclusion", typeof(FaceCorners));
        NegYOcclusion = (FaceCorners)info.GetValue("NegYOcclusion", typeof(FaceCorners));
        PosYOcclusion = (FaceCorners)info.GetValue("PosYOcclusion", typeof(FaceCorners));
        NegZOcclusion = (FaceCorners)info.GetValue("NegZOcclusion", typeof(FaceCorners));
        PosZOcclusion = (FaceCorners)info.GetValue("PosZOcclusion", typeof(FaceCorners));
        IsVisible = info.GetBoolean("IsVisible");
        Facing = (Faces)info.GetValue("Facing", typeof(Faces));
        _type = (BlockType)info.GetValue("Type", typeof(BlockType));
        Health = info.GetSingle("Health");
    }

    public void GetObjectData(SerializationInfo info, StreamingContext ctxt)
    {
        info.AddValue("Position", _position);
        info.AddValue("ID", ID);
        info.AddValue("HalfSize", HalfSize);
        info.AddValue("Yaw", Yaw);
        info.AddValue("Pitch", Pitch);
        info.AddValue("Roll", Roll);
        info.AddValue("BoundingBox", Box.FromMinMax(_boundingBox.Min, _boundingBox.Max));
        info.AddValue("Flips", Flips);
        info.AddValue("NegXOcclusion", NegXOcclusion);
        info.AddValue("PosXOcclusion", PosXOcclusion);
        info.AddValue("NegYOcclusion", NegYOcclusion);
        info.AddValue("PosYOcclusion", PosYOcclusion);
        info.AddValue("NegZOcclusion", NegZOcclusion);
        info.AddValue("PosZOcclusion", PosZOcclusion);
        info.AddValue("IsVisible", IsVisible);
        info.AddValue("Facing", Facing);
        info.AddValue("Type", _type);
        info.AddValue("Health", Health);
    }

    public Block(Vec3 position, BlockType type, float size = 1, float yaw = 0, float pitch = 0, float roll = 0)
    {
        ID = _nextID++;
        HalfSize = size / 2;
        Yaw = yaw;
        Pitch = pitch;
        Roll = roll;
        _type = type;
        _position = position;
        IsVisible = true;
        _boundingBox = new Microsoft.Xna.Framework.BoundingBox(_position - HalfSize, _position + HalfSize);
        Facing = Faces.None;
        Flips = Faces.None;
        PosXOcclusion = FaceCorners.None;
        PosYOcclusion = FaceCorners.None;
        PosZOcclusion = FaceCorners.None;
        NegXOcclusion = FaceCorners.None;
        NegYOcclusion = FaceCorners.None;
        NegZOcclusion = FaceCorners.None;
        Health = 100;
    }

    [Flags]
    public enum Faces : byte
    {
        None = 0,
        PosX = 1,
        PosY = 2,
        PosZ = 4,
        NegX = 8,
        NegY = 16,
        NegZ = 32,
        All = 127,
    };

    [Flags]
    public enum FaceCorners : byte
    {
        None = 0,
        X = 1,
        Y = 2,
        Z = 4,
        W = 8,
        All = 127,
    }

    [DataMember]
    public FaceCorners PosXOcclusion;
    [DataMember]
    public FaceCorners PosYOcclusion;
    [DataMember]
    public FaceCorners PosZOcclusion;
    [DataMember]
    public FaceCorners NegXOcclusion;
    [DataMember]
    public FaceCorners NegYOcclusion;
    [DataMember]
    public FaceCorners NegZOcclusion;

    [DataMember]
    private BlockType _type;
    public BlockType Type
    {
        get
        {
            return (_type == null ? BlockType.Get("Air") : _type);
    }
        set
        {
            _type = value;
        }
    }

    [DataMember]
    public Faces Facing;
    [DataMember]
    public Faces Flips;
    [DataMember]
    public float Health;
}

```

When a chunk builds its model, this happens for opaque, transparent, and liquid blocks (opaque shown here for brevity):

```
        IEnumerable<Block> blocks = Blocks.AsParallel().Cast<Block>().Where(b => b.IsAir == false && b.IsVisible);
        IEnumerable<Block> opaqueBlocks = blocks.AsParallel().Cast<Block>().Where(b => !b.Type.Transparency);
        //(Transparent, then Liquid block lists would be here)
        List<LitTextureVertex> vertices = new List<LitTextureVertex>();
        foreach (Block b in opaqueBlocks) vertices.AddRange(b.GetVertices());
        if (vertices.Count > 0)
        {
            lock (VertexBuffer)
            {
                if (vertices.Count > VertexBuffer.VertexCount) VertexBuffer = new DynamicVertexBuffer(Globals.GraphicsDevice, LitTextureVertex.VertexDeclaration, vertices.Count, BufferUsage.WriteOnly);
                VertexBuffer.SetData<LitTextureVertex>(vertices.ToArray(), 0, vertices.Count, SetDataOptions.Discard);
            }
        }
        vertices.Clear();
        //(Transparent, then Liquid blocks with a similar process)
        Dirty = false;

```

# Answer
Changes when it was structs were not propagating because things were passed by value rather than reference. This meant that the face culling wasn't applying, and all blocks had all faces culled unless they were freshly-placed.

I opted to stick with classes for now, but that was the issue.
> 1 votes

# Answer
Try change default Facing value from none to something else. If this value is established for all the blocks you get it just does not change where it should. Perhaps you pass a block as a parameter and change its value Facing inside the method.
> 0 votes

---
Tags: xna, rendering, voxels, block-world, struct
---


# Question
Title: How to retarget animation from Generic to Humanoid?
I am in a constant struggle to convert a character that is indeed a humanoid character but its rig has been assigned as a generic rig. I want it to be humanoid so I can easily retarget its animation and apply them to another character of my own. The problem that I am facing is that the animations when I run from the Animation tab of Unity Editor Works just fine but when I try to play them from the Script. The animations doesn’t play at all. I don’t know what could be the problem. I need help in this regard. I have explored google all around and I am in a need of serious help. If someone can I’ll be really very grateful. Thanks

# Answer
> 0 votes
You can put your animations in an animator and add that animator to the character. The animator have parameter property so that you can control which animation to show. Further explanation are are given on their website.

---
Tags: unity, animation
---


# Question
Title: GJK point-in-tetrahedron - capping the number of searches?
The very informative mollyrocket video has given me quite a lot to work with, but one thing that the video seems to suggest is that the algorithm should ideally run until it definitely determines whether or not there's a hit.

I was of the idea that if there's no collision, it would be obvious by testing the dot product of the latest point against the search direction; if it is not positive, then we did not pass the origin, so a tetrahedron which encloses the origin simply cannot be built.

In cases where there is a hit OR a clear miss, the routine typically picks up less than 11 loops through. However, as I tend towards 'questionable territory' and the definitive hit/miss is visually less distinct, there are times when the method apparently continues to pass the origin yet construct unsuccessful simplexes.

Is it common to cap this kind of function at a max number of tries? Right now I am somewhat arbitrarily using the number of points in one shape times the number of points in the other shape; in other words:

```
max_tries = len(shape1.pts) * len(shape2.pts)

```

It feels a bit hacky and I have to assume that the routine is geared towards simply running ad nauseum until it smacks into a clear hit/miss situation.

Has anyone experienced this before? Is this a problem or an anticipated safety measure in such an algorithm? If it needs to be done I'll gladly share some code, but I think it stands as self-evident that it is kind of a longer read than most code snippets so I've abstained for now.

# Answer
Yes, it's common to cap GJK to small number of iterations. This is because the algorithm is most limited by numeric precision. Also I should note that some of Casey's optimizations don't actually work in practice if you need really accurate results. For graphics culling and whatnot, perhaps this is a non-issue, for collision detection in a physics engine this isn't acceptable.

A good example of a solid GJK implementation is in Erin Catto's work in Box2D. He also gave an easier to learn from example in his 2010 GDC lecture and the code is freely available. This is the go-to demo for learning GJK and can be ported to 3D without too much work.
> 2 votes

---
Tags: collision-detection
---


# Question
Title: Show size / dimensions of an object in Unity Inspector
I want to see the size of the currently selected objects in the Unity Inspector, however I can't seem to find how to add it. Currently when I select a model in my scene, the Inspector panel shows info about its position, rotation and scale, but not the size of the object.

What I want to achieve is to create a scene so that the objects in this scene have the correct proportions to each other, i.e. if a human has a size of 1.8 'units', an example car should be about 5 units long.

# Answer
Do you really need the actual size in units? I mean, you can use the scale of your game objects to scale them up and down to create realisitics size relations between your objects.

If you are creating your own 3d assets, you might want to handle the size of your models directly in your 3d model creation software and leave the scale to 1 in Unity (for instance, this thread explains how to set up 3ds Max to work with Unity).

Finally, a GameObject does not really have a size itself, however, a mesh does. If your GameObject has a `Mesh` component, you can get the mesh axis aligned bouding box with Mesh.bounds (or Render.bounds) that will give you a Bounds object that contains useful data like the size of the bounding box.

If you want to show it in the inspector, you might want to extend the editor to display anything you want from the previously requested `Bounds` object.
> 2 votes

---
Tags: unity
---


# Question
Title: How do I limit the rotation speed of a mouse-following object?
I am trying to make a 2D top-down game where player controls a spaceship. The spaceship (a rocket) is just a sprite following the mouse cursor with a fixed speed and is always pointing toward the cursor location. I calculate rotation using `atan2(yDistance, xDistance)`. I've already implemented movement to cursor and rotation toward cursor;

```
float XDistance = Xplayer - Gdx.input.getX();
float YDistance = Yplayer - (Gdx.graphics.getHeight() - Gdx.input.getY());

rotation = (float) Math.atan2(YDistance, XDistance);

if (Gdx.input.isButtonPressed(Input.Buttons.LEFT)) {
    if (XDistance >= playerSpeed | YDistance >= playerSpeed | XDistance <= -playerSpeed | YDistance <= -playerSpeed) {
        Xplayer -= (float) (playerSpeed * Math.cos(rotation) * deltaTime);
        Yplayer -= (float) (playerSpeed * Math.sin(rotation) * deltaTime);
    }
    MathUtils.clamp(Xplayer, 0, Gdx.graphics.getWidth());
    MathUtils.clamp(Yplayer, 0, Gdx.graphics.getHeight());
    sprite.setPosition(Xplayer - sprite.getOriginX(), Yplayer - sprite.getOriginY());
    sprite.setRotation((float) Math.toDegrees(rotation));

```

This algorithm makes U-turn (and every rotation in general) instant. I want to achieve a smoother rotation. Instead of instant rotation, I'd like to implement either a curve or simply a bit slower, non instant rotation (while still moving towards cursor current location).

Also, instead of fixed velocity, I am trying to implement acceleration and deceleration, but to no success (for now).

I've already googled lots of various algorithms, but never found the right one.

Update:

```
public class PlayerEntity {

private float movementSpeedMax;
private float rotationSpeedMax;
private float decay;
private float destinationX;
private float destinationY;

// player
private float playerX;
private float playerY;
private float rotation;

// global
private float _dx;
private float _dy;

private float _vx;
private float _vy;

private float actualRotation = 0;

public PlayerEntity(){
    movementSpeedMax = 1000;
    rotationSpeedMax = 15;
    decay = .95f;
    destinationY = 500;
    destinationX = 500;
    playerX = 0;
    playerY = 0;
    rotation = 0;
    _dx = 0;
    _dy = 0;
    _vx = 0;
    _vy = 0;
    actualRotation = 0;
}

public int getX() {
    return (int) playerX;
}

public int getY() {
    return (int) playerY;
}

public float getAngle() {
    return  rotation;
}

public void updateRotation() {
    // calculate rotation
    _dx = playerX - destinationX;
    _dy = playerY - destinationY;

    // which way to rotate
    float rotateTo = getDegrees(getRadians(_dx, _dy));

    // keep rotation positive, between 0 and 360 degrees
    if (rotateTo > rotation + 180) {
        rotateTo -= 360;
    }
    if (rotateTo < rotation - 180) {
        rotateTo += 360;
    }

    // ease rotation
    actualRotation = (rotateTo - rotation)/ rotationSpeedMax;

    // update rotation

    if (actualRotation < 180);
    rotation += actualRotation;

}

/**
 * Calculate Position
 */
public void updatePosition() {
    // check if mouse is down
    if (Gdx.input.isButtonPressed(Input.Keys.LEFT)) {
        // update destination
        destinationX = Gdx.input.getX();
        destinationY = Gdx.graphics.getHeight() - Gdx.input.getY();

        // update velocity
        _vx += (destinationX - playerX) / movementSpeedMax;
        _vy += (destinationY - playerY) / movementSpeedMax;
    }

    // apply decay (drag)

    _vx *= decay;
    _vy *= decay;

    // if close to target, slow down turn speed
    if (getLength(_dx, _dy) < 50) {
        actualRotation *= .25f;
    }

    if (getDistanceCorrect(destinationX, playerX, destinationY, playerY) < 5) {
        _vx = 0;
        _vy = 0;
    }

    // update position
    playerX += _vx;
    playerY += _vy;
}

private float getLength(float delta_x, float delta_y) {
    return (float) Math.sqrt((delta_x * delta_x) + (delta_y * delta_y));
}

private float getDistanceCorrect(float x1, float y1, float x2, float y2) {
    return (float) Math.sqrt(((x2 - x1) * (x2 - x1)) + ((y2 - y1) * (y2 - y1)));
}

private float getRadians(float delta_x, float delta_y) {
    float r = (float) Math.atan2(delta_y, delta_x);
    if (delta_y < 0) {
        r += (2 * Math.PI);
    }
    return r;

}

private float getDegrees(float radians) {
    return (float) Math.floor(radians / (Math.PI / 180));
}

```

}

I've created this class (based on someone's solution on actionscript). However, this implementation has very annoying bug. If the character rotates clockwise, he will instantly rotate counter-clockwise by ~360. I need help in solving this problem.

This instant rotation happens after one full rotation (rotation direction doesn't matter).

# Answer
I think any linear function would be fine for this. You can keep two variables one for your spaceship's current angle `spaceshipAngle = Math.PI*k`, and one for the current angle that the user inputs with his cursor `cursorAngle = Math.PI*p`. And what you do is

```
if (Math.Abs(Math.PI*k, Math.PI*p) < Math.PI)
{
    if (Math.PI*k < Math.PI*p)
        k += 0.05f;
    else
        k -= 0.05f;
}
else
{
    if (Math.PI*k < Math.PI*p)
        {
            spaceshipAngle += 2*Math.PI;
            k -= 0.05f;
        }
    else
        {
            cursorAngle += 2*Math.PI;
            k+= 0.05f;
        }
}

```

here the "function" is k = k + 0.05 / k = k - 0.05

Note: If your spaceship looks to the top, it has Math.PI/2 angle, if it looks to the bottom it has Math.PI\*3/2 angle, this is how you need to calculate angles for this code to work properly. I have not tested this out so you might see some interesting bugs (for example i don't think this will ever stabilize to an angle even if you don't move your cursor, so you need to fix that), but i think this is mathematically correct.
> 1 votes

# Answer
I suggest moving the *target* slowly rather than the angle. Try this:

```
Vector2 Target;

// Interp is a value between 0 and 1. When 0, the target never moves.
// When 1, the target moves instantaneously. Intermediate values cause the target
// to move at different rates.
void UpdateTarget(float interp)
{
    Target = interp * Mouse.Position + (1 - interp) * Target;
}

```

The ship can then still turn instantaneously toward the target, but the target will smoothly change with respect to the mouse.
> 1 votes

---
Tags: java, 2d, libgdx, movement, rotation
---


# Question
Title: Displaying scores in tutorial projects - GUI and UI
I've just started learning to use unity by working through the tutorial projects but in both roll-a-ball and space shooter I've hit dead ends in the text lessons. The lessons tell you to simply add a GUI text object but they don't seen to exist anymore. From what I've gathered they have been replaced with UI text, but I can't find any documentation that explains how to use them in the way the tutorial describes.

Essentially my question is "how do I complete lesson 15 of the space shooter tutorial project now that unity doesn't let me create GUI text objects in the hierarchy?" Any help would be greatly appreciated.

# Answer
> 1 votes
Go to Component / Rendering GUIText ;)

# Answer
> 0 votes
Well, that is now the old-way to do GUI stuff. The new UI system that came with Unity 4.6 is, I think, extremely robust and easier to learn and work with. I strongly recommend you go through the new UI tutorials on Unity's new UI tutorials page and try to make your UI look like what it is seen on the tutorial you are working on by using the new UI system.

Here's another tutorial series for a pause menu from youtube that helped me get my hands on new UI system. It might be useful for you once you start to work on your pause menu.

---
Tags: unity, gui
---


# Question
Title: How do I draw long tiled paths in 2D? (Eye of the Beholder style)
I'm using artwork from the following page: http://opengameart.org/content/first-person-dungeon-crawl-art-pack

As you can see with the first artwork, the grass field is long. The floor also goes into the distance. I'm most interested in the path.

However, The floor is really small tile-wise, much like the grass. The floor 118x22 pixels.

I'm supposing that the artwork is layered on top of each other. But how?

Is the method similar to this? set x to 0, y -= 22 draw path set x+=20, y -= 22 draw path ...

But as you can see, the tile isn't square, so I don't think this is correct. I'm sure there's some industry standard to doing this. Any thoughts would be great. Thank you.

# Answer
Note this bullet point in the description of the linked art pack:

> Each tile has 13 visible positions in a rough cone shape.

And here's the floor tile within the pack (licensed CC-BY-SA 3.0):

So in this specific instance, nothing special needs to be done to draw these tiles right. You simply pick the right version based on where the tile is with respect to the observer, and render a normal 2D image.

As for the path itself, it is simply drawn from the sides to the center, and back to front, a la the Painter's Algorithm, so they overlap properly.

As for where to draw each tile, this is very much specific to what perspective and dimensions the artwork was drawn with. You can simply load up an image editor, piece the tiles together until they are seamless, then measure the offsets. There's only 13 tiles so you can easily do this manually. Or better yet, just ask the artist, who probably knows.
> 1 votes

---
Tags: graphics-programming
---


title: Accessing colliders from one script C#

text:
# Question
Title: Accessing colliders from one script C#
I want to access specific colliders(to see if they are been clicked) from one script insted of making multiple scripts for every collider.How?

I am using unity.

```
using UnityEngine;
using System.Collections;

public class MainMenuManager3D : MonoBehaviour
{
    public enum Menu
    {
        MainMenu,
        NewGameMenu,
        LoadGameMenu,
        OptionsMenu,
        GameSettingsMenu,
        GameGraphicsMenu,
        Exit
    }
    public Menu currentMenu;
}

```

I want to change the currentMenu based on which collider is clicked in this script. Insted of making 99999 scripts for every collider.

# Answer
> 1 votes
The correct design choice here would be making one script and attaching it to the menu elements (I assume buttons) and define what each button will do on `OnCollisionEnter()` or `OnMouseButtonDown(0)`. The main idea here is to **differentiate clicks based on the name** of the object that is being clicked on.

```
void OnCollisionEnter(Collision col)
{
    if(col.gameObject.name == "NewGameMenu")
    {                       // or whatever the name of the button object is
        // start new game
    }

    if(col.gameObject.name == "Exit")
    {
        Application.Quit();
    }
}

```

Or in the mouse button case (if your design is built on that type), you can ray cast from the mouse click:

```
// Update is called once per frame
void Update ()
{
    if(Input.GetMouseButtonDown(0))
    {
        RayCast();
    }
}

void RayCast()
{
    Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
    RaycastHit hit;

    if(Physics.Raycast(ray, out hit, 100))
    {
        if(hit.collider.gameObject.name == "NewGameMenu")
            // do stuff
        .
        .
        .
    }

 }

```

---

That should cover your question, I think,

# HOWEVER,

I **strongly recommend** you use the new UI system on Unity 4.6.

Use new UI features (Canvas, Button, Text) and assign functions to button clicks. The button animations are already there, which is quite cool! In case you need tutorials, check Unity's tutorials on the new UI System!

Make a menu manager object and define the functions that you want them to be called upon a button press. Simply like this:

```
public void MainMenu()
{
    Application.LoadLevel("menu");
}

public void Quit()
{
    Application.Quit();
}

public void Play()
{
    Application.LoadLevel("game");
}

```

Finally, go and assign the functions to the buttons.

Thats it! You have visually appealing, fully functional buttons!

# Answer
> 0 votes
```
OnCollisionEnter(Collision collision){
if(collision.gameObject.name == foo){
//do foo
}
else if(collision.gameObject.name == bar){
//do bar
}
}

```

---
Tags: c#, unity, collision-detection
---


title: Hexagonal buttons

text:
# Question
Title: Hexagonal buttons
I'm trying to create a map of touchable hexagons and the playing area would be like in Catan game. I would like to use Sprite Kit to do the job but is it cabable of doing that?

Process goes like this:

* user touches one of the hexagons and if it is not disabled game show some actions

Example of clickable area

This is turn-based game so I'm using game center to handle that side.

I have already found very good article about hexagonal grids. In my game the playing area is fixed (19 hexagons) so is there easy solution to do that with Sprite Kit?

# Answer
I would make a sub-class of SKSpriteNode. Each instance could hold its own texture(image) and possibly the numbers, playerImages, etc as children.

Include `-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event` to handle the touch events. Make sure that the sub-class includes: `self.userInteractionEnabled = YES;`

Each sprite includes a userData dictionary. You can use it for custom info for each sprite: playerOwnership? landType? etc.

There are many options here. I'd suggest creating your own custom init Method. Here's one I wrote:

```
    -(id)initForPlayer:(NSInteger)forPlayerNumber inScene:(id)theScene xMax:(NSInteger)xMMax  xMin:(NSInteger)xMMin yMax:(NSInteger)yMMax  yMin:(NSInteger)yMMin
{
    self = [super init];

    - your code here -

    return self;
}

```

as long as your first word of the method is lower case "init", you can add as many Parameters as you need. Your return type could be SKSprite\*.

You can give each instance some Properties that can be changed from the parent, like background image.

I'd create / store these in an array in the parent to be able to access them individually.in the parent
> 0 votes

---
Tags: ios, tilemap, spritekit, game-center
---


title: How to zoom randomly generated maps?

text:
# Question
Title: How to zoom randomly generated maps?
I made a Java program which generates a random map based on Perlin Noise + Poisson Algorithm + Voronoi Diagram. Here you can see a generated map. White are caves, black is empty.

The problem is that my character will go through this caves so I need to zoom this image to see only a big piece of where I am. But when I zoom in, the image obviously gets pixelated and looks really bad. So I save it as an svg image and the quality now is perfect but as far as I have read svg images are slow to render and 2D Games Engine (like SFML, SDL) can't render them.

The approach I have read about is that maps are tiled based, a tile size depending on zoom level, but this is a randomly generated map and zooming in svg image to generate the tiles and save the tiles to formats like png, jpeg, would be very slow (Or I am wrong?).

What can I do here? I have searched how to zoom the Perlin Noise function but it isn't a fractal noise so I can't.

Thank you in advance for your help! I am new in game development!

# Answer
This sounds like a good situation to use Signed Distance Fields. It's often used for text rendering to achieve high quality and sharp results when zooming (and rotating), but it can also be used for any black & white images. See this video and the image below.

Typically when text is prerasterized to bitmaps, each pixel stores the alpha value. 0 means transparent, 1 means opaque and values between are semitransparent due to antialiasing the edges. With signed distance fields the idea is to create a bitmap where each pixel stores the distance to the nearest edge. Values \< 0 are outside the shape and values \> 0 are inside the shape. When rendering, this information is read from the bitmap and the alpha value is decided on runtime based on the distance and "spread". Spread here means how sharp you want the edge to be, usually chosen so that the resulting antialiased edge is no wider than 1 pixel on the screen.

The nice thing about distance fields is that when zoomed in, the distances to straight edges stay accurate when the bitmap is sampled with bilinear filtering. This allows arbitrary zooming without pixelating or blurring. You just need to provide the spread matching the zoom level. This technique is also very fast to render, as it only requires a custom shader with a single texture lookup + some simple math. This is going to be **a lot faster** than polygon based methods. Distance fields also allows some effects easily, mainly borders around or inside the shapes: \[freetype-gl\]

The generation of the distance field can be a problem, as it's not trivial to calculate it from arbitrary shapes. Fortunately for you it should be pretty straigthforward, as you already seem have the distance information available as you are generating a voronoi diagram.

An additional bonus from distance fields is that it can be very friendly for some physics or lighting calculations. As an example PixelJunk Shooter used it for collisions.

The only problem I can see for your case seems to be that your map is not black and white. From the description it's not clear what the different shades of gray indicate. You could just sample the colors from traditional bitmaps or have multiple distance fields, one for each color. Or you could invent something totally different, but it all depends what you want to do.
> 4 votes

# Answer
Currently, you are generating a map in a format that is difficult to use.

Maybe you need use the algorithm for the Perlin Noise to generate a tiled map, instead of an image.
> 1 votes

# Answer
Divide the map in chunks of tiles, lets say chunks of 32x32 tiles, and create a mesh with the geometry of that chunk and map each 4 vertex of each tile with a tileset texture. Build all the map using those chunks join together and draw only the ones visible to improve performance. Use the texture only as reference to know the type of tile to draw at each position.
> 0 votes

---
Tags: java, maps, random, perlin-noise
---


# Question
Title: What level of use can I give to these third person IP based art assets?
I'm making my first game (2D), and while details are irrelevant it compromises lots of spaceships in and out of the screen. They are not the main character or controllable by any means (I don't know if it makes any difference).

For the sake of variety and fun, I decided to re-create some iconic spaceships of various known series. They would compromise a small portion of the overall, less than one percent. Their addition would go in the lines of 'easter eggs' or rare sights, just to warm the fans hearts with lovely memories and enrage the ultrafans brains with conflicting date frames and galaxies far far away mixing with milky way lore.

I will implement them on the developer version of the videogame, as I assume private use is as free as air (I really make the game I'd like to play, and hell if I won't be the one that has most fun). I could implement them as an option for the public version if I was sure it was completely safe.

But considering the scenario in which I finish the game and want to fully release it. This are some of the assets, as example: they are external designs, but I painted them pixel by pixel and generally have some little discrepancies with the canon, besides having one dimension less than they have in most of the original commercial products.

My question is: Under what conditions can I publish them? I would'nt claim them as original or own designs, but I am the maker(and thus, the owner) of the art asset nontheless. The fact that they are so low resolution could allow me to use them as parody work? What if I don't want to make any money of it, and just publish the game without charge?

The simple truth is that I don't really want any problem with anybody. Nor I consider this to end up beeing of any help to my economy. But it would be nice to know if I can distribute it, and what options does it have of helping prevent starvation of one guy. Like, putting a donations button in the same web I use to distribute it, while clearly stating that the development of the game is unrelated to the donations it recives (web without ads, I know that would be considered commercial).

Thank you for your time. (Non-native speaker, feel free to cry blood)

# Answer
> 3 votes
When you don't want any problems with anybody, don't copy other peoples intellectual properties.

Even when you assume you are technically in the right (fair use, notable differences and all), they might still sue. In most parts of the world, civil lawsuits aren't like criminal lawsuits. You won't get an attorney for free and defending yourself as a non-lawyer is practically impossible because civil lawsuits are a minefield of legalese a layman can not possibly survive in. When you want a chance to win such a case, you will have to hire a lawyer, and that lawyer will want money in advance. Such a process can be very lengthy and costly, and when you run out of money you will have no choice but to agree to a settlement, no matter how sure you are that a judge would rule in your favor.

When your game is free, they might decide that you aren't worth their effort (there is no point in paying lawyers to get a settlement with someone who can't pay it anyway), but you can't bet on it. They might just want to get rid of you for strategical reasons or because they fear dilution of their brand.

As a private person there is just no way to win a copyright lawsuit against a big corporation, so better don't risk doing anything which might have the slightest chance to piss one off. Better develop your own intellectual property. It's more fun anyway.

# Answer
> 0 votes
Unless it is a personal use, which means if you go public free or not, you cannot use the exact, recreated or apparently imitated designs without permission.

For parody and fan uses, every company reacts totally different. Some are totally ok with most fan art, some took it very seriously against it and take immediate legal action for any public use. There are also bounty hunter lawyers, who work in agreement with companies and look for illegal uses (or uses that look like illegal to fear enough), threaten owners with lawsuits, settle a payment and take commission out of it.

About fair use, it is not a world-wide concept. In some countries fair use still requires permission. Besides that if you are using them as a decoration, that is, not making humor, writing a research article or giving lectures in a school... etc. it is not fair use even distributed free. You still make benefit (fame, credibility, showcase, uneven competition...etc) out of some other people's work.

---
Tags: 2d, legal, art
---


title: Multiple Scripts versus single script

text:
# Question
Title: Multiple Scripts versus single script
I have (methink) a simple question regarding attaching scripts to a `GameObject`.
Is there any performance loss if I attach a script to a `GameObject` for each action to be performed (such as movement, attaking, interacting) instead of attaching a single script dealing with every single aspect?

I'd like to separete these things due to clearity reasons but I wonder if calling different `FixedUpdate()` functions would imply some kind of issue. For example: is their execution ensured to be called sequentially or they could run asincronously?

# Answer
> 8 votes
> I'd like to separete these things due to clearity reasons but I wonder if calling different FixedUpdate() functions would imply some kind of issue. For example: is their execution ensured to be called sequentially or they could run asincronously?

Each callback of each MonoBehaviour will be called exactly once for each update loop, but you haven't any guarantee about the order (unless you force the execution order explicitly).

> Is there any performance loss if I attach a script to a GameObject for each action to be performed (such as movement, attaking, interacting) instead of attaching a single script dealing with every single aspect?

Short answer: **NO**.

Long answer:

of course there will be a micro overhead, because a separate component need to be stored and updated, but this isn't even perceptible (maybe if you have thousands of components, and you could eventually try to benchmark it).

In any case that's definitely the goal of a component based architecture to split functionality across specific components, so I'd encourage you to do that.

Just a side (personal)note about execution order: it's true that you can force a specific update order of components, and that's sometimes is useful (rarely from my point of view). Forcing a specific update order btw, implies an implicit relation/dependency between components, that is generally not what we want if the components are truly independent.

---
Tags: unity, unityscript
---


title: Set world boundaries in box2d

text:
# Question
Title: Set world boundaries in box2d
So far I've seen the only way to set boundaries on `box2d` world which is to create rectangular shapes and place them at the edges of the screen, is there any other way? Perhaps I can set boundaries with some formula instead of shapes?

Why I'm asking: suppose my "world" looks like a rectangular box without top constraint so any object is ultimately constrained on left, right and bottom sides but can appear infinitely high.

# Answer
> 1 votes
If in your game there are only a couple of objects that could possibly go outside of your game limits, you don't have to add rectangles to set the boundaries in your game unless it somehow makes your code cleaner in your case. Efficiency-wise I guess the old fashioned `if (object1.Position.X < 0)` qualifies as the `left boundary` in your game. If you have many moving objects though, I guess you would have to go with rectangles.

---
Tags: box2d, jbox2d
---


# Question
Title: How to calculate a 3D orientation from 2D vanishing lines on an image?
Let say I have a image that represent a 3D scene. I did not have the 3D camera orientation of that scene (left, up and forward vectors) and i'd like to calculate it.

On that picture, I draw the following segments : A1, A2 and B1, B2.

A1 and A2 are vanishing lines for the plane defined by left and up axis.

B1 and B2 are vanishing lines for the plane defined by forward and up axis.

As input, I only have 2D coordinates of segments (in screen space), so eight coordinates in total. This is the "handles "of the segments on the picture. I also have P0, a 2D position (in screen space) of the origin of the up / left / forward axis (not sure if this information is needed).

Is there a way, from that information, to retrieve the 3D orientation (in world space) of the 3D scene (so the left, up and forward vectors) ?

Once the forward and left vector are calculated getting the up one is trivial : cross product would do.

**EDIT : As Peethor stated, there was some missing information to get what I wanted. I have update question and picture to add more details and make it more clear.**

# Answer
You can look into the Perspective n Point problem. I think that's what this issue is officially called.
> 1 votes

# Answer
Well, getting 2d orientation from 3d points can be done by multiplying it with the world, view, and projection matrices. You could reverse these calculations. The thing is, you don´t know depth. What you get is a line inside the viewing frustum , between the near and far clipping plane of the camera, that tells you where you see this point. But there is no way to know how far away from the camera it is.

UNLESS of course, these points are always on a certain plane, but that´s unlikely given the nature of your question.

You can't know which of the points on a line is closer to the camera, so you can't know how the plane is rotated, so you can't get the "up" vector
> 0 votes

---
Tags: 3d, mathematics, projection
---


title: Permeable objects in Box2d

text:
# Question
Title: Permeable objects in Box2d
In Box2d, can I make a static object to be permeable by dynamic objects? Can I simulate something like water in a way that it lets rigid bodies to dive into it but at the same time pushes them off over time?

Here's an illustration I've made:

1. Three circles in steady state rest inside my "game world" with some gravity.
2. I push the top circle down, two circles on bottom start sinking into walls since wall objects are permeable.
3. Walls slowly push circles back into the world once the top circle stopped affecting them.

# Answer
> 1 votes
Imagine that you have a class that represents a permeable object (in pseudocode):

```
class permeableObject {
    b2RigidBody body; //this holds the actual box2D rigid body

    //this is a virtual function; it will be override by derived classes
    vec2 getExertedForce(vec2 point);

    //...
    //functions such as constructor, setBody, etc
}

```

Then, you implement custom derived classes that have specific functions:

```
class permeableCircle extends permeableObject {

    float getRadius() {
        //...
    }

    vec2 getPosition() {
        //...
    }

    @Override //override the base function
    vec2 getExertedForce(vec2 point) {
        if(distance(point, getPosition() > getRadius()) {
            return vec2(0,0); //no force is exerted, the object isn't inside the circle
        } else {
            //get a force that pops the object out of the circle
            return (point - getPosition()) / getRadius();
        }
    }
}

```

So this is a super basic example, and I haven't done Java in a long time so forgive any syntax errors. Basically, your "permeable objects" have a function which returns the "bouyancy" vector at a specified point. In my circle example, if an object falls into a circle, for example, it will get pushed out if you apply the force returned by `getExertedForce`.

Note that you will probably want to use box2D's built in collision detection, not your own, AND that box2D has sensor objects (I think), which do not collide with objects, only detects collision.

---
Tags: box2d, jbox2d
---


# Question
Title: What are real world uses of secondary key bindings?
I'm currently wondering if there's really a reasonable use that would justify making the effort of implementing *secondary key bindings*?

If you don't know what they are: They allow multiple controls (keys, mouse clicks, ..) to be mapped to the same action (running forward, opening a chest, ..).

# Answer
I think the best argument for secondary controls is probably for when you're already using all "maxing out" the input on one of your hands. For instance, in a FPS, you might want to move diagonally, while sprinting, jumping into a crouch, and then doing a quick melee attack. In this instance, it might be easier to use `MOUSE3` than `V`. The opposite goes if you were already steadily aiming a sniper (with a button to zoom, adjust zoom level, hold breath, etc), it might be easier to use `V` to melee someone who suddenly comes into vision, rather than a mouse button.

Someone with a Razer Naga or similar might also appreciate having lots of additional configurations, just because they CAN. PC players are big on their customizations, which I'm sure you know.

I personally like to use the "Secondary" bindings to keep from overwriting the defaults when I can.
> 1 votes

# Answer
These help in situations where a certain control scheme is easier to use than another. It's especially useful if you can map some action to a key and a mouse button at the same time. You can map movement and jumping in an FPS to the extra mouse buttons and use the other hand to eat pizza!

It's even more useful if you can map both to the keyboard/mouse **AND** a gamepad. See the games coming with native gamepad support on Windows. Some of them require you to explicitly enable/disable the gamepad (Fallout New Vegas), which is not very nice, especially if they default to the gamepad, while others let you switch between keyboard/mouse and the gamepad seamlessly while playing (LA Noire).
> 1 votes

# Answer
It can be useful for driving/simulation games where walking and driving controls may be different.

I.e. Battlefield games.

When walking on foot you may use a keyboard. When flying you may use a joystick.

And like someone else has mentioned, if you have alternative input devices, you don't want to remap or reload your configuration, you want to have flexibility to use both whenever you feel like it.
> 0 votes

---
Tags: input
---


# Question
Title: Sound Synthesis from object collision in Virtual Reality Environment
I have a project whose subject is "Sound Synthesis from object collision in Virtual Reality Environment" First of all, I have to define some objects with certain attributes (like shape, mass, material) and then I have to create sound from the collision of these objects in C++ according to their attributes, area of collision etc. I think I have to use some sort of Physics Engine like Bullet or ODE but I'm not sure how to start this project. Is there any Physics Engine specialized in Sound Synthesis?

I've come up with PhyA but I don't know how to download it and implement it. http://www.tech.dmu.ac.uk/~dylan/z/phya/

P.S. I intend to use CHAI3d or H3dApi because I have to use the Falcon device.

# Answer
> 6 votes
**When you say 'synthesis' do you mean pure analog/additive/FM synthesis from scratch, or would a sample-based approach be acceptable?** If you can't use combinations of real-world audio samples then this is more complicated process. Trying to generate truly realistic sounds through synthesis isn't the standard way that most game/virtual instruments/sound designers work.

If you *do* need something that's based on real **waveform synthesis**, like what you linked to, you probably need to perform a harmonic analysis of a large variety of sounds. Performing a harmonic analysis of various sounds will allow you to break real world sound samples down into fundamental sine waves. Keeping a data structure that associates each sound with its harmonics will probably allow you to interpolate new sounds semi-realistically. Using all this harmonic data, you can then construct the sounds again through additive synthesis. To do this from scratch you will probably need:

* A large database of samples that you will associate with a wide variety of physical conditions. (In your case, samples of a variety of materials of various shapes at different masses.)
* From there you will probably need to perform a harmonic analysis of each sample to break it into fundamental waves. Each sound can then be synthesized again via additive synthesis of its fundamentals.
* Interpolating *new* sounds should then be as simple as comparing the fundamental waves of one or more sounds, and interpolating between them. Like light, the physics of sound is pretty complex, so the odds of generating a *truly realistic* sound this way are pretty slim in my opinion. But analyzing a larger, more diverse pool of samples will probably result in more realistic results.

If you can't use harmonic analysis of real world samples for some reason, the scope of this problem will become a lot bigger - as sound synthesis usually relies on combination/modulation of fundamental waveforms, you'll need to use physical modelling synthesis instead.

---

However, if **sampling** is acceptable, the question becomes how accurate of a simulation are you going for? From what I remember, Valve's Source engine has a relatively similar method of combining sound samples for the same/similar effect (when a plastic prop collides with a metal one, they generate a 'hybrid' sound). If that's acceptable, then you will need to:

* Gather one or more audio samples for each material. The more specific your materials, the better (i.e. plastic sheet, hollow plastic, hollow metal, metal sheet, solid metal, thick wood, thin wood, etc.), and having multiple audio samples per material will create more variety and less computer-like, 'uncanny valley' repetition.
* When a collision occurs you can mix the audio from the samples of both objects depending on the force of the collision, the mass of the objects, etc. More forceful collisions will *probably* result in louder sounds, while a more massive object will likely sound at a lower *pitch* than a less massive one. One again, if you can afford to record a larger pool of sounds for objects with different contours or masses it will likely increase the realism of your final result.
* Finally, if you can create a 'physically-based' reverb effect based on your environment it will help ground your sounds in the environment. Things sound different in large rooms when compared to small rooms and outdoor environments.

I've never attempted this so I've only given it a little bit of thought, but from what I understand this is how most commercial virtual instruments create realistic sound performances. When 'VST' makers try to recreate the sound of a violin, they usually do so through extensive sampling of a real violin - sampling various notes on each string played at different velocities, using different playing techniques, and so on. Creating realistic sounds through pure waveform synthesis is interesting, but it's certainly not the standard practice in game engines at the moment. Good luck.

**Edit:** I didn't touch upon the physics engine part of your question, but I'd assume that most physics engines should be able to detect collisions for you and present you with information about those collisions (force/object mass/direction vectors/etc.).

# Answer
> 2 votes
You should check these for audio synthesis in C++. Check the sources as well. You may find a way to write audio buffer on the fly according to some parameters passed from physics engine.

# Answer
> 0 votes
From what I understand, you should be able to integrate the stream of haptic information from the CHAI3d or H3dApi frameworks with a DSP framework like http://aquila-dsp.org/.

The 3D haptics frameworks should provide the collision detection required, without adding the complexity of another physics layer. This will generate a force effect that can drive the DSP.

DSP frameworks give full control over sampled sounds using Fast Fourier Transforms (FFTs). This allows you to control:

* Pitch
* Doppler
* Speed
* Volume
* Spatialization (3D stereo channels - look at Quaternions for the math).
* Reverb
* etc

The list goes on. There is some processing overhead with the FFTs, since they are doing a lot computations over samples that can be quite large.

There is a tradeoff between realism and processing. You may have to reduce the quality of your samples to get a reasonable effect.

Get a handle on how the outputs from the haptics will feed into the inputs of the DSP.

I have seen/experienced haptics automatically generated from sound streams in games, but the approach to drive the sound stream from the haptics would give a much more immersive realism.

Please post your progress, and good luck.

---
Tags: c++, physics, sound, physics-engine, virtual-reality
---


# Question
Title: Android OpenGL: Use several Textures for one Animated Sprite
Good evening. I'm programming an Android Game. To reduce the amount of textures that need to be loaded (OpenGL ES 2.0) I've created several spritesheets of size 1024x1024. Some frames of the same animation are on different spritesheets. Now my question is if that is bad for the performance since I have to bind (OpenGL.bind()) a different texture for each animation frame? Thank you for clarification!

# Answer
The goal of sprite sheets is to reduce the number of texture bindings.

As you probably need to bind different textures (other than your animations) during a single frame you'll always have at least one texture bind to select one of the spritesheets back on the next frame. Whichever texture your bind on the next frame will have the same penalty as the data will likely be evicted from the texture cache by that point and the issue is a little bit moot with mobile GPUs using tile-based rendering.

When in doubt, use or write a profiler and test.
> 1 votes

---
Tags: unity, android, opengl-es2, andengine, spritesheet
---


# Question
Title: 2D animated sprite jumping and gravity physics
I'm currently writing a Megaman clone for my school project. So far all I did was making the character run and stay put when needed. Know I want to be able to make him jump using the 'X' button. I already have the animation sheet of the jump. But I really can't figure out how to do it and how the physics work after reading so much about it both here and other places. I think you get what I mean. From the state of staying put or running, going to a jumping position and landing. Also to be able to press left/right and the jump button to jump in the direction(I know It's stupid that I explain all of this because you probably know all this but just in case). Anyway this is my code for Game1: http://pastebin.com/zYM5gnRD And this is the code for my Animated Sprites class: http://pastebin.com/5H36YAdb I'm not saying it's the smartest writing, but it's only a school project so I need it to work so I'm fine with it. Thanks a lot, a lot in advance for those who read this and are going to help.

# Answer
> 0 votes
http://www.rodedev.com/tutorials/gamephysics/

float jumpHeight = 4; //defining the jump height isn't needed. You need only determine the y velocity versus gravity. I suppose that jumpHeight could be the y velocity. You can use trigonometry to determine the jump velocity at a specific angel as shown on the link I provided. Grant you this isn't exactly in xna persay, but programming has sort of a universal explanation once you learn one then it isn't hard to pick up on the others contextually.

```
var velocity.y = 4;
var gravity = 1;
var moving = true;

function GameLoop()
{
    if(moving == true){
        velocity.y = velocity.y - gravity;
    }
}

```

believe that more or less covers the gravity piece you asked about anyhow. It's all in that link I posted. If you aren't jumping high enough turn up the velocity.y if you are reaching the height of your jump and then zipping down way to fast decrease gravity. Will take some playing with to get it right. Perhaps if you have already created the game environment in which you intend to move Megaman on you could load the enviroment and do your own alpha testing :-)

---
Tags: 2d, xna-4.0, physics, jumping
---


title: AndEngine rotate all connected bodies

text:
# Question
Title: AndEngine rotate all connected bodies
I have created below hexagon structure in Andengine with box2D physics extension. I want to rotate whole structure with respect to center when other ball collides with the structure using physics.

I tried weld joint and revolute joint with the bodies but it is not performing proper motion as required. All bodies are attached with weld joint and vertices have revolute joint with center body which is static like,

```
RevoluteJointDef revoluteJointDef1 = new RevoluteJointDef();
revoluteJointDef1.initialize(centerB, movingBody[i], centerB.getWorldCenter());
revoluteJointDef1.enableMotor = true;
revoluteJointDef1.motorSpeed = 0;
revoluteJointDef1.maxMotorTorque = 1f;
this.mPhysicsWorld.createJoint(revoluteJointDef1);

```

I had refered these links: box2d manual and box2d joints tutorial

Is there any other way to perform smooth rotation of whole structure? Thanks.

# Answer
> 0 votes
Oh! i got solution by myself... I did the same thing as i mentioned in first comment my question where I attached balls on a big circle body like,

```
Body circleBody ... ;// having large radius
//for all balls arranged in hexagon structure
foreach BallBody b
{
WeldJointDef def = new WeldJointDef();
def.initialize(b, circleBody, b.getWorldCenter());
mPhysicsWorld.createJoint(def);
}

```

and got the rotation by having revolute joint of circleBody with center. Thanks who put their efforts.

# Answer
> 2 votes
If the circles never need to move independently, you can make one body. See here for an example of a hexagon body. I've extracted the relavent bits and pasted them here:

```
import static org.anddev.andengine.extension.physics.box2d.util.constants.PhysicsConstants.PIXEL_TO_METER_RATIO_DEFAULT;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.Body;
import com.badlogic.gdx.physics.box2d.BodyDef.BodyType;
import com.badlogic.gdx.physics.box2d.FixtureDef;
import com.badlogic.gdx.physics.box2d.PolygonShape;

/* ... */

public class PhysicsExample extends BaseExample implements IAccelerometerListener, IOnSceneTouchListener {

    /* ... */

    private static Body createHexagonBody(final PhysicsWorld pPhysicsWorld, final Shape pShape, final BodyType pBodyType, final FixtureDef pFixtureDef) {
    /* Remember that the vertices are relative to the center-coordinates of the Shape. */
        final float halfWidth = pShape.getWidthScaled() * 0.5f / PIXEL_TO_METER_RATIO_DEFAULT;
        final float halfHeight = pShape.getHeightScaled() * 0.5f / PIXEL_TO_METER_RATIO_DEFAULT;

    /* The top and bottom vertex of the hexagon are on the bottom and top of hexagon-sprite. */
        final float top = -halfHeight;
        final float bottom = halfHeight;

        final float centerX = 0;

        final float left = -halfWidth + 2.5f / PIXEL_TO_METER_RATIO_DEFAULT;
        final float right = halfWidth - 2.5f / PIXEL_TO_METER_RATIO_DEFAULT;
        final float higher = top + 8.25f / PIXEL_TO_METER_RATIO_DEFAULT;
        final float lower = bottom - 8.25f / PIXEL_TO_METER_RATIO_DEFAULT;

        final Vector2[] vertices = {
            new Vector2(centerX, top),
            new Vector2(right, higher),
            new Vector2(right, lower),
            new Vector2(centerX, bottom),
            new Vector2(left, lower),
            new Vector2(left, higher)
        };

        return PhysicsFactory.createPolygonBody(pPhysicsWorld, pShape, vertices, pBodyType, pFixtureDef);
    }
}

```

EDIT:

I know the OP has found a working solution to their problem, but I thought I would update my answer anyway. I think the best way is still to make just one body, but you can add multiple fixtures to it (Example done in RUBE):

When a collision happens, the fixture (e.g. ball) in contact is passed to all the collision callbacks, so you don't have to worry about implementing any fancy system to determine which ball was hit in a collision.

IMO this is a lot cleaner and faster than creating new bodies for every ball, and then joining every body to a central one using weld joints.

---
Tags: 2d, android, box2d, andengine
---


# Question
Title: Unity 3d 4 players Only 4 buttons can be pressed at a time
Only 4 buttons can be pressed at a time, so players cant move sometimes

Each Player Has their own Controls

i Change, Up Arrow and the other ones for each player---v

InputsV-V-V

```
public string UpArrow;
public string DownArrow;
public string LeftArrow;
public string RightArrow;

    if(Input.GetButton(UpArrow))
        transform.Translate(Vector3.forward * moveSpeed * Time.deltaTime);

    if(Input.GetButton(DownArrow))
        transform.Translate(-Vector3.forward * moveSpeed * Time.deltaTime);

    if(Input.GetButton(LeftArrow))
        transform.Rotate(Vector3.up, -turnSpeed * Time.deltaTime);

    if(Input.GetButton(RightArrow))
        transform.Rotate(Vector3.up, turnSpeed * Time.deltaTime);

```

# Answer
> 19 votes
Keyboards have hardware limitations on how many keys can be pressed and recognized at the same time.

Your code is not the problem here, it's most likely the design of the keyboard.

# Answer
> 11 votes
Keyboards have a key matrix, where the buttons have been arranged into something roughly square, with the keyswitches each being tied to one row and one column. The keyboard activates each row and then reads the columns. If you sketch this out you will see that some button combinations must activate "phantom" keys. You can fix this with one diode per button (which is a substantial cost for a keyboard) and have *full rollover*. To avoid the phantoms, a keyboard without full rollover will ignore key combinations which are ambiguous.

Modifier keys are always designed so that they can be chorded.

Once the keyboard has a set of keys to report, it has to pack it into the USB HID report, which has one byte that's a bitmask of modifiers, and 6 bytes for other scancodes. So even with full rollover you're not likely to see more than 8 modifiers and 6 scancodes simultaneously.

(the keyboard report also has one byte that's always 0, making 8 total bytes)

---
Tags: unity, input
---


# Question
Title: Cross-platform multiplayer game in JavaScript
I want to start creating a simple **multiplayer**, JavaScript based, cross-platform game. Think about it as a two player mario where players can shoot each other.

My question is what is the best way (or at least a feasible way) to implement multiplayer into the game. I was thinking about:

* Running the game on the both clients, from which one of them is considered to be the server and the other is playing catch-up.
* Using my web server only to establish the connection between the two clients (and forward requests between them, I think this is easier then trying to use some RTC peer-to-peer protocol).

I have never done any multiplayer game, so I do not know if this method is good. One flaw in the design is that the game becomes very hackable (as the one that is considered to be the server has control over all the legal move validations done).

So, my question is if, using this method, a playable multiplayer game can be implemented, where if one player clicks the "shoot" button pointing in a specific direction the other player would receive this data in a period of time short enough so that he can react to it. If not, what is another reliable way to create a `JavaScript`, cross-platform (web, mobile) game?

If I were to also run an instance of the game on the server for each duel betwen two clients I think the servers would be over-loaded very easily, so I don't consider this a solution.

PS: About the hackable part. Do you think it can be reduced if I can somehow implement checkings on **both** clients?

PS2: When I say `multiplayer` I mean over the internet, not a local ad-hoc multiplayer for mobile devices.

# Answer
> 1 votes
When you say "Javascript" you certainly mean "running in the web browser". In that case, peer-to-peer networking isn't possible because there is no browser-independent standard for this.

But what you can do is having a server. One technology which is quite well-suited for real-time games are websockets. You can prevent most kinds of cheating by having an authoritative server which implements all game mechanics and sends the clients the results.

---
Tags: javascript, multiplayer, cross-platform, hacks
---


# Question
Title: Set Non-Looping Animation Time to Seconds
I have an animation that does not loop. It plays for the default duration (n seconds), then stops on the last frame. This is exactly what I want to have happen, but I want it to play for m seconds, not n seconds. I do not know how long n seconds is.

I have to get it exactly to m seconds, because it is a changing variable. So estimating will not work. I need it to match up exactly with another animation. How can I stretch an animation to last an exact number of seconds?

# Answer
> 1 votes
An easy way if it is a simple animation (rotating gear, a piston, etc) would be to edit your animation to be exactly 1 second long then use the `Animator.speed` and set it to `1.0f / wanted_seconds`, but that's not usable for complex character animations.

You can figure out the length of the `AnimationClip` ( http://docs.unity3d.com/ScriptReference/AnimationClip.html ) then set the speed to `my_animator.speed = my_animator.animation.clip.length / wanted_seconds`.

---
Tags: unity, animation, timing
---


title: 2D Boat controlling physics

text:
# Question
Title: 2D Boat controlling physics
I'm working on a top-down 2D boat game with Unity3D. I couldn't able to understand how to implement physics of rudder controlling. My physics knowledge is not enough to think how rudder dynamics work. How rudder dynamics works in water? Can you help me for finding a starting point for this?

Since I'm not able to think any solution for this, I can't provide an example code.

EDIT:

I'm trying to apply a force to rigidbody2D of the ship at the point of rudder with angle of the rudder. But I couldn't able to make something working

Sample Code

I draw a sketch. Red point is location of rudder. I'm trying to apply a force at that point with angle of rudder relative to ship heading on each Update. How can I do this?

# Answer
The simplest, modestly realistic, model I can think of would be parameterized by the following:

* **Mz** The Turning Moment of the ship about the steering (ie Z or yaw) axis;
* **L/2** The distance of the rudder from the turning axis, approximated as 1/2 the ship's length L;
* **v** The current linear velocity of the ship (relative to the **water**, not the land nearby, so take into account any current).;
* **w** The current rotational (yaw) velocity of the ship about the Z-axis, measured CCW in radians per second;
* **p0**,**p1**,**p2** The constant, linear and quadratic coefficients respectively of angular friction (ie resistance to turning) for the water (these control how quickly the ship stops turning when the rudder returns to straight, and impose a limitation on how sharply the rudder can be turned before losing any effect.)
* **A** the area of the rudder;
* **d** the density of the water.
* **theta** the current rudder angle measured CCW from straight back in radians
* **heading** the current heading measured CCW from origin direction in radians.
* **delta-t** is your time interval.
* **Cd** is coefficient of increased drag due to a non-neutral rudder position.

Then the relevant equations of motion can be derived something like this:

1. Turning torque from rudder **Tr** == sin(**theta**) * **A** * **v** * **d** * **L/2**
2. Friction torque from water **Tw** == **p0** \+ **p1** * **w** \+ **p2** * **w**^2
3. Net torque **T** == max(0, abs(**Tr**) - abs(**Tw**)) * sign(**Tr**)
4. **w'** == **w** \+ **T** / **Mz**
5. **heading'** == **heading** \+ (**w'** \+ **w**) * **delta-t** / 2
6. Drag on forward motion increases by **Cd** * abs(sin(**theta)) * \**A** * **v** * **d**

I think I have the signs correct, but that can be corrected if necessary by multiplying **T** by -1 in either equation (3) or (4).

By playing around with the parameters you should even be able to get an appropriately different feel for larger vessels compared to smaller ones. You should also set a modest limit on how fast the rudder can be turned, and prevent it from being turned further once **Tw** exceeds **Tr**.

Setting **p0** greater than zero will nicely model the fact that ship have no steerageway below a minimum speed.

**Update**

Calculation of Moments of Inertia \- For ships of the same style but different sizes, the moment of inertia should vary linearly in the mass of the ship, and as the square of the length of the ship, as a first approximation.

**Update 2**:

* Added Equation (6) above and corresponding drag coefficient; and
* corrected equation (1) with additional factor **L/2**.
> 5 votes

# Answer
If the rudder turns left /, the boat turns left.

If the rudder turns right \\, the boat turns right.

The more you turn the rudder, the greater the turn the boat takes. This assumes the rudder never turns 90+ degrees.

The / and \ assume the boat is facing up ^.

```
   ^
  |  |
  |  |
  ---
   /   <---rudder

```
> 1 votes

---
Tags: unity, physics, unityscript, water
---


# Question
Title: EditorApplication.SaveScene followed by EditorWindow.Close throws InvalidOperationException
I'm making a really basic custom editorwindow that has a textbox for a scene name, creates a scene with that name and closes itself. Trimmed down to the essence it looks like this:

```
public void OnGUI()
{
    if (!GUILayout.Button("Create")) return;

    if (CreateScene())
    {
        Close();
    }
}

private bool CreateScene()
{
    var path = string.Format("{0}/{1}.unity", Application.dataPath, "bug");
    EditorApplication.NewScene();
    return EditorApplication.SaveScene(path);
}

```

This throws an InvalidOperationException

```
InvalidOperationException: Operation is not valid due to the current state of the object
System.Collections.Stack.Peek () (at /Users/builduser/buildslave/mono-runtime-and-classlibs/build/mcs/class/corlib/System.Collections/Stack.cs:321)
UnityEngine.GUILayoutUtility.EndLayoutGroup () (at C:/BuildAgent/work/d63dfc6385190b60/artifacts/EditorGenerated/GUILayoutUtility.cs:223)
UnityEngine.GUILayout.EndVertical () (at C:/BuildAgent/work/d63dfc6385190b60/artifacts/EditorGenerated/GUILayout.cs:266)
UnityEditor.HostView.OnGUI () (at C:/BuildAgent/work/d63dfc6385190b60/Editor/Mono/GUI/DockArea.cs:135)

```

When I remove either the save or the close, the exception doesn't rise.
My guess is the project window needs to finish refreshing somehow.

**UPDATE**

Tried a frame of delay
Tried AssetDatabase.Refresh()
Tried GUILayout.EndVertical()
Filed a bug
Bugtrack: http://fogbugz.unity3d.com/default.asp?668833\_nmit48pnb2fivo27

Any advise?

# Answer
> 1 votes
Looks like the GUI is finishing building after the Close() by automatically calling EndVertical().

Try adding an `GUILayout.EndVertical();` before the `Close();`.

Or if that doesn't work delaying your Close call by one frame, something like:

```
private bool close = false;

public void OnGUI()
{
    if(close){
        Close();
        return;
    }

    MapName = EditorGUILayout.TextField("Map Name", MapName);

    var requestedSave = GUILayout.Button("Create") || PressedEnter();
    if (!requestedSave) return;

    if (!CreateScene())
    {
        Debug.Log("Failed saving");
    }
    close = true;
}

```

---
Tags: unity
---


# Question
Title: Help with understanding "transform.root.GetComponent<>" in Unity
I'm reading through a tutorial for making an RTS in Unity, and in certain scripts it wants you to make a Player field and then OnStart(){ transform.root.GetComponent}. I am not quite getting what that does or what purpose it serves.

Player.cs is added as a component to the game object "Player". Player.cs is the following:

```
public class Player : MonoBehaviour {

public string username { get; set; }
public bool human { get; set; }
}

```

Then on another script which is also attached to the Player (gameobject) as a component:

```
protected Player player;

protected void Start ()
{
    player = transform.root.GetComponent<Player>();
}

```

This is instructed: http://stormtek.geek.nz/rts\_tutorial/part2.php right under "Camera Input". There is a description there, but I am confused by it since it does not allow you to actually interact with the game object Player, but the instance of the Player script.

I'm sorry if this was poorly worded, I can't think of a better way to ask this question. I am completely confused as to why it asks you to do this and what it actually does. I'm also very confused about how to reference instances of a class that are attached to a game object, and if the snippet in question assists with that (I can remove the snippet and things seem to work fine).

Edit: I have looked at the unity documentation on game objects, transform, root, getcomponents and other related methods.

# Answer
> 1 votes
I am not quite sure what you are not understanding here, but I attempt to answer your question anyway.

> I am not quite getting what that does or what purpose it serves.

In cases where you do not fill in the fields in the inspector (which requires them to be public), you need to find the instances of the needed components in code. The `GetComponent<T>()` method does just that; it tries to find the given component instance from the game object the method is called on. In this case, it tries to find the Player component from the topmost game object (root) in the object hierarchy.

You can also get the component instances by making the field public and dragging the correct object in to the field in the inspector in Unity editor. In this case you do not have to call the GetComponent method, but you need to make sure it is actually set before you try to use it. If you do not, the game will throw a null reference exception.

The null check is recommended thing to do in any case, even when you get it with GetComponent method.

> This is instructed: http://stormtek.geek.nz/rts\_tutorial/part2.php right under "Camera Input". There is a description there, but I am confused by it since it does not allow you to actually interact with the game object Player, but the instance of the Player script.

The GameObject does nothing by itself. It always has some components that actually does something. The component can determine if it should draw some mesh, or some sprite, or just play some sound. Without any components, the empty GameObject is pretty much useless entity in the scene. The component scripts derived from MonoBehaviour class are used for custom behaviour for the GameObject, in addition to the Unity's built-in components.

The `GetComponent<T>()` again is the key here, it always gets the instance of the component script for you to interact with. If you modify something in this instance, it will modify only the GameObject's component.

> I'm also very confused about how to reference instances of a class that are attached to a game object, and if the snippet in question assists with that (I can remove the snippet and things seem to work fine).

It works fine if the player field is not accessed anywhere in your script code. It will not work if you try to interact the Player script from the code if you have not assigned it's instance to the player field.

---
Tags: c#, unity, objects, gameobject
---


# Question
Title: XNA draw texture/font and DrawIndexedPrimitives at the same time
When i Draw a texture2d or a font with spriteBatch and also draw GraphicsDevice.DrawIndexedPrimitives, the frame is draw weird

```
SpriteBatch  spriteBatch = new SpriteBatch(GraphicsDevice);
BasicEffect basicEffect = new BasicEffect(GraphicsDevice);

protected override void Draw(GameTime gameTime)
{
    GraphicsDevice.Clear(Color.LightSteelBlue);
    RasterizerState rasterizerState = new RasterizerState();
    rasterizerState.CullMode = CullMode.None;
    GraphicsDevice.RasterizerState = rasterizerState;

    //for(...) {
    GraphicsDevice.SetVertexBuffer(vertexBuffer);
    GraphicsDevice.Indices = indexBuffer;

    foreach (EffectPass pass in basicEffect.CurrentTechnique.Passes)
    {
        pass.Apply();
        GraphicsDevice.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, 8, 0, 20);
    }
    // } end for

    spriteBatch.Begin();
    spriteBatch.DrawString(MainFont, "FPS: " + Math.Round(1 / (float)gameTime.ElapsedGameTime.TotalSeconds, 2), new Vector2(200, 10), Color.Red);
    spriteBatch.End();

```

How can i solve this ?

# Answer
This is because the sprite batch hijacks the graphics device's states when you use it. You need to cache them before using the sprite batch and then restore them afterwards. (Or you can set them directly afterwards without caching if you know the ones you want to use.)

```
// cache device states
var blendState = GraphicsDevice.BlendState;
var depthStencilState = GraphicsDevice.DepthStencilState;
var samplerState = GraphicsDevice.SamplerStates[0];

// use your SpriteBatch

// restore device states
GraphicsDevice.BlendState = blendState;
GraphicsDevice.DepthStencilState = depthStencilState;
GraphicsDevice.SamplerStates[0] = samplerState;

```
> 1 votes

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


# Question
Title: How do I convert a cube map to an equirectangular projection?
I have a cube map texture showing a surrounding area, which I want to pass to a program that only works with latitude/longitude maps.

How can I do this?

---

In other words, I need to turn this:

…into this (I think it's additionally rotated -90° over the x axis):

# Answer
> 2 votes
With `rect_coordinate` ranging from -1 to 1 and assuming sin/cos functions take radian as inputs, for each pixel in the rectangular texture do:

```
color CubeToRectangle(vec2 rect_coordinate)
{
    vec3 cube_map_coordinate;

    cube_map_coordinate.x = cos(rect_coordinate.x * PI * 2) * cos(rect_coordinate.y * PI);
    cube_map_coordinate.y = sin(rect_coordinate.y * PI);
    cube_map_coordinate.z = sin(rect_coordinate.x * PI * 2) * cos(rect_coordinate.y * PI);

    return CubeMapTextureRead(cube_map_coordinate);
}

```

---
Tags: textures, algorithm, projection
---


title: Logic for enemy chasing main player

text:
# Question
Title: Logic for enemy chasing main player
I'm making AI to tell a minion to chase and attack the player.

I played Magicka, and the minion follows the player in a nice curved manner (left image), rather than what I currently have (right image), where the minion just keeps reacting the the player's changes in X,Y.

The code I have makes the chasing minion appear to move in a blocky way as it keeps trying to have its coordinates == the player's coordinates:

```
    if (enemy.pos.x <= game.data.playerX) {
        enemy.body.vel.x += enemy.body.accel.x * me.timer.tick;
    }
    else {
        enemy.body.vel.x += -enemy.body.accel.x * me.timer.tick;
    }
    if (enemy.pos.y <= game.data.playerY) {
        enemy.body.vel.y += enemy.body.accel.y * me.timer.tick;
    }
    else {
        enemy.body.vel.y += -enemy.body.accel.y * me.timer.tick;
    }

```

How can I achieve a more smooth transition effect?

# Answer
> 1 votes
You need to keep a enemy heading (direction) variable and only move the enemy along that direction.

Slowly rotate the enemy heading to face where it actually wants to go but only a few degrees per frame.

You move forward according to the dot product of the heading and where you should be heading. This prevents overshooting the target. The enemy will move a bit slower as its turning to reach the target.

```
enemy.pos += enemy.heading * enemy.max_speed * Max(0, DotProduct(Normalize(player.pos-enemy.pos), enemy.heading))

```

`Max()` is there to not walk backward but that is optional. Could also use Clamp(dot, -0.25, 1.0) if the enemy is allowed to walk backward slowly in a somewhat comical fashion.

A different way to go about it would be to only update the enemy's target every seconds or so, or have the enemy target lag behind the wanted target by interpolation or delay queue.

```
current_target_pos += (real_target_pos - current_target_pos) * 0.25;

```

There are many variations of these depending on the exact desired effect.

---
Tags: ai, path-finding, rpg, npc
---