texts:
I am making an army fight for my website armyfight. There can be fights of hundreds of thousands units. I am looking for better unit targeting. in jsfiddle is an example.

var enemy = {
    2: {
        3: {}  // object inside with unit data
    },
      5: {
        6: {}
    }
}

var ally = {
    4: {
        3: {}
    }
}

function unit_searches_for_target(y, x) {
    var closest_y   = iterate_Y(y);
    var unit_target = iterate_X(closest_y, x);
  return unit_target;
}

// Searches for closest target at Y axis
function iterate_Y(y) {
    if (_.has(target, y)) {
        return y;
    } else {
      var y = parseInt(y);
        for (var i = 1; i < 300; i++) {
            // If y == 4, it checks 4+1=5 (positive side)
            if (_.has(target, String(y + i))) {
                return (y+i);
            // Else if y == 4, it checks 4-1=3 (negative side)
            } else if (_.has(target, String(y - i))) {
                return (y-i);
            }
        }
    }
    // if didn't find anything, just returns same y as given
    return y;
};

// Searches for closest target at X axis
function iterate_X(y, x) {
    if (_.has(target[y], x)) {
        return {y: y, x: x};
    } else {
      var x = parseInt(x);
        for (var i = 1; i < 300; i++) {
            // If x == 4, it checks 4+1=5 (positive side)
            if (_.has(target[y], String(x + i))) {
            return {y: y, x: x + i};
            // Else if x == 4, it checks 4-1=3 (negative side)
            } else if (_.has(target[y], String(x - i))) {
              return {y: y, x: x - i};
            }
        }
    }
    // if didn't find anything, just returns same x as given
    return {y: y, x: x};
};

Here first i iterate on Y axis, later on X axis. But on different army positions it gives wrong results.

In this example, units are looking for targets by simply iterating. It is not very good for a huge army fight of hundred thousands units.
Best would be to iterate like here, when iteration process is much faster leading to first-hit success:

function iterate_X(y, x) {
  return _.find(enemy[y], function (value, key) { return parseInt(key) >= x });
}

But this iteration works only 0..100, or 99..100, but not 100..0, so i can't iterate objects in reverse mode. So if ally is {5: {10: {}, 99: {}} and enemy is at {5: {100: {}}}, enemy unit would find closest ally as [5, 10] instead of [5, 99]. If it would be an array iterating backwards from 100 to 0, so it would be first-hit success. But can asotiative array be reverse-iterated?
Any suggestions please on structure? Maybe change units structure from objects to arrays or mix?  But then I have problems with associative arrays. I am looking for an explanation or example about the structure and for a faster iteration for units targeting.
And i am also looking for websites, where i could ask these heavy logic questions? I have more of them.


texts: Terms of integrating 3rd party sdk and libraries in your engine

texts:
I am developing my own engine and integrating Bullet Physics.

Now Bullet Physics is open source under Zlib license. My concern is, can original owner change the license later on to paid and how it can affect the games which already released with my engine? Do I need to strip out all the code related to Bullet Physics?

Same questions I'd like to know for free engines like Unity & Unreal.

Thank you.


texts: How realistic are procedural textures in sandbox?

texts: I'm working with Unreal and want to make a Minecraft-Style Block-Sandbox with HD-textures. Since at that resolution the repetitive pattern becomes too noticable, I'd like the game to generate the textures on the fly, based on coordinates, so the blocks have a seamless appearance, and distance to player, so further away blocks have a lower resolution. I'd love something between Rust and Grounded, Quality-wise, so it will include PBR, SSS, and height maps. I've got a fairly powerful PC, but since the CPU will have to constantly generate textures, which all would have to be stored inside the RAM, I was wondering how realistic something like that would be in the first place. And how I could save resources, things like reducing the quality in the shadows or so on. Thanks in advance.


texts:
I want the player to select 2 points (vectors). With these 2 points a floor should be created. When these points are parallel to the x-axis it's easy, just calculate the amount of blocks needed by a simple division, loop through that amount (in x and y) and keep increasing the coordinate by the size of that block.

The trouble starts when the 2 vectors aren't parallel to an axis, for example at an angle of 45 degrees. The 2 red dots would be the player selected locations. (The blocks indeed aren't square.) .

How do I handle the math behind this?


texts: Having trouble creating multiple sprites from one class

texts:
So I am trying to make more than one sprite using a single class but I cannot seem to get the sprites to be drawn at all or drawn in different places (they are all just on top of one another).

In my Game1 I have:

    Flag flag;
    List<Flag> GameFlags = new List<Flag>();

then in LoadContent:

flag = new Flag();
tempTexture = Content.Load<Texture2D>("FlagTexture");
tempRectangle = new Rectangle(50, 500,tempTexture.Width / 3, tempTexture.Height / 3);
flag.SetSprite(tempTexture);
flag.SetRectangle(tempRectangle);

for (int i = 0; i < 2; i++)
        {
            GameFlags.Add(flag);
            flag.spriteRectangle.X += 100;
        }

Then in Draw:

 foreach (Flag flag in GameFlags)
        {
            spriteBatch.Begin();
            flag.Draw(spriteBatch);
            spriteBatch.End();
        }

The effect I am after is having 2 sprites spaced out by a specified amount of space. Image if the underscores were spacing and the zeros were sprites in the following:

0____________________________0

Any help and advice is appreciated.

Thanks in advance,

TeaBelliedTitch.


texts: Does C# have a future in games development?

texts:
I recently learned that the MMO Minecraft is powered by Java from a recent interview on CVG.co.uk on a possible collaboration between two former and now competing colleagues. In the interview he bluntly said that the founder of Minecraft is a Java coder and he is a C or C++ coder so they are incompatible with each other. So collaborating on future projects will be difficult.

This got me thinking, If Java could do that? What does the future hold for MS very popular C# language and .Net platform as far as games or mainstream games development is concerned?


texts: Unity - Transform.RotateAround() + Transform.Translate() - Why is rotation offset created and how can it be fixed?

texts:
I have one object orbit another with RotateAround(), then I use Translate() to move the orbiting object in the same frame in an effort to change the distance at which the object is orbiting.  This causes the rotation provided by RotateAround to drift.  How can this drift be corrected without rewriting my own RotateAround?

public class TestRotateAround : MonoBehaviour
{
    [SerializeField]
    Transform orbitTarget;

    // Start is called before the first frame update
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {
        Vector3 dirToTarget = (orbitTarget.position - transform.position).normalized;

        transform.RotateAround(orbitTarget.position, Vector3.forward, 10 * Time.deltaTime);

        transform.Translate(-dirToTarget * Time.deltaTime * 2);
    }
}


texts: How can change some text above a character upon collision in Unreal?

texts:
I've just started using Unreal Engine, and I was trying to do a super simple game where there is a character that has text above his head that says 'Bag 'o' fries.'

My plan was to have it so if something touches the bag 'o' fries, the text changes to 'Mission Complete.' I currently have one blueprint that just says onGameStart --> BoxOverlapActors --> set variable 'text' to 'Mission Complete'. The variable 'text' I made isn't actually connected to the text, so this is where I have the problem.

How can I do this?


texts: Make zoomable Camera and Environment follow player smoothly

texts:
I am making a 2D side-scroller racing game. The Player is a car that moves on a 2D terrain already created. The Camera follows the Player. I also wanted to created more depth by making the background follow the y-axis of player so that the background doesn't look like a plain picture. The effect I want to replicate is that when the player jumps the camera just zooms out.

I am using a perspective camera so it zooms out by moving it slightly farther away from the Player. Unfortunately, the effect isn't smooth.

The platform is using 2D edge collider. The movement gave me motion sickness and I just don't know what I should be doing to make this follow nicely.

I have tried using smooth damp that gave me spring effect which isn't needed here. I used Lerp which just doesn't work at all. It's dang slow and when I make it fast it just same undesirable behaviour. The MoveTowards works a bit but not quite really. The smoothness is just not what I want.

For reference, my game is pretty much same like the I hate zombies.
check video https://youtu.be/YQZoBC1hVyk?t=31s

attached is my code.

 Vector3 newPos;
public Vector3 camOffSet = Vector2.zero;
public float speed = 2;
Vector3 velocity = Vector3.zero;
void FixedUpdate()
{
    if (CarController.Instance != null)
    {
        newPos = CarController.Instance.transform.position + camOffSet;
        if (CarController.Instance.IsGrounded)
        {

            newPos.z = -10;
        }
        else
        {
            float zz = Mathf.Clamp(-10 - newPos.y, -20, -10);
            newPos.z = Mathf.Clamp(-10 - newPos.y, -20, -10);
            //newPos.x = CarController.Instance.transform.position.x + (camOffSet.x * 3);
            newPos.x += (zz * -0.4f);
            //newPos.z = Mathf.MoveTowards(transform.position.z, Mathf.Clamp(-10 - newPos.y, -20, -10),
            //    speed * Time.deltaTime);
        }
        //transform.position = newPos;
        transform.position = Vector3.MoveTowards(transform.position, newPos, speed * Time.deltaTime);
    }
}


texts: why isn't onTrigger invoking on collision with a trigger or a rigidbody?

texts:
void onTriggerEnter(Collider other)
{
    if (other.gameObject.CompareTag("Pick Up"))
    {
        other.gameObject.SetActive(false);
        count = count + 1;
        setCountText ();
    }
}

This is the methodI want to invoke, on collision of a sphere with another cube. The cube is set as a trigger, and a rigidbody component is attached to both of the objects. Still, on collision, the method is not invoked. Is there anything else that may be done, for this method to execute?


texts:
Myclass
{
void run();
sf::Clock m_clock;
float m_time;
float timestep
}
Myclass::run()
{
if (m_time>= timestep)
{
//update
m_time-=timestep;
}
restartCLock();
}
Myclass::restartCLock()
{
m_time+=m_clock.restartAsSeconds();
}

How do i do the same but when m_time is being sf::Time?


texts:
How you can see my mouse goes little bit faster than widget.

My movement algorithm is:

cursorPositionPrev.set(cursorPosition);
cursorPosition.set(getCurrentPos());
...
Vector2f delta = new Vector2f(cursorPosition).sub(cursorPositionPrev);
widget.getPosition().add(delta);

I am using LWJGL and my own GUI solution.

Here is visual structure of event processor part.
One thread for processing events generated by user and another thread render current gui state.

Even if rendering and processing events is in one thread the issue is still exist.

So what can I do to make to avoid this delay and make widget to keep up with the mouse movement?


texts:
How can I add a parallax effect into my side-scrolling game? I read a lot about parallax scrolling so I know what the logic is and what parallax is but I can't create a dynamic parallax effect.

I have draw and update functions like this:

void UpdateBackground(Background &back)
{
    back.x += back.velX * back.dirX;
    if(back.x + back.width <= 0)
        back.x = 0;
}
void DrawBackground(Background &back)
{
    draw_bitmap(back.image, back.x, back.y, 0);

    if(back.x + back.width < WIDTH)
        draw_bitmap(back.image, back.x + back.width, back.y, 0);
}

So this draws a parallax effect with two background objects but it draws it statically. I'm creating a 2D side-scrolling game and I'm translating my character and my camera position along x axis. So I have to translate my parallax effect with my camera but when I add to background position.x it doesn't work. How can I solve this?


texts: RectTransform Button Start shaking with Vector3.MoveTowards()

texts:
I have a RectTransform Button that i want to make it move to a de-terminated vector3.

To move the button i use this code (it is inside Update())

        int i = -1;
        foreach (RectTransform Button in Buttons)
        {
            i++;
            Vector3 NewPosBtns = new Vector3(StartButtonsVect[i].x, (StartButtonsVect[i].y + 192.5f), StartButtonsVect[i].z);
            Vector3 CurPosBtns = StartButtonsVect[i];
            Button.localPosition = Vector3.MoveTowards(CurPosBtns, NewPosBtns, AnimationSpeed);
        }

Buttons is a array and i add the button to the list using unity editor

StartButtonsVect is of vector3 that i add the using this code

void Start()
{
    foreach (RectTransform Button in Buttons)
    {
        StartButtonsVect.Add(Button.localPosition);
    }
}

For some reason the button start shaking instead of going to the target position (NewPosBtns)


texts: Can i use shaders in allegro without opengl?

texts:
I'm currently learning opengl but it seems quite complicated so i considered using some library like sdl or allegro. I noticed that allegro has some built in functions to create and attach shaders.

But my question is: do my shaders "shade" everything i render with allegro or they are only functions to ease the work of loading shaders with opengl/directx?

Any help apreciated!


texts:
I would like to know why we would use alpha blending in that shader for just rendering a sprite, which is just a texture ?
What is tint color ?
Why we multiply the alpha value by the color here ?

fixed4 c = tex2D(_MainTex, IN.texcoord) * IN.color; // why ?
c.rgb *= c.a; // why ?
Shader "Sprites/Default"
{
    Properties
    {
        [PerRendererData] _MainTex ("Sprite Texture", 2D) = "white" {}
        _Color ("Tint", Color) = (1,1,1,1)
        [MaterialToggle] PixelSnap ("Pixel snap", Float) = 0
    }

    SubShader
    {
        Tags
        {
            "Queue"="Transparent"
            "IgnoreProjector"="True"
            "RenderType"="Transparent"
            "PreviewType"="Plane"
            "CanUseSpriteAtlas"="True"
        }

        Cull Off
        Lighting Off
        ZWrite Off
        Fog { Mode Off }
        Blend One OneMinusSrcAlpha

        Pass
        {
        CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag
            #pragma multi_compile DUMMY PIXELSNAP_ON
            #include "UnityCG.cginc"

            struct appdata_t
            {
                float4 vertex   : POSITION;
                float4 color    : COLOR;
                float2 texcoord : TEXCOORD0;
            };

            struct v2f
            {
                float4 vertex   : SV_POSITION;
                fixed4 color    : COLOR;
                half2 texcoord  : TEXCOORD0;
            };

            fixed4 _Color;

            v2f vert(appdata_t IN)
            {
                v2f OUT;
                OUT.vertex = mul(UNITY_MATRIX_MVP, IN.vertex);
                OUT.texcoord = IN.texcoord;
                OUT.color = IN.color * _Color;
                #ifdef PIXELSNAP_ON
                OUT.vertex = UnityPixelSnap (OUT.vertex);
                #endif

                return OUT;
            }

            sampler2D _MainTex;

            fixed4 frag(v2f IN) : SV_Target
            {
                fixed4 c = tex2D(_MainTex, IN.texcoord) * IN.color;
                c.rgb *= c.a;
                return c;
            }
        ENDCG
        }
    }
}


texts: What underlying character stats would you put into your "character" object in an RPG engine

texts:
basically I'm making my own RPG/TBS engine named Uruk (making an rpg themed about the epic of gilgamesh) and I am thinking of a combat system similar to the Disgaea franchise or the Super Robot Wars franchise

I'm currently in the process of writing the "character" class (cant name it character since it causes confusion with the primitive data type "character") and right now i've decided to go with the regular RPG route of including the following base stats:

strength
Agility
Willpower
Endurance
Luck

and the base stats would then dictate the following stats

Attack (probably a combination of the strength stat and weapon stats)
Physical Defense (determined by endurance and armor)
Magic Resistance (maybe something to do with willpower and armor)
Crit Rate (luck and agility)
Max Health (endurance)
Max Mana (willpower)
Max Stamina (combination of strength and endurance)
Move per turn (determined by character class or agility)

of course there would also be a leveling system with level and experience stats

the biggest problem I am facing right now is whether I should put additional underlying stats (hidden from the play) for leveling purposes (for example stats such as strength per level and max health per level) and how would i go for implementing said underlying stats with a class system, currently I am using an enum within the character object (calling them objects to avoid confusion with programming classes and character classes) to implement the class system and I have been considering on whether I should just write multiple objects extending on the character object for each character class or should I keep on using enums to represent different classes


texts: Closest to hardware/fastest pixel manipulation

texts:
I am currently working on the concept of a game, but I'm running into some problems.

For the game, I'd like to be able to directly change pixels on screen. However, all approaches that I tried so far resulted in my programs being rather slow, even without game mechanics attached to it.

Since a lot of games are also running on 60 fps with changing every pixel, you would expect it not to be hard to achieve such frame rates, if you could find the right way of changing pixels. The speed that I am aiming for is also at least 60 fps (if possible even on low-end hardware)

What is (or what library has) the fastest way to achieve this? It doesn't really matter what language the library is for, as long as I can get those high speeds.


texts: Farseer: How can I break a body into multiple pieces?

texts:
I created a breakable body but the pieces are not flying around if the ball touches it. What is wrong? Why is the breakable body not breaking into pieces?

I made a video and I enabled debugview, so you can see the bodies:

http://www.vidup.de/v/ihW2L/

//create the breakable body
BreakableBody Polygon;
List<Vertices> list = new List<Vertices>();
Vector2 _origin;
float _scale;
PolygonSprite = Content.Load<Texture2D>("polyplatform");
uint[] data = new uint[PolygonSprite.Width * PolygonSprite.Height];

PolygonSprite.GetData(data);
Vertices textureVertices = PolygonTools.CreatePolygon(data, PolygonSprite.Width, false);
Vector2 centroid = -textureVertices.GetCentroid();
textureVertices.Translate(ref centroid);

_origin = -centroid;
textureVertices = SimplifyTools.ReduceByDistance(textureVertices, 4f);

list = BayazitDecomposer.ConvexPartition(textureVertices);
_scale = 1f;
Vector2 vertScale = new Vector2(ConvertUnits.ToSimUnits(1)) * _scale;
foreach (Vertices vertices in list)
{
  vertices.Scale(ref vertScale);
}

Polygon = new BreakableBody(list, world, 1);
Polygon.MainBody.BodyType = BodyType.Static;
Polygon.MainBody.Position = new Vector2(graphics.GraphicsDevice.Viewport.Width / 200f, graphics.GraphicsDevice.Viewport.Height / 200f + 1.15f);
Polygon.Strength = 2;
Polygon.MainBody.CollisionCategories = Category.Cat11;
world.AddBreakableBody(Polygon);

//Draw the breakable body
spriteBatch.Draw(PolygonSprite, ConvertUnits.ToDisplayUnits(this.Polygon.MainBody.Position), null, Color.White, this.Polygon.MainBody.Rotation, _origin, _scale, SpriteEffects.None, 0f);


texts: Is my game "shovelware" if it uses images from Google Image searches?

texts:
I think this is a stupid question, but i want to know.

I just read Wikipedia about Steam software and i found a new word for me, that is Shovelware. Wiki says that :

  Low-budget, poor-quality games, released in the hopes of being purchased by unsuspecting customers, are often referred to as "shovelware".

So, let's say that i want to make a games. I have no budget, i use free game engine, free software and using free texture from internet (maybe from dedicated texture website like Textures.com or Poliigon.com) or download free image from google and make my own texture + material with that image using free software like GIMP.

Is my game considered as "shovelware" ?


texts: How to force Landscape Mode Unity3D Android Game?

texts: I am developing a small side project on Unity that will ultimately be for Android but I cannot figure out how to force landscape on the device and when I have tried it out the game just goes all over the place! I am using Unity Canvas and have spent a long time with binding position points etc. but I cannot work it out! Could someone please tell me how to force the phone into landscape mode?


texts: How to gradually decrease opacity of model?

texts:
I have been searching for this matter for a long time and slowly I begin to think that this option is not available in XNA for Windows Phone.

I am trying to get a 3D-Model to be drawn at 50% opactity/transparency.

The most promising piece I found is following:

//1. Set the alpha blend mode for the graphics device with:

graphics.GraphicsDevice.RenderState.AlphaBlendEnable = true;
graphics.GraphicsDevice.RenderState.SourceBlend = Blend.SourceAlpha; // source rgb * source alpha
graphics.GraphicsDevice.RenderState.AlphaSourceBlend = Blend.One; // don't modify source alpha
graphics.GraphicsDevice.RenderState.DestinationBlend = Blend.InverseSourceAlpha; // dest rgb * (255 - source alpha)
graphics.GraphicsDevice.RenderState.AlphaDestinationBlend = Blend.InverseSourceAlpha; // dest alpha * (255 - source alpha)
graphics.GraphicsDevice.RenderState.BlendFunction = BlendFunction.Add; // add source and dest results

//2. Set the alpha value in the BasicEffect for the model:
effect.Alpha = 0.5f; // Creates a 50% translucent object.

But GraphicsDevice.RenderState.AlphaBlendEnable isn't even available in XNA for Windows Phone.

So is there any way to achieve that effect?


texts: How to enable treat warnings as errors in Unreal Engine 4.24?

texts:
I've had little luck googling and it takes about an hour to build the engine (which I have to do if I'm to test if it works), so guessing is a bit time consuming.
I've seen advice to add the '/WX' flag to *.target.cs, as well to one of the functions in VCToolChain.cs, but I wasn't able to make it work.
Has anyone here enabled this and knows how it works? I don't think it matters, but I've been using VS2017.


texts: I have attached a post processing profile to my main camera for bloom and other similar effects. I know that when the game is running, the post processing works as I can see its effects. However, is there a way for me to see my post processing effects without having to run the game?


texts: 3D Sandbox game: Detecting when a block is no longer attached to the ground

texts:
I've been playing "Ace of Spades" recently, mostly because my son likes that. They have a feature that my son calls "gravity", but I don't know the official name. Anyway, the effect of "gravity" is that if you have a tower, and you remove the last block at the bottom, the game engine detects that the rest of the tower is not connected to the game world/ground anymore, and makes the tower fall apart.

My question is: how do you quickly detect that a part of the game world is not connected anymore (and which part)?

While "Ace of Spades" levels are fixed-size, an algorithm that also works for "infinite worlds" would be preferred. If that kind of problem has a specific name, I'd like to know that as well, since it helps when looking for possible implementations ...

I think this is somehow similar to how a garbage collector works: when there is no "path" from the ground to a block, then it is disconnected (garbage).


texts:
So, I'm just trying to draw a texture to two triangles that are the same size as the viewport, but it breaks up the image and distorts it. I have tried resizing the image file and everything, but nothing seems to work. Below is the code that maps the texture and draws the triangles.

 public void Render()
    {
        Texture texture = _textureManager.Get("splash");
        Gl.glEnable(Gl.GL_TEXTURE_2D);
        Gl.glBindTexture(Gl.GL_TEXTURE_2D, texture.Id);

        double height = 720;
        double width = 1280;

        double x = 0;
        double y = 0;
        double z = 0;

        float topUV = 0;
        float bottomUV = 1;
        float leftUV = 0;
        float rightUV = 1;

        Gl.glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
        Gl.glClear(Gl.GL_COLOR_BUFFER_BIT);
        Gl.glBegin(Gl.GL_TRIANGLES);
        {
            Gl.glTexCoord2d(leftUV, topUV);
            Gl.glVertex3d(x - width, y + height, z);
            Gl.glTexCoord2d(rightUV, topUV);
            Gl.glVertex3d(x + width, y + height, z);
            Gl.glTexCoord2d(leftUV, bottomUV);
            Gl.glVertex3d(x - width, y - height, z);

            Gl.glTexCoord2d(rightUV, topUV);
            Gl.glVertex3d(x + width, y + height, z);
            Gl.glTexCoord2d(rightUV, bottomUV);
            Gl.glVertex3d(x + width, y - height, z);
            Gl.glTexCoord2d(leftUV, bottomUV);
            Gl.glVertex3d(x - width, y - height, z);
        }
        Gl.glEnd();

    }

Here is the original image:

And here's the result:

The image is 1920 x 1080, and the viewport is 1280 x 720, but I'm not too sure that matters because I have tried resizing the image and nothing seems to work.

edit: this is a cross-post from stack overflow (I asked it here as well because nobody seemed to have an answer): https://stackoverflow.com/questions/26723470/opengl-texture-mapping-distorts-image


texts: What are the units when reading depth using glReadPixels()?

texts: Suppose I use glReadPixels() to read the depth of a pixel from the depth buffer. What are the units of this? Is it the distance from the camera? Or the distance from the near clip plane? And is the distance normalized to clip space, or in real units?


texts: RTS game: How to handle disconnects in a fully connected peer to peer architecture?

texts:
I'm currently working on a game in which I am considering implementing a networking architecture as described in this article: http://www.gamasutra.com/view/feature/131503/1500_archers_on_a_288_network_.php

In order for the implementation as described in the article to work, all peers need to be interconnected without any exceptions. Like so:

This works fine when everything is well. But I am wondering how to agree on disconnects in such a network. (Sadly something the article does not go into). It is relatively easy if one client goes down. Just give every client a timeout, and if a client does not respond for a certain time, it is removed from that client.

However, how should the system solve a case in which one client does not respond to another, but still responds to all others. In such a system the following could happen, resulting in a invalid state:

Of course this can be solved by giving one of the clients some kind of "master" role. It being the only one that can decide whether or not to disconnect other clients. But I'm wondering if it can be achieved in a pure p2p network.

Note I realize this case is not one that can likely occur "naturally". But I want to prevent players from being able to ruin a networking game for others by playing a trick like this by using the firewall for example.


texts:
I'm trying to write a randomly patrolling AI for my 2D Platformer. The AI already has a ground checker function which checks if there are tiles nearby or not. What I want to do is randomize its actions and create an illusion of a somewhat "sentient" enemy. What I tried to create below is using the built in RNG to make the enemy either jump, change direction, or keep moving.
The problem is, it doesn't seem to work properly. The enemy just jumps every second I want it to change behaviour. The change direction functions, however, don't occur as frequently. I need to know what I've done wrong here. Thanks.
void Update()
{
      //RNG
      behaviour = Random.Range(0,3);
      jumpSpeed = Random.Range(1,5);

      //clock
      timer += Time.deltaTime;
}

  //time
    private float waitTime = 2.0f;
    private float timer = 0.0f;

 void MoveRandomizer()
{
    if((Mathf.Round(timer%waitTime)) == 0)
    {
        if(behaviour == 0)
        {
        movingRight = false;

        }
        if(behaviour == 1)
        {
        movingRight = true;

        }
        if(behaviour == 2)
        {
        rb.velocity = new Vector2(rb.velocity.x, jumpSpeed);
        }
    }

}


texts:
I've been messing around with SFML, it's my first experience with C++ and I'm enjoying it. But I'm wondering how to publish my game onto anything other than a native platform. Noting that this is my first time dealing with porting and C++, could anyone explain this to me as if I'm 5?

Thanks in advance.


texts: How was the world game market segmented in 2011?

texts:
Is there a source (or perhaps several) presenting how was the world game market segmented in 2011 (or does anybody know themselves)? For example:

How many casual gamers there are? What is the total business, of which how much in virtual item sales?
How many console gamers there are? How much is spent in hardware, how much in software?
How many mobile gamers there are? How much is spent in hardware, how much in software?

And how all above is in different regions / countries?


texts: Rendering Problems(Artifacts, Flickering) with the Mirage Solo VR Headset

texts:
Im getting some strange flickering artifacts when testing on device (Mirage solo), this problem occurs on Unity 2018.3.2 and Unity 2019.1.2. Its not happening on other devices such as the OculusGo, Google Pixel, Samsung s7,s9. It seems to be only occuring on devices that use Qualcomm Adreno 540 GPU. Has anyone else encountered anything like this if so, did you fix it and how? The Environment is using a custom shader, the robot character is simply using a unity standard shader and there is a hologram at the side(right) which is using a custom shader.

Hardware: Snapdragon 835 SoC Qualcomm Adreno 540 GPU

Video: https://streamable.com/

Screenshots:

Bad:

Good:


texts:
I've tried wording and rewording this question in various forms of search and can't seem to find an answer to it. If I'm wording it wrong and/or just not finding the right information, feel free to throw me a link.

Here's what I'd like to accomplish:
I want to do several different processing effects with GLSL, on several different images - each image a different effect - and then retrieve the end result and combine all the images to form a finished result.

Then, I want to save the finished product to an image I can later reuse.

So basically:

Make non-transparent blurry, greyscale, whatever else...
Do different effects on 3-10 images...
Layer all images on top of one another...
Flatten the images to result in a single image that looks identical...
Save to PNG.

I know 'save to PNG' isn't one of those things OpenGL can do and I have something I can use for that. However, I'm running into problems thinking up a way to retrieve the pixels from the end result (From the shader) and flatten them into a single result (in language of choice/OpenGL), and then get the final pixel data.

This doesn't have to be done in near realtime (Of course). It'll only happen when specific events are triggered, and only when absolutely necessary during those events. The events trigger 'permanent until further notice' situations, which is why this would be useful - on top of the idea of having multiple images being drawn over one another every frame being reduced to one, of course.

Thanks!


texts:
The size (in bytes) of games have been growing over time. There are probably many factors contributing to this: trailer/cut scene videos being bundled with the game, more and higher-quality audio, multiple levels of detail being used, etc.

What I'd really like to know is how the size of 3D models and textures that games ship with have changed over time. For example, if one were to look at the size of meshes and textures for Quake I (1996), Quake II (1997), Quake III: Arena (1999), Quake 4 (2005), and Enemy Territory: Quake Wars (2007), I'd imagine a steady increase in file size. Does anyone know of a data source for numbers like this?


texts: How can I support different screen resolutions without scaling the sprites?

texts:
I already tried to support different screen resolutions with scaling the sprites. But if I scale my sprites from 800x480 to 1920x1080 pixel, then the sprites look blurry. I want to use different sprites for each resolution to avoid the blurry effect.

How can my game choose the right sprite for each resolution? How can I do that?

How can I calculate the right measures for every sprite?
For example, I use a 64x25 pixel sprite with a 800x480 pixel resolution. If I change the  resolution to 1280x720, what should then be the measures of the sprite?

Can I calculate the measures like this?

sprite measures(1280x720): Width = 1.5f*64= 96, Height = 1.5fx25= 37,5

Should I round up or round down the height(37,5 pixel) of the sprite?

I create a Windows Phone game with Monogame, and I want to support every resolution from 800x480 to 1920x1080 pixel without scaling.


texts: How to report bugs found on procedurally generated levels?

texts:
There is many topics on how procedural generating works but I couldn't find any info on how to test and - what's more important - how to report bugs that may occur on procedurally generated levels. What is the best way to describe a bug, for example related to level design, on a map that will look different each time you play new game? What information should be included in bug report so reproducing it would be easier for level designer, level artist, etc. and then also during regression process?

EDIT:
It is worth mentioning that the game, I am preparing to test, is in very early phase of developing and is constantly changing along with the systems responsible for generating levels. The purpose of this research is to learn how to describe bugs (what info to include in report) so the regression in a changing environment would be as less time consuming and as effective as possible.


texts: Common practice when handling sprite animation

texts:
Let's say I'm using the following sprite as a sample to try LibGDX Animation and TextureRegion.

http://www.smackjeeves.com/images/uploaded/comics/7/8/78bc6b62fEySW.gif

As you can see, the provided image above has different width & height per image. The width when Zero performs a slash is different when Zero stands.

Is it a good practice to create a padding / margin for every image so they have similar width & height. Or should I just have all the sprite cramped like that and try to handle it in the backend?

Thanks


texts: Baking lights causes weird seams on meshes. How to avoid it?

texts:
I'm trying to bake lightning in the simple scene with some imported geometry.
The result is weird seams near the edges of the meshes even there is no free space between them.
How to avoid it and just simply bake that lightning? This is just something that should not be.


texts: How do i draw depth complexity(overdraw) in directx 11?

texts:
I want to read the stencil value in the shader so I can set colors for different depths.

What I understand. Make a loop after the scene is rendered but before is is presented.
so a loop with the number of colors(k) and in the loop, use the code:

 md3dImmediateContext->OMSetDepthStencilState(RenderStates::DrawDepthDSS, k);

This is what I know. What are the other steps? like to send the depth to the shader?

..I have this code for the shader

   Texture2D<uint> txStencil : register (t0); // set the corresponding register
float4 PSStencil(float4 pos: SV_Position) : SV_Target
{
    uint stencil = txStencil.Load(int3(pos.xy, 0));

    // debug output
    if (stencil == 1) return float4(0, 1, 0, 1);
    else return float4(0, 0, 0, 0);
}

But how do I send the shader the stencil value?


texts: Bodies are colliding but refusing to rotate in Box2D

texts:
I'm running box2d in C++ and hooking it up to C# via p/invoke. All physics stuff occurs in C++.

My problem is that bodes know when they are colliding and do so with great precision. However if I have two boxes which are 10x10 units, one located at the origin and is static while another is set 30 units in the sky 4 units across and is dynamic, when the dynamic box falls and hits the static one it stops falling but doesn't turn and slide off the edge.

Here's a screenshot of what I mean:

The box on top is as far to the left as it possibly can be, any further left and it will fall past the box on the bottom. There is barely a pixel overlap that's keeping the top box there. As you can see it's not rotating to fall off.

This also happens (again only the lowest most box is static, the rest fell down a distance to get there),

Any ideas what I'm doing wrong?

My code for creating boxes is as such:

extern "C"
int CreateBox(b2Vec2 dim, b2Vec2 pos, bool dynamic, int worldid)
{
    dim.x /= 100.0f;
    dim.y /= 100.0f;
    pos.x /= 100.0f;
    pos.y /= 100.0f;

    World &g = GetWorld(worldid);
    b2BodyDef bodef;

    bodef.type = b2_staticBody;
    if(dynamic)
    {
        bodef.type = b2_dynamicBody;
    }
    bodef.position = pos;
    bodef.angle = 0;
    b2Body* pBody = g.m_pWorld->CreateBody(&bodef);

    b2PolygonShape groundBox;
    b2Vec2 center = b2Vec2(-dim.x / 2.0f, -dim.y / 2.0f);
    groundBox.SetAsBox(dim.x / 2.0f, dim.y / 2.0f, center, 0);
    for(int i = 0; i < b2_maxPolygonVertices; i++)
    {
        b2Vec2 vert = groundBox.m_vertices[i];
        vert.x += dim.x / 2.0f;
        vert.y += dim.y / 2.0f;
        groundBox.m_vertices[i] = vert;
    }

    b2FixtureDef fixtureDef;
    fixtureDef.shape = &groundBox;
    pBody->CreateFixture(&fixtureDef);
    //fixtureDef.density = 10;

    pBody->SetUserData((void*)++g.m_actorid);

    g.m_bodies.push_back(pBody);

    if(dynamic)
    {
     //   pBody->SetAngularVelocity(0.5f);
    }

    return g.m_actorid;
}

and I create the boxes in C# like so:

m_worldid = CreateWorld(ToB2(new Vector2(0, -1.8f)));

m_boxID1 = CreateBox(ToB2(new Vector2(50, 50)), ToB2(new Vector2(-51,300)), true, m_worldid);
m_boxID2 = CreateBox(ToB2(new Vector2(50, 50)), ToB2(new Vector2(0,0)), false, m_worldid);

Using the box ids I grab positions and rotations from the C++ code (and the get functions take into account that I've /= 100 the dimensions), it all works fine on that front, code here for those interested:

extern "C"
ActorTransform BodyTransform(int bodyid, int worldid)
{
    World &g = GetWorld(worldid);

    for(int i = 0; i < g.m_bodies.size(); i++)
    {
        if( (int)g.m_bodies[i]->GetUserData() == bodyid)
        {
            ActorTransform c;
            c.Position = g.m_bodies[i]->GetPosition();
            c.Rotation = g.m_bodies[i]->GetAngle();
            c.Position *= 100.0f;

            return c;
        }
    }
}

Another interesting thing to note is if I set an angular velocity on the box it actually is physically represented on screen and it can cause the box to fall off, setting rotatens on bodes also seems to work.

Actually continuing on from setting angular velocities. I found that if I set an angular velocity just once the velocity doesn't go away, even after it lands on the static box it continues to rotate as if it were a motor or something. I'm guessing this has something to do with my core problem since bodies aren't meant to maintain an angular velocity that was set on them just once..

so any ideas?


texts: How Can I See, Have, Use, and Not Compile Available Assets in Unity?

texts: In short, I own a bunch of asset packages. I don't know what's in them until I bring them into Unity. Some of them have scripts that are not compatible with my current Unity build, but I may not care, I still want to see what I have and perhaps even fix them if I want them. My problem is that I'm having to import everything into my project just to see what I have and then further I can no longer run my project because these assets have compiler errors even though I'm not using them in my scene. So what can I do here? I don't want it compiled, using a "~" at the end of the folder as often suggested makes it disappear entirely so I can't even see the files, and yet I still want to see everything and choose what I want. Am I missing some process flow here? This really sucks.


texts: How to read a color of a pixel from texture (cocos2d-js)?

texts: How to read a color of a pixel at [x,y] from a texture (in cocos2d-js)?


texts: OpenGL ES 2.0: Calculated Cube Vertex Normals Verification

texts:
Could I kindly ask to confirm, that the calculated normals are correct, please? I have calculated them on my own, but my testcube is still strangely lighted within OpenGLES 2.0.

The vertices were exported from 3D authoring application.
The vertex normals were calculated using matrix cross product.
The vertex and fragment shaders I were exact copies from the book, so there should not be a bug.

The output in OpenGL looks like the sphere is lighted from its bottom. Moreover, it looks, like the box is visible from inside, as the top part is always transparent. Any idea, where can be a problem?

Added:

The vertex normals are calculated based on triangulated quad-polygons. The triangulation is performed internally, by the 3d application. Vertices/ indices are generated by calling API calls of that application.

#begin 8 vertices
vs 24
v -25.000000 -25.000000 -25.000000
v 25.000000 -25.000000 -25.000000
v -25.000000 25.000000 -25.000000
v 25.000000 25.000000 -25.000000
v -25.000000 -25.000000 25.000000
v 25.000000 -25.000000 25.000000
v -25.000000 25.000000 25.000000
v 25.000000 25.000000 25.000000
#end 8 vertices

#begin 12 faces
fs 36
f 0 2 3
f 0 3 1
f 0 1 5
f 0 5 4
f 0 4 6
f 0 6 2
f 1 3 7
f 1 7 5
f 2 6 7
f 2 7 3
f 4 5 7
f 4 7 6
#end 12 faces

#begin 8 calculated normals
ns 24
n -0.577350 -0.577350 -0.577350
n 0.816497 -0.408248 -0.408248
n -0.408248 0.816497 -0.408248
n 0.408248 0.408248 -0.816497
n -0.408248 -0.408248 0.816497
n 0.408248 -0.816497 0.408248
n -0.816497 0.408248 0.408248
n 0.577350 0.577350 0.577350
#end 8 calculated normals

I use OpenGL ES 2.0, but that should not be relevant at this moment.

Update:

I can confirm now, that the calculated vertex normals are correct, and can therefore be used by others, to verify correctness of their triangulated cube vertex normals calculations.

However, I still have a problem that all the vertices, which are in positive z axis, are not rendered. Not sure if they are culled, but I have pretty large frustum. Vertices in the -z axis are kept, so the rendered mesh looks like cut in half, as it is position in 0 z-axis.

This lines below show that I should not concsicously setup small render area:

mProjection = glm::perspective (45.0f, (float)WINDOW_WIDTH / (float)WINDOW_HEIGHT, 1130.0f, -1130.0f);

mViewTransformation = glm::lookAt(glm::vec3(vIntCamera.x, vIntCamera.y, 1130.0f), glm::vec3(vIntCamera.x, vIntCamera.y, 0.0f), glm::vec3(0.0f, 1.0f, 0.0f));

Any ideas, please, what else should I check?

Solved:

Eye position of the camera (in glm::lookAt() function) should be above the top of the perspective frustum, defined by glm::perspective().

Thanks for your support guys, especially with the upper part of my question.


texts: How does Unity's QualitySettings.masterTextureLimit work?

texts:
I'm trying to get to the bottom of how masterTextureLimit works, but my results have been inconsistent so far.

I created a massive sprite (8192x8192), and I'd like to resize it at runtime to save performance. The idea is to start with large sprites and then resize based on the monitor's resolution. Here's what happens at different settings:

Texture import size 8192, masterTextureLimit 0, mipmaps off: ~2ms
Texture import size 8192, masterTextureLimit 0, mipmaps on: ~1.5ms
Texture import size 8192, masterTextureLimit 1, mipmaps on: ~1.5ms
Texture import size 4096, masterTextureLimit 0, mipmaps off: ~0.9ms
Texture import size 4096, masterTextureLimit 0, mipmaps on: ~0.9ms
Texture import size 4096, masterTextureLimit 1, mipmaps on: ~0.83ms

Looking at these results, I have a couple of questions:

If masterTextureLimit is supposed to halve the texture resolution, why did it not affect performance while setting texture size to 4096 did?
Why did turning mipmaps on improve performance at 8192 texture size but not at 4096? My camera is orthographic, and it's only 1 unit away from the sprite.


texts: Unity: Can I use sprites for tiles to overlay a grid over a plane mesh?

texts:
I have a plane mesh in Unity. I have various other meshes on this plane (props) with tags that denote the areas under these props are unwalkable. I raycast, project and generate a grid on this plane and I have a map of walkable regions and unwalkable regions. This grid is a List of GridCell objects, I'm omiting the details.

Now I want to visually show this grid, so I attach a mesh renderer to the Gridcells and attach a mesh. Looking good.

My question is, can I use 2D sprites for these cells instead of a 3d mesh and still get the visual overlay on the grid plane?


texts: Is a HashTable the best way to store replay data in C#?

texts:
I'm looking to make a deterministic replay in my 2D game. I want to follow a similar approach to braid in storing the relevant information every frame (at 60 frames per second).

I wanted to know what the best way to store this information is. My friend suggested using a hashtable and being new to C# I'm sort of leaning towards just using an array, but I wanted to see if there were other schools of thought.

I've read posts like this How to design a replay system and this "Super meatboy"-ish replay which were very informative, but not very specific to C# and XNA.

My game is 2D and does not have all that many moving parts. At any given time there is probably less than 50 bodies I would need to track the position/rotation of.

Curious to hear your thoughts.


texts: When should you label something as a micro transaction, DLC or expansion?

texts: Is it based on monetary cost, filesize, perceived value or something else entirety?


texts: How to draw a BitmapFont every user click

texts:
Im starting learning the libgdx framework and I want to "clone" some games.
I know how to handle touch with

if(Gdx.input.isTouched())

But how do I render new fonts every time user clicks on the screen? (Like the Numbers going up and desapearing)
I tried creating new objects, and made a array to store all "y" positions, but both no success.


texts: What is the perfect sprite size for new ipads with retina displays

texts:
The graphic designer is sending me huge sprites 3000px in width drawn by hand. And now the company is hiring a professional painter to paint huge oil paintings for the game for other levels. Nothing digital. I receive PNG.

The game is a clicking game where you find hidden stuff, puzzle. So the slightest details matters. Everything must look so perfect. Primary devices are the ipads with retina displays but the game must be cross platform.

What is the size I should ask the painter to paint? And the graphic designer to draw?
What is the best size for a background PNG? And what size is the items? currently I resize to 600 * 400 the background and the items are 100px by whatever height photoshop deems good.

I'm afraid to go smaller than that, even though technically I should be able to. Another programmer working on the game, resized them down so much and they got stretched.


texts:
Im making simple 2D space shooter with use of html5 and JavaScript.
The idea is simple, shoot down as many aliens as you can.
I made it to the point where I have player which can move and rotate, but I want the player to move in the angle, like 80s Asteroids (you set angle then press forward key and ship goes forward in that angle)

my movement now is simple:
up = y -= speed * delta time
down y += speed * delta time
left x -= speed * delta time
right x += speed * delta time

my rotation is made like this:
ctx.save();
ctx.translate(this.x + this.w / 2, this.y + this.h / 2);
ctx.rotate(this.angle);
Draw.Rect(ctx,this.w /2 * (-1),this.h / 2 * (-1),this.w,this.h,"red",1);//context,x,y,w,h,color,opacity
ctx.restore();

angle:
if(keys.e)this.angle += 0.1;
if(keys.q)this.angle -= 0.1;


texts: In Unity, how do I make a 3D flight arc preview?

texts:
I'm stuck on how to make a preview trajectory for a projectile appear when holding a button. The trajectory should start at a certain position on the scene and end wherever the player points their mouse. On mouse click, a projectile should be launched along that trajectory with the clicked position as its target.

How can I do this?


texts:
First theoretical question. What is better (faster)? Develop your own gpgpu techniques for physics simulation (cloth, fluids, colisions...) or to use PhysX?
(If i say develop i mean implement existing algorithms like navier-strokes...)

I don't care about what will take more time to develop. What will be faster for end user? As i understand that physx are accelerated through PPU units in gpu, does it mean that physical simulation can run in paralel with rastarization? Are PPUs different units than unified shader units used as vertex/geometry/pixel/gpgpu shader units?

And little non-theoretical question: Is physx able to do sofisticated simulation equal to lets say Autodesk's Maya fluid solver?

Are there any c++ gpu accelerated physics frameworks to try? (I am interested in both physx and gpgpu, commercial engines are ok too).

Edit: Simulation does not have to be realtime i'm thinking just about acceleration.


texts: How should multiplayer games handle authentication?

texts:
I've been lurking around to understand how an authentication system would work in games, but after many searches, it seems that working with ssl/certificates could be a little complicated for just a multiplayer game with a lot less capacity than an MMO.

I know that successful multiplayer games need this, but I'd like to check if other multiplayer games commonly take this precautions.

EDIT: I'll describe what I have in mind. The server not only handles game logic, but also authentication. So, in order to play on a specific server (that everyone could start), you first need to register an account on the server, and each time you want to play there, login as usual (password/name user).

My question is, would not providing a secure channel for logging in/registering an account be forgivable/understandable in this context? Also I'm interested to know how games with a similar architecture would handle this matter.


texts:
Currently, I am learning about entity-component-systems, and I have a question concerning the components. How would the systems handle dependent components?

For example, In a 2D game, I have a game object entity that has the following components:

RenderComponent - contains current character sprite
AnimationComponent - contains set of sprites and frame index
CharacterStateComponent - tells what the character is actually doing

Given player input, such as "move_forward", I am not sure which of the following procedures should happen:

System Polling:

Input notifies StateSystem.
StateSystem updates CharacterStateComponent.
AnimationSystem reads CharacterStateComponent changes.
AnimationSystem updates AnimationComponent.
RenderSystem reads AnimationComponent changes.
RenderSystem updates RenderComponent.
RenderSystem draws RenderComponent normally.

All-in-one Updates:

Input notifies CharacterSystem.
CharacterSystem updates CharacterStateComponent, AnimationComponent and RenderComponent.
AnimationSystemiterates AnimationSystem normally.
RenderSystemdraws RenderComponent normally.

I am not quite sure how the engine would respond to a change in one component that is suppose to update other components, as well. I believe there will be performance issue, when it comes to each system having to poll its prerequisite component changes (as shown in System Polling).

How would the entity system handle dependent components?


texts: Unreasonable CPU consumption for server build with nographics

texts:
I have built my game in server mode on Mac OS and attached profiler to it. In profiler I can see unreasonable high cpu load.

Other scripts take a lot of cpu time. How can this be optimized?

Vsync takes a lot of time otherwise. How can it be since I have disabled VSync, built as server, run with -nographics and even removed cameras and UI?


texts: Controlling the movement of player by sprite using Mouse

texts:
I want to move the player by pressing down on the mouse and moving around by dragging. The player won't move to the position of the mouse. Instead it should be relative to the players current position.

https://youtu.be/oGSpX6GEYa0?t=5m55s

The way this works, your finger can be anywhere on the screen, and when you move down, the player moves down. This is what I have so far, but it's not as elegant as I want it to be. For example, if your mouse is not moving, it still applies acceleration.

public static inline var EASING:Float = 0.1;

private var mouseX:Float;
private var mouseY:Float;
private var vx:Float;
private var vy:Float;
private var distance:Float;

/**
 * Function that is called once every frame.
 */
override public function update(elapsed:Float):Void
{
    if (canMove == false) {
        return;
    }

    if (FlxG.mouse.justPressed) {
        this.mouseX = FlxG.mouse.screenX;
        this.mouseY = FlxG.mouse.screenY;
    }

    // if we are pressing down, we should move ronnie
    if (FlxG.mouse.pressed)
    {
        vx = getVelocityX();
        vy = getVelocityY();
        distance = getDistance(vx, vy);

        if (distance > 0) {
            this.x += vx * EASING;
            this.y += vy * EASING;
        }

    }

    if (FlxG.mouse.justReleased) {
        //
    }

    super.update(elapsed);
}

/**
 *
 * @return
 */
function getVelocityX():Float
{
    return FlxG.mouse.screenX - this.mouseX;
}

/**
 *
 * @return
 */
function getVelocityY():Float
{
    return FlxG.mouse.screenY - this.mouseY;
}

/**
 * Return distance
 *
 * @return
 */
function getDistance(vx:Float, vy:Float):Float
{
    return Math.sqrt(vx * vx + vy * vy);
}


texts:
When I add component like RigidBody2D or BoxCollider, Can I set offset / size in scene window in Unity?
Other than manually set value in inspector form, then look in scene window whether it is fit or not?


texts:
I'm really stucked. I couldn't understand what does Vector3 state.
When I look Unity Vector3 documentation it says

Representation of 3D vectors and points.

According to this sentence, a Vector3 can state a point or a vector in space.
But When I go into other documentation about Vector3 it really confused me.
For example When I look Vector3 Constructor documentation it says

Creates a new vector with given x, y, z components.

So that means Vector3 states a vector.
But When I look Debug.DrawLine(Vector3 startpoint, Vector3 endpoint)
it says startpoint and lookpoint are points in world space.
So according to this, Vector3 is a point not a vector
I can increase the examples.
For example when I go into transform.position documentation it says,

The world space position of the Transform.

So it says Vector3 is a position(that means point. I think you can't state a position with Vector)
But when we try to change a position of gameobject with transform.position we again use Vector3
and that state a vector.Because you can't change position of a gameobject with point. You could use Vector
So, what does a Vector3 state ?


texts:
I am quite confused over how networking works in XNA. I'm currently developing a game for Xbox. I want to create a multiplayer environment and read some tutorials about it.

But I'm confused over how packets are transmitted over the network - E.g.; what is the difference between a LocalNetworkGamer, a NetworkGamer and a LocalGamer? Why do I need to iterate over all LocalGamers when reading packets?

I know that's not a typical SE question, but can anyone point to a tutorial that explains how the networking operates as opposed to how to use it?


texts: What data structure to use for the map in Pac-Man?

texts:
I am trying to make a Pac-Man game in C# using GDI+. I have done some basic work and I have previously replicated games like Copter-It and Minesweeper, but I am confused about how I can implement the map in Pac-Man. I mean: which data structure to use, so I can use it for moving AI controlled objects and check collisions with walls.

I thought of a 2D array of ints but that didn't make sense to me. Looking for some help.


texts: Buttons only trigger right/left movement once, not continually

texts:
I have a Unity mobile project where I am trying to use right/left movement using two UI buttons situated accordingly.  The issue is that it only moves the player to the right/to the left one time, not continually when the player is holding the button down.
I'd like the player to be able to hold down a certain button and have the character move constantly in that direction until the button is released.  I've tried making the void into a Coroutine, but nothing working works.
Here is my code.  (rightCallable and leftCallable are attached to the buttons).
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class playerController : MonoBehaviour
{
    public GameObject player;
    public float speed = 1000f;
    public GameObject left;

    //this is so the player may also use the A and D keys if they want, and it works fine.
    public void Update()
    {
        var movement = Input.GetAxis("Horizontal");
        transform.position += new Vector3(movement, 0, 0) * Time.deltaTime * speed;
    }

    //Below is what isn't working
    public void rightCallable ()
    {
        StartCoroutine("moveRight");
    }

    public void leftCallable ()
    {
        StartCoroutine("moveLeft");
    }

    IEnumerator moveRight()
    {
        var movement = 1f;
        transform.position += new Vector3(movement, 0, 0) * Time.deltaTime * speed;
        yield return null;
    }
    IEnumerator moveLeft ()
    {
        var movement = -1f;
        transform.position += new Vector3(movement, 0, 0) * Time.deltaTime * speed;
        yield return null;
     }
 }


texts: Is there any way to change texture filtering globally in Direct3D 11?

texts:
One of the major changes I have encountered between Direct3D 9 and Direct3D 11 is the new API for setting up texture sampling. In D3D9, it was sufficient to simply set a given value of a given property to a given sampler index and safely assume that state would remain (and be unaffected by other state changes) for as long as was needed by the application.

direct3Ddevice->SetSamplerState(samplerIndex, D3DSAMP_MAXANISOTROPY, value);

However, in D3D11, the process is a little more involved. First you create and populate an object of type D3D11_SAMPLER_DESC, then from that object create an ID3D11SamplerState, then apply that to a sampler index.

D3D11_SAMPLER_DESC desc = CD3D11_SAMPLER_DESC(CD3D11_DEFAULT());
desc.MaxAnisotropy = value;
ID3D11SamplerState * state = 0;
direct3Ddevice->CreateSamplerState(&desc,&state);
direct3Dcontext->PSSetSamplers(samplerIndex, 1, &state);

I understand that this is designed to minimise the number of queued requests per frame by batching potentially a whole bunch of state changes into one object... However, if the developer wanted to, say, put a global anisotropic filtering setting in their game's options screen, they'd need to keep copies of the sampler descriptions of every sampler they use for every shader (to ensure that no other parameters would get lost), then iterate through all of those copies to apply the new filtering level, and recreate all those state objects.

Surely there must be a simpler way to apply a single sampler setting globally for an application?


texts:
I've been trying to nail down a walking animation with libGDX.  I'm making an RPG with the character that can move up, down, left, and right.  I have this movement in a spritesheet.  I've been following a youtube tutorial called Java Tiled Map Game which can be found here: http://www.youtube.com/watch?v=qik60F5I6J4

He does a better job then some of explaining what the code does but he glosses over the part where he gets his character to do a walking animation (by which I mean he doesn't show it at all).

I then moved to the tutorial found here: http://obviam.net/index.php/getting-started-in-android-game-development-with-libgdx-tutorial-part-2-animation/

But this tutorial tells exactly what needs to be done in regular words and then just gives a block of code.  I already know what I need to do in regular words but I'm not trying to learn english but programming which is a completely different language.  I'm sure I could copy and paste that code and edit it to do what I need but I wouldn't understand HOW it works only THAT it works.  I want to know the how of it all.  I'm new to libGDX and this is my first RPG game.  I really want learn how to do it myself instead of relying on others.

My question is simply this:  Do you know of a tutorial which shows and (more importantly) explains how to do a simple walking animation?  I'm hoping you can supply one for me.


texts: Rotate around an axis function for euler angles representation

texts:
For a 3d game i need a function to rotate an euler representation around an arbitary axis by an angle.
For example an object is rotated with euler angles (0,90,0). Now the object should be rotated by 100 degrees around the axis (0,1,0). The resulting angle will be (0,190,0) using rotation order YXZ.
In this case I can add the angle to the euler value of the axis, however for an arbitary axis this will not work.
Problem with Quaternions & Rotation matrices:
With these representations the resulting rotations will always be smaller that 180 for each axis. I need the rotation to be lerped afterwards for example from (0,0,0) to (0,720,0).
Basically I am searching for a way to display euler angles like most of the 3D editors. When you rotate an object around any arbitary axis rotation might be larger than 360 in the editor, like (420,720,15).


texts: Necessary design skills to develop games using Unity, UDK, etc

texts:
With my question I want to know if DESIGN 2D/3D skills are necessary in order to create a game using some engine like UDK or Unity.

I have experience as a developer, and experience with openGL, I have also some experience with 3dMax, but Im NOT able to design something from scracth. I simply dont have the skills.

In this kind of engines, is there a way to create and customize levels or characters for example?

Thinking in something related, I will think in the character editor of games like World of Warcraft, etc. I would like to know if the creation of levels and characters would be  like that.


texts: Centralized event system using dictionary

texts:
I'm trying to make a centralized event system for my unity game - a central hub where other parts of the game can register/broadcast their own types of events. This means I have a singleton GameEventSystem that is globally accessible.

This is an example structure:

I have tried to combine multiple sources, trying to figure out how to do this, and this is where I got.
I have a Dictionary where the key is Type(that supposed to be T : GameEvent), and the value is GameEventListener<GameEvent>, GameEventListener is supposed to be Action<T : GameEvent>.
What I'm trying to achieve is a singleton class that manages Dictionary<T : GameEvent,  GameEventListener<T : GameEvent>>.

The implementation of RegisterListener:

Type eventType = typeof(T);

GameEventListener<GameEvent> listenerTemp;
if (EventListeners.TryGetValue(eventType, out listenerTemp))
{
    listenerTemp += (GameEventListener<GameEvent>)listener;
    EventListeners[eventType] = listenerTemp; // Copy the newly aggregated listener back into the dictionary.
}
else
{
    listenerTemp += (GameEventListener<GameEvent>)listener;
    EventListeners.Add(eventType, listenerTemp);
}

And this would be the UnregisterListener:

Type specificGameEventType = typeof(T);
if (!AnyListeners(specificGameEventType, this.EventListeners))
{
    // No one is listening, we are done.
    return;
}

EventListeners[specificGameEventType] -= (GameEventListener<GameEvent>)listener;

Passing an Action<UnitDiedEvent> to RegisterListener will lead to InvalidCastException: Specified cast is not valid., at the following line:

listenerTemp += (GameEventListener<GameEvent>)listener;

Why can't I cast a GameEventListener<UnitDiedEvent> class, to GameEventListener<GameEvent>?

Is there a better approach to achieve a centralized event system in unity?
From my research I can't just make GameEventSystem a static class and expect it to be accessed by the rest of the game objects/components. That makes global systems/managers like this one a little problematic to instantiate and access.

I think I'm not fully grasping events/delegates and generics as a whole to tackle this on my own.


texts:
I'm trying to render a smooth terrain with Direct3D. I've got a 50*50 grid with all y values = 0, and a set of 3D points that indicate the location on the grid and depth or height of the "valley" or "hill".
I need to make the y values of the grid vertices higher or lower depending on how close they are to each 3D point. Thus, in the end I should have a smooth terrain renderer.

I'm not sure at all what way I can do this. I've tried changing the height of the vertices based on the distance to each point just using this basic formula:

dist = sqrt(a² + b² + c²)

where a, b and c are the x, y, and z distance from a vertex to a 3D point.
The result I get with this is not smooth at all.

I'm thinking there is probably a better way.

Here is a screenshot of what I've got for the moment:
https://dl.dropbox.com/u/2562049/terrain.jpg


texts:
I have a small trouble with my collsion detection system, ill show it on images.
im checking the detection by using that logic with example when moving to the right:

obj.x+obj.w+obj.mov > block.x
obj.x+obj.w+obj.mov < block.x+block.w
and
(
    obj.y <= block.y
    obj.y+obj.h >= block.y
    or
    obj.y <= block.y+block.h
    obj.y+obj.h >= block.y+block.h
)

when object size and block size are equal, the problem appears

the 3 blocks are detected

1 = is the trouble maker

2 = isnt making much problem, since its on same axis

3 =  is working

the 1 block is detected since its within Y + H area of the block (

it happens when the object is sticked with 0 pixel distance.

im using motion based on min(mov,dist) [dist is Y distance between object and block] function and when it tries to move to the right, it gets moved like that

because min(mov,dist) will become negative when getting distance to object 1 instead of 3, making it buggy

im asking if its possible to prevent block 1 (block 2 optionaly) when that situation happens. (or atleast change the logic)


texts: Can letting players take resources from others prevent inflation despite the lack of money sinks?

texts:
For a long time I've been idly thinking about a competitive game with strong collection elements with such a rule that players will win or lose resources at the expense of each other during each match.

Sorry if this seems unclear; let me provide a concrete example: Chess with an ecosystem.

Each player starts with a standard set of a king, a queen, two bishops, two knights, two rooks, eight pawns. Each time, during a match, a figure or pawn is captured, it permanently goes to the player who captured it (promoted pawns count as pawns for this purpose, not as whatever they were promoted to). This is the only way players can earn pieces¹.

The game is divided into several leagues: each league restricts the total value of pieces both players may start with. As long as each player only uses pieces they own and their value doesn't exceed their league's maximum, they can start with any pieces they desire. Thus each player who's just founded their account will start at a mediocore league that enforces the total value of pieces of up to 43 (8 pawns * 1 + 2 bishops * 3 + 2 knights * 3 + 2 rooks * 5 + 1 queen * 9 + one king * 4 = 8 + 6 + 6 + 10 + 9 + 4 = 43); if they lose pieces they will lose access to the starting league and be demoted to lower leagues, down to the lowest league that only accepts the total value of pieces of 5 (meaning that, aside from the mandatory king, it only allows one pawn); if they earn pieces they are promoted to higher leagues that allow them to start with more total material. (Players may also play lower leagues than their league if they wish, but not higer). If they lose so much pieces they cannot even play at the lowest league, they lose permanently and have to start with a fresh account.

Now from this follows that since there are no sinks and the total material of the game will only be increasing with people founding more and more accounts. From this we can expect that as more and more players lose permanently, we will have more and more players having hundreds and thousands of pieces, so inflation happens.

But if, regardless of their league, players are always matchmade according to their elo and if there are so many players that the matchmaking works and is unpredictable (granted, big 'if's...), their winrates should sit at 50%! Thus their earn/lose balance should be around zero. Pieces have a fixed cost: Getting them requires winning against an opponent of equal skill.

Ugh... Looking at the problem from these two different perspectives yields conflicting results. What am I missing? Would inflation happen in such a game?

Note this chess example is really only an example: I only provided it because it is the only concrete example I could muster. However, we can easily think about a collectible card game with a system similar to this, and I suppose such a TCG example would be even better here.

¹ Well, almost. If a player loses a king and have no more kings they must buy another king. To this end they must sell other pieces: pawns for one gold piece each, knights and bishops: three pieces each, rooks for 5 gold pieces each, queens for 9 gold pieces each; this in-game currency goes to the 'king fund' that will be used to buy kings from the in-game shop, 4 gold pieces for each king. No other pieces can be purchased for gold gained in such a way.


texts:
I've recently attempt for the first time to implement a map generation system and while it does work, it doesn't work exactly the same I want but I'm not really sure on what changes I can make it to make it generate the type of map I want.

This is my map generation code

///<summary>Generates a Room at a Start Position</summary>
    void GenerateMap(Vector2 roomStartPos)
    {
        Vector2 startPos = roomStartPos;

        int roomTileNum = random.Next(minRoomTiles, maxRoomTiles);
        for (int i = 0; i < roomTileNum; i++)
        {
            if (CheckTilePosValid(startPos)) //Checks if a position is taken by a tile already
            {
                Tile newTile = CreateTile(startPos); //Creates a Tile at a passed in Position
                startPos = GetRandomEdgeDirection(newTile.SpritePosition); //Gets a Random position next to the passed in Position

            }
            else
            {
                startPos = GetRandomEdgeDirection(startPos);
                i--;
            }
        }
    }

It's likely a really bad way of generating a map. It basically gets a random number of tiles to generate, it will then place a Tile at the start position and select a new position in a random direction (Up, Down, Left, Right). It'll then place a new tile at that new position specified, it will then simply loop through that till it's placed every tile.
The "CheckTilePosValid()" function is used to determine if the random position that is gathered has already been taken by a tile. If the position isn't taken then it will create the tile and continue through the loop, while if the position is taken then it will get a new position and basically keeping doing that till it gets a position that hasn't been taken already.

This generates maps like this:

The issue is mainly with the first image since as you can see, the map is very stretched out which isn't what I want. I'd more want a map similar to the second image, tiles much closer together and not so stretched out but is still random enough.

I'm just not sure how exactly I can achieve this so I was wondering if anyone would be able to help me? Would I need to completely rework my generation system or can I just make simple changes to fix this?
I'd very much appreciate the help :)


texts: What's wrong my code to create a GL texture from an SDL_Surface?

texts:
I have an issue here with converting an existing SDL_Surface into an OpenGL texture.
The texture gets created, but it's a plain white texture, below is a screenshot of the result:

It seems to me that the SDL_Surface image data is not being properly cast onto the OpenGL texture. But I'm unsure why. Below is another screenshot, showing the image data of the "Loaded_Image", which is the existing SDL_Surface.

I'm just a bit unsure where I'm going wrong. The code seems alright to me:

SDLib::Image SDLib::ConvertImage(SDL_Surface* surface)
{
    SDL_Surface *LoadedImage = NULL;
    GLuint tempTexture;
    Image tempImage;
    LoadedImage = surface;

    //Set Width/Height Of Image
    tempImage.width = LoadedImage->w;
    tempImage.height = LoadedImage->h;

    SDL_Surface *image = SDL_CreateRGBSurface(0, LoadedImage->w, LoadedImage->h, 16, 0xff000000, 0x00ff0000, 0x0000ff00, 0x000000ff);
    SDL_BlitSurface(LoadedImage, NULL, image, NULL);

    glGenTextures(1, &tempTexture);
    glBindTexture(GL_TEXTURE_2D, tempTexture);

    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_BGRA, image->w, image->h, 0, GL_BGRA, GL_UNSIGNED_BYTE, image->pixels);

    //Finally Set The TempTexture data for our OpenGl Texture to the Temporary Image Struct
    tempImage.texData = tempTexture;

    return tempImage;
}

The image itself it supposed to rendering out like this for reference:


texts: Citrus Engine - How do I set-up the camera?

texts:
(Would be great if someone with greater rep created the Citrus Engine tag and add it to this question)

I want to make a game where my inner starling stage dimensions are 320x240. My game will have three parts:

A vertical (left-aligned 32x208) toolbar in Rect(0, 0, 32, 208)
A horizontal (bottom-aligned 320x32) toolbar in Rect(0, 208, 320, 32)
The game content (right-top-aligned 288x208) in the remaining area: Rect(32, 0, 288, 208). It will be handled by the state, view, and camera.

My game would consist of only one playable state (which would render the level content by fetching the data from the server), and would be reset when the player goes to another map (other states are meaningless here since they are just form/UI states).

Please correct me if I'm wrong with these steps, and help me with the further:

I can set cameraLensWidth to 288px and cameraLensHeight to 208.
I can set the inner center to 0.5 and 0.5 with no deadZone (my game will require it), and set the bounds to Rect(0, 0, myMapWidth * tileWidth, myMapHeight * tileHeight) to track player movement only inside the map, and ensuring the camera follows the target by focusing it in its center (as long as it can).
What I don't know is how to ensure the camera top-left corner position be at (0, 32).

What must I do to ensure the last point?


texts:
I'm trying to make a levels map page that shows number-buttons in the page. I want to make this page in a XML layout file and I'm actually trying to make something like this:

I know that I should provide a picture for the background and the background is not a problem, but I'm trying to place those buttons in certain places. I can do that by assigning margins to the buttons but then it won't show up the same way on a bigger or a smaller screen.
Is there any way to do this?


texts: How to achieve this kind of look of a cube in a most efficient way?

texts:
It might be a trivial question, but I couldn't come up with a simple solution.
I need to create a cube like on the image below in Unity.

As always, I target mobile so it would be nice if it was made on a mobile/diffuse shader.

I was playing with lights a little bit, but in order to achieve this kind of look, I'd need to stack multiple lights because one shadow is not enough. Also, I tried adjusting the angles of the lighting - with no luck.

Do you have any tips, how could I make one in a most efficient way?


texts: How do I handle collision sounds with many objects?

texts:
I have a game where I am dropping blocks onto a wooden platform.  The idea of the game is to stack them whilst keeping them balanced.

The blocks fall from a height.  Sometimes they land on the plank, other times on other blocks.  Players will opt to stack them close together.

I want to make a noise when the block hits something, so I have the following code:

void OnCollisionEnter(Collision other)
{
    Debug.Log("Cube collided");
    Debug.Log(other.collider.GetComponent<Collider>().tag);
    GetComponent<AudioSource>().Play();
}

This is attached to my block.

The sound plays, however it feels extremely unrealistic.  The block makes the same noise no matter what the velocity of the impact.  If a block becomes jammed between other blocks then it makes a few sounds, all of the same sound it makes when hitting the plank from a height.

Is there a way of creating more realistic 3D sounds?  I guess I'm after a noise and falloff based off of the velocity, but that might not be the case, I'm a little unsure.  This seems like a very common usecase but I am struggling to find anything online about it.


texts: Unity, WaitUntil in a self-made message box class

texts:
I managed to make a simple message box prefab with a Text and a Button through Canvas, and then instantiate it through the constructor.

public class MessageBox
{
    public MessageBox(string msg)
    {
        GameObject obj = (GameObject)MonoBehaviour.Instantiate(Resources.Load(@"MsgBox"));

        obj.GetComponentInChildren<Text>().text = msg;
    }
}

So when another script needed it, simply do

MessageBox mb = new MessageBox("This is a test message!");

This all worked fine, but then I wish to change it to like normal MessageBox where the code was suspended, but not locked, until the user click the OK or Cancel button.

I managed to do it by calling a coroutine in the calling script.

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

IEnumerator Do()
{
    MessageBox mb = new MessageBox("This is also a test message!");

    yield return new WaitUntil(() => GlobalVariables.MsgBoxClicked == true);
    //GlobalVariables is a separate class containing some static variables.
    Debug.Log("Done!");
}

(You have to set the MsgBoxClicked to false when the prefab is created and set it to true when the button is clicked, of course.)

But that means every time I needed to use the message box, I need to call a coroutine!

And that's super inefficient no matter how you looked at it!

So I tried to move the coroutine into the MessageBox class itself.

But now here comes the problem!

The MessageBox does NOT inherit from MonoBehaviour!

And you can't call a coroutine without it!

I had tried to make the MessageBox inherited from MonoBehaviour, but the Unity warned me This is not allowed every time I tried to new it! Even though the game ran smoothly.

I even tried to new the MonoBehaviour itself and call its StartCouroutine, but of course, the same warning popped up! And this time the game won't even run!

I also tried to use the old AutoResetEvent, but it locked the whole thing and crashed my game!

So, could somebody be so kind and teach me how to get around it!?

Much appreciated!


texts: Attack vs Defence and who is the winner?

texts:
I am in the process of creating a new simple game in mobile and I've spent several days on the following part.
For simplicity, let's say that I have two fighters. The only attribute of them is Attack and Defence. When the first attacks, the only thing that matters is the attack of him and the defence of the opponent. And vice versa.
They don't have equipment, items, stamina or health. Just Attack vs Defence.
Example:

Fighter 1:
Attack:50, Defence: 35

Fighter 2:
Attack 20, Defence: 80

The fighting process will be just a single attack which will determine the winner. So, no multiple attacks or rounds. I don't want to make it deterministic, but add a light version of unexpected. A fighter with lower attack will be able to win another fighter with higher defence (but of course not every time)
My first idea was to make it linear and call a uniform random number generator.
If Random() < att1 / (att1 + def2) {
    winner = fighter1
} else {
    winner = fighter2
}

Example with attack 50 and defence 80, the attacking fighter will have about 38% to win. However, it seems to me that the unexpected is too far and worst fighters will win a lot.
I was wondering how you have worked on similar situations.
P.S. I searched a lot in this QnA and other sources and I found similar questions mentioned as too broad for SE. But those have had many attributes, weapons, items, classes etc that could make it too complicated. I think my version is far simpler to fit it in the QnA style of the SE.


texts: Is Unity3D (free) sufficient to publish to the Mac App Store?

texts: Is Unity3 (free) + dev account sufficient to get an app on the MAC app store? Or, do I require the pro version?


texts: Efficient Collision detection for polygons (fleet) in an RTS

texts:
I'm trying to make an RTS for android using libgdx. I would like to have collision detection to be able to detect ships inside the range of weapons and collision between my bullets and the ships.

So far my strategy has been to use a PM QuadTree that I coded myself to store every segment of every polygons. A polygon being the hitbox of a ship.

Every frame I clear and add all the segments back in the quadtree. Every segment has a reference to the ship it belongs to. When I add a ship, I add it recursively to the nodes of the quadtree based on the intersection with the bounds of a node.

Detection collision is done by polling every polygon inside a rectangle that look into every node that fit entirely or partially inside the rectangle.

My problem is that adding every ship every frame gives bad result on Android. On Desktop it is fast enough but on Android it can takes up to 100 ms just to add around 200 segments.

Is there something wrong with my implementation (it shouldn't be this slow ?) or should I use another strategy for collision detection ? I thought about clearing the quadtree only every 5 frames but it would make the detection unprecise.

I have measured that some simple math operation to calculate intersection takes up to 50 more times on my android and I'm not sure why. Surely my phone cpu is not 50 times slower than my laptop, is it ?

It's a sufficiently fast moving RTS. Often the whole fleet is moving, thus every segment.

I heard about RDC in that article. Would that be a better algorithm ? My issue is that some ships are hard to be bounded by a sphere if they're very long but not wide.


texts: Can you run OpenGL 2.0 on modern machines?

texts:
I'm looking to get into 3d with OpenGL, using SDL to help with other stuff.

I found plenty of good tutorials (lazyfoo is a big one), but "Learning Modern 3d Graphics Programming" uses a newer version of openGL that I'm not able to run!

I opened up OpenGL extensions viewer, and I can only run OpenGL 2.0, whereas most tutorials are in higher versions.

I ask this because I've heard that just about everything in 2.* got depreciated in the newer versions, so I'm worried that my code might not work.

I'm looking at a few other tutorials, but I'm so used to SDL that those just confuse me...

So should I bother trying to do graphics programming now,  or should I just wait until I can upgrade my computer?


texts: Need a little more help with rotating sword around player (Unity 2D)

texts:
this question is somewhat similar to my last question (found here). This time, I have upgraded to the new Input Manager and updated the script that uses the controller, but now I'm having trouble with having the sword rotate around the player and towards the mouse. The image below might help visualize this better.

Here's my current code:
public void Update()
{
    var gamepad = Gamepad.current;
    var mouse = Mouse.current;
    if (controllerControl)
    {
        x = gamepad.rightStick.ReadValue().x;
        y = gamepad.rightStick.ReadValue().y;
    }
    else
    {
        x = mouse.position.ReadValue().x; //Here's where I think the problem is
        y = mouse.position.ReadValue().y;
    }

    //convert the input into an angle in radians, and convert that into degrees
    float rads = Mathf.Atan2(y, x);
    float degrees = rads * Mathf.Rad2Deg;

    //use trig to position sword
    sword.localPosition = new Vector3(Mathf.Cos(rads) * distance, Mathf.Sin(rads) * distance, 0);
    //rotate to face away from center. note that the angle atan gives us is
    //oriented differently than unity's rotation, so we have to reverse it
    //and add 90.
    sword.localEulerAngles = new Vector3(0, 0, degrees - 90);
}

The boolean "controllerControl" will change based on which input device the player chooses. The sword is a child of a box object. If someone could point me in the right direction, that would be much appreciated.


texts: Does Facebook give new games any free promotion?

texts: I would like to understand, if Facebook gives some free out of the box promotion for new games? I see "New Games" section in Facebook App Center, does every new game gets in there?


texts: Why is the player not showing up on UI when connecting to server?

texts:
I want to create a playerList, that whenever a player joins server, his/her name will show up on a list in UI. But currently the names are only showing up on the Client + host side. Below is my NewtworkManager code. lobbyPlayerList is just a UI element with VerticalLayoutGroup. lobbyCharacter is just UI textElement with a networkBehavior script that sets the text field value and also has newtworkIdentity and networkTransformation.
  public struct PlayerInfo: NetworkMessage
{
    public string name;
}

public class LobbyManager : NetworkManager
{
    public GameObject lobbyCharacter;
    public GameObject lobbyPlayerList;
    // Start is called before the first frame update

    public override void OnStartServer()
    {
        base.OnStartServer();

        NetworkServer.RegisterHandler<PlayerInfo>(CreateLobbyCharacter);
    }

    public override void OnClientConnect(NetworkConnection conn)
    {
       // base.OnClientConnect(conn);

        PlayerInfo info = new PlayerInfo
        {
            name = "Test"
        };

        conn.Send(info);
    }

    private void CreateLobbyCharacter(NetworkConnection conn, PlayerInfo info)
    {
        GameObject gameobject = Instantiate(lobbyCharacter, lobbyPlayerList.transform);

        gameobject.GetComponent<LobbyCharacter>().SetText(info.name);

        NetworkServer.AddPlayerForConnection(conn, gameobject);
    }
}


texts:
I am trying to trace the StarWarrior code (the Artemis tutorial). I cannot figure out how these sprites are being drawn.  This is the code where the player's ship is initialized:

/// The initialize player ship.
private void InitializePlayerShip()
{
    Entity entity = this.entityWorld.CreateEntity();
    entity.Group = "SHIPS";

    entity.AddComponentFromPool<TransformComponent>();
    entity.AddComponent(new SpatialFormComponent("PlayerShip"));
    entity.AddComponent(new HealthComponent(30));

    entity.GetComponent<TransformComponent>().X = this.GraphicsDevice.Viewport.Width * 0.5f;
    entity.GetComponent<TransformComponent>().Y = this.GraphicsDevice.Viewport.Height - 50;
    entity.Tag = "PLAYER";
}

Which line of code actually leads to the ship being drawn? The drawing takes place in PlayerShip.cs. Here is a commented version of the code with what I think is happening:

/// The initialize player ship.
private void InitializePlayerShip()
{
    Entity entity = this.entityWorld.CreateEntity(); //declare and initialize entity
    entity.Group = "SHIPS"; //Unused label

    entity.AddComponentFromPool<TransformComponent>(); //Add the component to store X and Y
    entity.AddComponent(new SpatialFormComponent("PlayerShip")); //Add a component which is just a String (perhaps this has something to do with PlayerShip.cs?)
    entity.AddComponent(new HealthComponent(30)); //Add a health component with 30 hp

    entity.GetComponent<TransformComponent>().X = this.GraphicsDevice.Viewport.Width * 0.5f; //Initialize the TransformComponent's X
    entity.GetComponent<TransformComponent>().Y = this.GraphicsDevice.Viewport.Height - 50; //Initialize the TransformComponent's Y
    entity.Tag = "PLAYER"; //Unused label
}

So how is the actual sprite being drawn?  Because, I am not seeing it. :(

If it is being drawn by entityWorld.Draw() in the Draw() method, then which line(s) of code put it in the world to be drawn? Or what is actually happening in entityWorld.Draw()?

I believe the RenderSystem is the one that is doing the drawing, but I don't get how it is being called.

I am sorry for the uninformed question, but I have made no progress after about 12 hours, and I desperately need some guidance!


texts: How do I use Unity's TargetRPC calls? Trying to send data from the server to a client

texts:
I want to send a large amount of data to only one player, as it would be wasteful to do this for every player when only one player needs the data. After a bit of research, it appears that TargetRPC is the thing that I want to use. Unfortunately, TargetRPC was only introduced semi-recently in Unity 5.4, and I have not been able to find a guide on how to use it properly.

Here is a barebones version of my attempt so far:

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

public class TargetRpcTest : NetworkBehaviour {

    private List<NetworkConnection> finishedConnections = new List<NetworkConnection>();

    void Start () {
        // We don't want to send data to ourselves.
        finishedConnections.AddRange(NetworkServer.connections);
    }

    void Update () {

        // If we're not the server, we don't have any business in sending data to players.
        if (!isServer) {
            return;
        }

        // Do the code contained below for everyone we haven't done it for yet.
        foreach (NetworkConnection connection in NetworkServer.connections) {
            if (!finishedConnections.Contains (connection)) {

                TargetSendStuff (connection);
                finishedConnections.Add (connection);
            }
        }
    }

    [TargetRpc]
    public void TargetSendStuff (NetworkConnection connection) {
        print ("I've just received a target RPC call!");
    }

}

This code is all I could come up with, and it does compile properly. No errors are thrown on the server side, either. However, when a client connects to the server, Unity throws this error:

Could not find target object with netId:5 for RPC call ClientRpc:InvokeRpcTargetSendStuff
UnityEngine.Networking.NetworkIdentity:UNetStaticUpdate()

The 5 in netId:5 varies depending on which object I apply this script to. All objects I attach this script to are required to have NetworkIdentity component because of NetworkBehavior. I have tried applying this script to static scene objects as well as the players themselves, but for some reason UNet still can't seem to find the target objects.

Also, I don't really need the TargetRPC call to apply to any particular object. The code within will do only operations to other objects, and even create new ones based on the sent data. All I need is some way that I can send data to specific clients.


texts: How can I make OnDrawGizmos and OnDrawGizmosSelected functions to run the code inside with a button click?

texts:
using UnityEngine;
using System.Collections;

public class CurvedLinePoint : MonoBehaviour
{
    [HideInInspector] public bool showGizmo = true;
    [HideInInspector] public float gizmoSize = 0.1f;
    [HideInInspector] public Color gizmoColor = new Color(1, 0, 0, 0.5f);

    void OnDrawGizmos()
    {
        if (ResetLineRendererPositions.hasReseted == false)
        {
            if (showGizmo == true)
            {
                Gizmos.color = gizmoColor;

                Gizmos.DrawSphere(this.transform.position, gizmoSize);
            }
        }
    }

    //update parent line when this point moved
    void OnDrawGizmosSelected()
    {
        if (ResetLineRendererPositions.hasReseted == false)
        {
            CurvedLineRenderer curvedLine = this.transform.parent.GetComponent<CurvedLineRenderer>();

            if (curvedLine != null)
            {
                curvedLine.Update();
            }
        }
    }
}

Then I created two scripts one is editor type with two buttons. One to reset the linerenderer positions and one to generate the positions :
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ResetLineRendererPositions : MonoBehaviour
{
    public LineRenderer lineRenderer;
    public static bool hasReseted = false;

    public void ResetLinerendererPositions()
    {
        lineRenderer.positionCount = 0;
        hasReseted = true;
    }

    public void GenerateLineRendererPositions()
    {
        hasReseted = false;
    }
}

And
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;

[CustomEditor(typeof(ResetLineRendererPositions))]
public class ResetLineRendererPositionsButton : Editor
{
    public override void OnInspectorGUI()
    {
        ResetLineRendererPositions myScript = (ResetLineRendererPositions)target;
        if (GUILayout.Button("Reset Linerenderer Positions"))
        {
            myScript.ResetLinerendererPositions();
        }

        GUILayout.Space(30);

        if (GUILayout.Button("Generate Linerenderer Positions"))
        {
            myScript.GenerateLineRendererPositions();
        }
    }
}

The buttons are working the problem is when I click on the button "Generate Linerenderer Positions" then I have to select the linerenderer object in the hierarchy to make it take affect and draw the gizmos.
I want that when I click the "Generate Linerenderer Positions" button it will automatic run the code in the OnDrawGizmos and OnDrawGizmosSelected functions.


texts: Best/Efficient way to implement a 3d Collision

texts:
I've already programmed a 2d based collision system for a previous game. It was my first collision system and it was ugly. I was looking for collision between objects by checking all objects with all objects. I've already heard about a grid system with cells where an object will only look the collision with other objects from its current cell(s). Is it really a good way to check collision?

I'd like to have a good technique to loop trough all my items in a 3d world.


texts: 3DS Max exporting too many vertexes for model

texts:
I have a sample model of a cube and a buddha downloaded from internet in 3ds format which I can load correctly into my program and view them without problem, but wanted to try and create my own model.

I created a simple box mesh in 3ds max, and exported it as .3ds (Converted to mesh -> export as .3ds)
When inspecting the .3ds file with a hex viewer, I was expecting to see 8 vertexes and 12 faces declared (as the model I downloaded from internet). But what i found was that it listed 26 vertexes, and 12 faces! And when I try to load that file with my .3ds viewer, my parser isn't detecting the face block (0x4120), which is strange because it worked for other objects downloaded from internet.

Do I have to set any special property in order to export a 3ds file with minimum vertexes and a vertex-index list?


texts: Pixel thin lines appearing between sprites on camera move

texts:
I'm going to apologize in advance for the lack of screenshots, but this was a very hard thing to capture, but very obvious to see.

I'm using LibGDX to create a tile base rogue-like. Everything is going alone smoothly and working well, but there is one graphical glitch that is very bothersome. I have the camera LERPing towards the player, but this smooth movement causes very small gaps to appear for about a frame between the floor tiles that's quite distracting.

The tile rendering code looks something like this:

for(int y = 0, i = 0; y < mHeight; y++) {
    for(int x = 0; x < mWidth; x++, i++) {
        batch.draw(mTiles[i].textureRegion, x * TILE_SIZE, y * TILE_SIZE);
    }
}

Where mTiles is a 1D array representing the 2D dungeon, batch is the main SpriteBatch used for rendering, and textureRegion is the TextureRegion of the tile.

The camera code looks like this:

pos = mEntity.getPosition();
mCam.position.x = MathUtils.lerp(mCam.position.x, pos.x * TILE_SIZE, delta);
mCam.position.y = MathUtils.lerp(mCam.position.y, pos.y * TILE_SIZE, delta);

The problem is solves if I cast the result of the LERP to an int, forcing the camera to line up with the tiles, but it's not ideal. I also tried creating a new texture of the entire dungeon floor from the texture regions that make it up, but there doesn't seem to be any elegant way to do this.

Anyone else face a similar situation? I'll try and capture some screenshots and post them later.