texts:
I am trying to implement the Parallax Refraction effect explained by Jorge Jimenez on this presentation:  http://www.iryoku.com/downloads/Next-Generation-Character-Rendering-v6.pptx and I am facing some difficulties. Here is a screenshot of the interesting part.

But this document lacks a bit of explanations especially the second part with the Physically based Refraction.

Here is what I've achieved for the moment.
This is the simple Parallax Refraction effect and, as you might notice in the screenshot, there is small glitch at grazing angles in the iris when the Parallax Scale value is too high.

This seems to be caused by the parallax calculation but are there some tricks to avoid or minimize such issue ?

I don't want to go deeper with parallax mapping for the moment, so I don't want to use Steep Parallax Mapping or Parallax Occlusion Mapping.

This is the simple Parallax Refraction part.

// height value comes from a texture
float2 offset = height * viewDir;
offset.y = -offset.y;
texcoord -= ParallaxScale * offset;
// Next there is the texture sampling with the texcoord value

Here is the way I calculate the refraction vector according to Snell's law.

float cosine = dot(viewDir, worldNormal);
float sine = sqrt(1 - cosine * cosine);

float sine2 = (_IOR * sine);
float cosine2 = sqrt(1 - sine2 * sine2);

float3 x = -worldNormal;
float3 y = normalize(cross(cross(viewDir, worldNormal), worldNormal));
float3 refractedW = x * cosine2 + y * sine2;

This is integrated with the Physically based Refraction and it gives interesting results but I still don't know how to get rid of the high parallax scale issue which appear at grazing angles...

Any idea how to get rig of that ?
Thanks a lot.


texts: cocos2d: syncing CCAnimation frames with Box2d Shape manipulations

texts:
my cocos2d game currently has a ccsprite attached to a box2d body.
during the game i apply different CCAnimations on my sprite, i would like to perform certain manipulations to the box2d body according to the frame currently displayed by the sprite (change rotation of the body, etc.) my current idea on implementing this is to subclass ccsprite and change the setDisplayFrame implementation but i thought somebody here probably did the same and already has a solution, so any suggestions on how to implement this?

thanks!


texts: Can diffuse and specular component of Phong model shine thru object?

texts:
I have been implementing simple 3D engine in OpenGL, mostly based on tutorials by Tom Dalling. I have implemented the Phong lightening model as described in his tutorial, but I see light artifacts on concave shaped objects (and also when using normal mapping). I came to a point, where i don´t know if my code is broken, or this is actually normal behaviour, and you need special handling for it.

I think that these artifacts could be happening, because the normals of concave object at same points head back into the point light source, not actually considering there is a solid object in between. I tried to do a little scetch of this situation in 2D (for diffuse component):

So I need to know, if this is a common problem of this light model, or my calculations are wrong.


texts:
In my project, certain data is stored in floating point datatypes (C's native float, double). Before sending the data in a VBO to OpenGL I have to convert this data to GLfloat with some pretty silly code.

float data[DATA_SIZE];
GLfloat *new_data;

new_data = malloc(sizeof(data));
for (i = 0; i < DATA_SIZE; i++)
    new_data[i] = (GLfloat) data[i];

upload_to_gpu(new_data);

free(new_data);

Of course, since I know float is equal to GLfloat on my platform, I can just ignore this but then my code won't be properly platform-independent. I could also store the data in my program in OpenGL native datatypes but this is unacceptable as I don't want to fixate my code only on OpenGL (DirectX or a software renderer are possibilities I don't want to exclude).

How can I solve this? Is the conversion step unavoidable? Or am I obligated to store my geometry in GLfloat's?


texts: How do I place a progress bar in AndEngine?

texts: I am developing game using AndEngine. I need to place a progress bar in my game to denote time remaining in the game. Is there a built-in method for doing this in AndEngine? My searches only turned up results for Android, not for AndEngine.


texts: Tools for non-programmers to add new tasks to games

texts: Since graphic designers/end users are not programmers, what are the technique to allow them to add new tasks or change application logic in a game? what are the end user tools? I want some popular examples.


texts: Global fog does not work with deferred rendering in Unity

texts: When I set deferred rendering the global fog from the Unity Standard Assets does not work, there is no fog at all. With forward rendering the global fog works. How do I add fog with deferred rendering?


texts: Is there an SDK to write console apps to simulate an Xbox 360 controller?

texts: Is there any SDK I can use to write a console app that can connect to an Xbox 360 as a controller and simulate controller interaction?


texts:
I am successfully drawing all of my geometry with an AlphaTestEffect and would like to apply shaders. I've built a shader Effect from a tutorial and can't seem to find anything on the web that answers my question:

Does monogame support passing separate effects with the same geometry to the Graphics Device, or do you have to perform all Techniques you intend to apply to a model in the same effect?


texts:
I'm  trying to build card game using the Quintus game engine. I have objects called Card. I can touch and drag it in the screen but I want just to touch and drag it one time but I can't figure out how to disable the touch after I dragged the card and I try to Google it but no luck.

My code:

Q.Sprite.extend("Card", {

init: function(p){

    this._super(p,{
        asset: "Queen_OF_Hearts.png",
        x: Q.el.width / 2,
        y: Q.el.height - 120
    });

   this.on("drag");
   this.on("touchEnd");
},

drag: function(touch) {
   this.p.dragging = true;
   this.p.x = touch.origX + touch.dx;
   this.p.y = touch.origY + touch.dy;
 },

touchEnd: function(touch) {
   this.p.dragging = false;
   // put a line on the screen if the card pass it put the card in the new position if not put the card in the orginal(old) postion
   if(touch.origY + touch.dy > Q.el.height - 200) { //define the line that the card should pass if the amount of draged > the screen line in Q.el.height - 200
       // put the card in the same old postion if is not pass the line
       this.p.x = touch.origX;
       this.p.y = touch.origY;

    } else {
        // put the card if it pass the line in the new postion
        this.p.x = Q.el.width / 2;
        this.p.y = Q.el.height - 280;

    }
}
});

so in the else statement in the touchEnd I'm trying to do some thing like that

this.p.touch = false;

but is not working.


texts: How do I separate physics from framerate?

texts:
Skyrim (Creation Engine / Gamebryo) is a prime example of a game that has its physics tied to the framerate for which it has been heavily criticized, because if you disable vsync / have a > 60 HZ monitor the physics will glitch, characters will fly into the air, and the screen will flicker while you are put into a swimming position. This problem can be solved by using a framerate limiting mod. But I want my game to run at any framerate, any refresh rate, just fine. How can I do that? Sorry if this isn't a game development question necessarily, it's more of a game engine question.

I looked and saw similar questions asked but they were very old and new tech / new programming techniques might have allowed better ways to do it since 2008.


texts: How to modify A* so that it takes into account the number of movement point left?

texts:
Context : turn based game, grid system

Let this graph here :

(A)-2-(B)-1-(C)
 |    /|   /
 1  2  2  1
 | /   |/
(D)-1-(E)

My unit is at A and wants to go at C. He currently has 1 point left, therefore he cannot go onto tile B until next turn.

A*star could say that the best path is A-B-C and say that the next move is go to B. But my unit cannot. It should've gone to D, as it would move closer to C and use all of its remaining movement point.

Right now, I have done a workaround in which I give a set of tiles to ignore, these tiles are neighbouring tiles that cannot be access given a number of movement point left. This works OK because my tiles either cost 1 or 2 MP, and my units have a maximum of 2 MP.

I would like something that is more general.

I have currently thought of something. I will now stop adding tiles to the frontier for which the cost so far is superior to my current movement point left. Once the frontier is empty, I iterate over all the already seen tiles and select the one with the best heuristic and get the path from there. Would that work?


texts:
I'm trying to achieve grid/tile based collisions like "a link to the past"; here is an article showing it off (sliding off the corners and such). I'm currently using this type of collision test. It's based on deepnight's implementation of tile collisions but modified a bit, you have your positionX/Y in the world, TileX/Y is the tile equivalent (my tiles are 16/16), and XRatio/YRatio which is how much into a tile are you so whenever you're moving into a tile you can clip into it for a certain amount which is nice for making it seem like the player is above stuff and to have more control over it but I'm really looking for someone to show me how I'd go about implementing this kind of collision testing properly I've been having so many problems (Getting stuck in 1 pixel in the corners, Snapping on one side while the other u don't, getting stuck in general/not being able to move when holding diagonals etc) If you could "Explain Like I'm 5" that'd be awesome I'd really like to learn this stuff properly.
TL:DR - Trying to achieve Topdown collision detection like a link to the past/stardew (Slide off corners of tiles) and being bug free (Not getting stuck / snapping)


texts:
How can I simulate the vegetation (of a human being)?

To simulate Hunger for example, I use some kind of saturation based system now. Means that every food-object saturates differently and the saturation influences how much gets substracted from the current hunger level.

But I'm not very satisfied with the result and I don't really have an idea how to realize the same with the needs Fun and Energy.

So, is there a special way to do this? Or is there an algorithm that is used in stuff like The Sims or even Minecraft (which has hunger only, but it has.)?


texts: How to check if a line casted from one point to another point passes through a mesh?

texts:
Let's say we have two vectors A and B. Is there a way to use Three.js' Ray or Raycaster classes to cast a line between vector A and vector B and check is it passes through a mesh in the scene? I know from the documentation that both the Ray and Raycaster classes accept origin and direction vectors but I specifically need two points.
Thanks in advance.


texts:
I am trying to handle the touch of one of the Actors in the stage. The following is the code I have written:

public class MyGame extends ApplicationAdapter
{
    private GameStage gameStage; //Game stage is custom stage class.
    @Override
    public void create ()
    {
        gameStage = new GameStage();
        Gdx.input.setInputProcessor(gameStage); //Set the input processor
    }

    @Override
    public void dispose()
    {
        super.dispose();
        gameStage.dispose();
    }

    @Override
    public void render ()
    {
        Gdx.gl.glClearColor(0, 0, 0, 1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

        gameStage.act(Gdx.graphics.getDeltaTime());
        gameStage.draw();
    }
}

Now in the GameStage class:

public class GameStage extends Stage implements ContactListener
{
    MyActor myActor; //Custom actor object.
    public GameStage()
    {
        super(new ScalingViewport(Scaling.fill, Constants.APP_WIDTH, Constants.APP_HEIGHT, new OrthographicCamera(Constants.APP_WIDTH, Constants.APP_HEIGHT)));
        setUpWorld(); //Code to setup the world. added background and other actors. none of them are touchable.
        addActor();
    }

    private void addActor()
    {
        myActor = new MyActor(100, 100, 100, 100, 1000, 0);
        myActor.setTouchable(Touchable.enabled);
        myActor.addListener(new InputListener()
        {
            @Override
            public boolean touchDown(InputEvent event, float x, float y,
                                     int pointer, int button)
            {
                actorTouched(); //This method is not getting triggered becaused the call never comes in this function.
                return true;
            }
        });
        addActor(myActor);
    }
}

The custom actor class initializes the actor with a sprite image.

public class MyActor extends Actor
{
    public MyActor(int startX, int startY, int startWidth, int startHeight, int endX, int speed)
    {
        TextureAtlas textureAtlas = new TextureAtlas(Gdx.files.internal(Constants.ATLAS_PATH));
        TextureRegion[] runningFrames = new TextureRegion[Constants.MOVING_REGION_NAMES.length];

        for (int i = 0; i < Constants.MOVING_REGION_NAMES.length; i++)
        {

            String path = Constants.MOVING_REGION_NAMES[i];
            runningFrames[i] = textureAtlas.findRegion(path);
            if (horizontalMovingDirection == MovementDirection.Right)
            {
                runningFrames[i].flip(true, false);
            }
        }
    }
//code to draw and animate in a straight line by overriding the draw and act methods.
}

Am I doing something wrong here? Why am I not getting the touch in the actor?


texts: How to handle wearable items on character

texts:
I am developing a text/image based rpg game with javascript.I have questions about how to handle wearable items on character.

Lets say that there are many(naked no item) character types(images)and there are many items.When a player equips a sword and a helmet,do i have to make images of all item combinations with all base character types import them into the game then check all of them with if elses then display correct picture on screen  ?  or is there any other way


texts: Why is it that there are invalid "dt" values in physics simulations?

texts:
I'm utilising some of NeHe's spring code, and after getting some pretty weird results I eventually realised the source of my error - my "dt" value in my Update function; the value that everything is multiplied against to speed up/slow down the calculations, hopefully based on frame rate. For example:

public void Update(GameTime gt) {
   float dt = gt.ElapsedGameTime.Milliseconds / 160.0f;
   velocity += (force / mass) * dt;
   position += velocity * dt;
}

160.0f seems to work pretty well for the player's update function, but for my spring simulation I need a value of about 3000, or I end up with my springs located at (NaN,NaN) pretty much instantly.

Why do bad values for this cause everything to go so crazy? I thought it would just slow down or speed up my simulation but it seems to cause some weird cascading failure.

Edit: Sorry, forgot to link to NeHe's post on this: http://nehe.gamedev.net/tutorial/introduction_to_physical_simulations/18005/


texts:
I'm looking for some math to "degrade" stats over level. The idea is that if you have x value for a stat that it's affect will be less when you increase your level, making you have to put more points into that stat to maintain.

For my specific example I have a stat I call Focus. I want the Focus stat combined with the level to create a percentage. I will use this percentage against each abilities damage/heal value to get a value. This value will act as the low end and the abilities value will act as the high end for finding a random number between. So if "Strike" has a value of 10 and my focus % is 50% then then I find a random number between 5 and 10 to get the actual damage to apply.

So at level 1 ideally this % is 100% (so "Strike" will do 10 damage always). At level 2 with no more points in the Focus stat, I want this final % to go down but putting points into the Focus stat could keep it up.

This seems like the kind of thing every RPG game has, but I'm not sure how it's done. I'm picturing all stats being like this. Each level I would increase base damage/heal values for abilities by x% and then degrade other stats. Like strength for example. The idea would be to try and keep the strength state so it results in 100% of the ability damage by putting points into it each level.

Does this make sense or am I way off base in my thinking on how this kind of stuff is done or can be done?


texts:
I've bought a 3d model from a 3d marketplace.

It is a big interior scene.

I've imported the single FBX into Unity, added some collider, changed materials (6-7 materials) etc. There are hundreds of child object/mesh:

Despite what my camera is looking, i noticed Unity is rendering 3-400K tris.

Why Occlusion Culling isn't working ? Maybe importing a single huge Fbx isn't the right practice ?

Thanks

This image is my player looking at a black wall... 360K tris rendered !!!!


texts: Orbiting a specific point - Orbiting Camera

texts:
How would I create a camera that with the mouse, it allows you to orbit around a specifc position, with the camera always facing that point? I would also like it to be able to always be at a constant distance from the point, and be able to orbit around it in every direction.

Any ideas?


texts: Windows Phone XAML and XNA Apps with Game Components

texts:
I am using the Windows Phone Template "Windows Phone XAML and XNA Apps" and targeting Windows Phone 7/8. Most examples show your game inheriting from Microsoft.Xna.Framework.Game and then adding Microsoft.Xna.Framework.GameComponent items to the Components collection. But as my game page inherits from PhoneApplicationPage there isn't a Components collection  or a Game property.

How can I use GameComponent from within PhoneApplicationPage?


texts: Handling bad network clients using socket.io

texts: Currently I'm working on a MMO game which players can join and exit game whenever they want. I have a connection manager server (CMS) written in golang using socket io library. World connects to CMS and clients connect to CMS and talk to world and world update clients with snapshots of game state. For testing I wrote a client that connects to CMS and act as a player for testing how many clients can my CMS handle. I reach around 80 clients per one core vcpu and 1 gig ram and that's acceptable for my game and resources. I released the game but in real life when there is around 5 or 6 real players and one player with bad network connection joins game it massively take effect the another players game experience. Packets don't receive to another clients or delayed heavily! I believe it's because socket io uses tcp and when a bad network client joins it should send messages many times for client received it completely. How should I overcome this? I know I should used udp for my game but it's too late and I released my game in play store and it got around 700 installs. Is there anyway I can put a time to live like attribute to messages that if client don't received them at a certain time dropped them? Any idea whould be helpful.


texts: Custom Editor for Map/Dictionary in Unity

texts:
I'm trying to build my own little ResourceManager in Unity that will allow me to tag resources (ranging from materials to prefabs) to a label in the editor, and then access them in game.

The ResourceManager itself is really easy to write- it's just a Dictionary. However the Unity Editor doesn't seem to be able to serialize (and thus render) Dictionaries.

To get around this, I created a list of key-value pairs which gets loaded into the dictionary by unity. That way Unity gets its list and I get my Dictionary. However, when I try and run the code shown below, I can only add a single entry to the list. Any idea what I'm doing wrong?

ResourceManager.cs

using UnityEngine;
using System.Collections.Generic;

public class ResourceManager : MonoBehaviour, ISerializationCallbackReceiver {
    private Dictionary<string, Object> resources = new Dictionary<string, Object>();

    #region Unity
    // Unity doesn't know how to deal with maps, so we give it a list to work with
    public List<ResourceEntry> entries;

    // Dictionary -> List
    public void OnBeforeSerialize() {
        entries.Clear();
        foreach(string key in resources.Keys) {
            entries.Add(new ResourceEntry(key, resources[key]));
        }
    }

    // List -> Dictionary
    public void OnAfterDeserialize() {
        resources = new Dictionary<string, Object>();
        foreach(ResourceEntry entry in entries) {
            resources[entry.key] = entry.value;
        }
    }

    [System.Serializable]
    public class ResourceEntry {
        public string key;
        public Object value;

        public ResourceEntry() {}

        public ResourceEntry(string key, Object value) {
            this.key = key;
            this.value = value;
        }
    }
    #endregion

    private static ResourceManager instance;
    public static Object Get(string category, string key) {
        instance = instance ?? GameObject.FindObjectOfType<ResourceManager>();
        if( instance.resources.ContainsKey(key)) {
            return instance.resources[key];
        } else {
            return null;
        }
    }
}

ResourceManagerEditor.cs

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

[CustomEditor(typeof(ResourceManager))]
public class ResourceManagerEditor : Editor {
    private ReorderableList list;

    public void OnEnable() {
        list = new ReorderableList(serializedObject, serializedObject.FindProperty("entries"), true, true, true, true);
        list.drawElementCallback = (Rect rect, int index, bool isActive, bool isFocused) => {
            SerializedProperty element = list.serializedProperty.GetArrayElementAtIndex(index);
            rect.y += 2;
            EditorGUI.PropertyField(new Rect(rect.x, rect.y, 60, EditorGUIUtility.singleLineHeight), element.FindPropertyRelative("key"), GUIContent.none);
            EditorGUI.PropertyField(new Rect(rect.x + 70, rect.y, 160, EditorGUIUtility.singleLineHeight), element.FindPropertyRelative("value"), GUIContent.none);
        };
        list.drawHeaderCallback = (Rect rect) => {
            EditorGUI.LabelField(rect, "Resources");
        };
    }

    public override void OnInspectorGUI() {
        serializedObject.Update();
        list.DoLayoutList();
        serializedObject.ApplyModifiedProperties();
    }
}


texts: graphics.GraphicsDevice.Clear strange result (XNA)

texts:
I have such Execution:

graphics.GraphicsDevice.Clear(new Color(255, 0, 0, 0));

Alpha is 0. So why it draws me Red color?

graphics.GraphicsDevice.Clear(new Color(255, 0, 0, 255));

Also draws the same red color. Changing alpha value doesn't affects the color on the screen. Why?


texts:
I am working on a bukkit plugin.  One thing I want this plugin to do is teleport you to other worlds on the server.  However, I don't want the player's inventory to be saved.

Right now, I have this code:

File playerInvConfigFile = new File(plugin.getDataFolder() + File.separator + "players" + File.separator + sender.getName(), "inventory.yml");
FileConfiguration pInv = YamlConfiguration.loadConfiguration(playerInvConfigFile);

        Player user = (Player)sender;
        PlayerInventory inv = user.getInventory();

        String worldName = user.getWorld().getName();
        int i = 0;
        for (ItemStack stack : inv.getContents()){
            i++;
            String start = worldName + "." + Integer.toString(i);

            pInv.set(start + ".amount", stack.getAmount());
            pInv.set(start + ".durability", stack.getDurability());
            pInv.set(start + ".type", stack.getTypeId());
        }
        inv.clear();

This works great, but there is a big problem: enchantments are now saved!  This is a big problem.  I want to know how to both save enchantments to a file, and then read them back in and set them!

Thank you all!


texts:
I work with a small team of three people, and we use the collaborate service within Unity to share our progress. One of the folders we have inside our Unity project is an "OffGame" folder, which includes a tool I created specifically to help with the creation of certain assets. It's not actually supposed to be part of the game, but since I'm often making changes to it, I figured I'd include it in the Unity project. The Unity project temporarily makes use of certain files inside said OffGame folder, however, once the game is done, those files will be moved outside of that folder and integrated into the game proper.

Since that OffGame folder is not supposed to be part of the game and I only included it there to share it to my teammates over the collaborate service, I don't want it to be treated like a normal folder for the game. Specifically, I don't want Unity to create a bunch of useless meta files for each file in that folder, or to act like a stray .js file in there is part of the project. I actually got compile errors because Unity kept thinking it had to include all the .js files in that folder.

How can I make Unity ignore that folder?


texts: My GameObject keeps spawning when it shouldn't

texts:
I'm trying to instantiate a new gameObject when the current gameObject gets to a select point. The problem comes when the program gets to the second if() statement. It sets the floorsSpawned to 1 and when it does, the game object instantiates a bunch of times. Shouldn't the floorSpawned be set to 2 in the first if() statement and only instantiated once?

public class FloorMovement : MonoBehaviour
{

    public GameObject floor;
    [SerializeField] int speed = 10;
    public int floorsSpawned = 1;
    // Start is called before the first frame update
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {
        transform.Translate(Vector2.left * Time.deltaTime * speed);

        if (transform.position.x <= -18.0 && floorsSpawned == 1)
        {
            floorsSpawned = 2;
            Instantiate(floor, new Vector2(11.5f, -2.0f), Quaternion.identity);
        }

        if (transform.position.x <= -40.25 && floorsSpawned == 2)
        {
            floorsSpawned = 1;
            Destroy(floor, 3);
        }
    }
}


texts: My lighting stays the same when I go indoors?

texts: My problem can be seen here notice how the shadows don't change intensity or color when moving indoors to the cave. The only thing that changes is the highlights when I move under the directional light. I was thinking about adding global illumination but I don't think that would work with a toon shader. How can I get my lighting to become darker once I enter indoors e.g a cave. Thanks!


texts:
I need to read depth buffer from GPU and write it to texture. How this can be done?
Here is how texture for depth buffer is created:

depthBufferDesc.Width = screenWidth;
depthBufferDesc.Height = screenHeight;
depthBufferDesc.MipLevels = 1;
depthBufferDesc.ArraySize = 1;
depthBufferDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
depthBufferDesc.SampleDesc.Count = 1;
depthBufferDesc.SampleDesc.Quality = 0;
depthBufferDesc.Usage = D3D10_USAGE_DEFAULT;
depthBufferDesc.BindFlags = D3D10_BIND_DEPTH_STENCIL;
depthBufferDesc.CPUAccessFlags = 0;
depthBufferDesc.MiscFlags = 0;

m_device->CreateTexture2D(&depthBufferDesc, NULL, m_depthStencilBuffer);

Also, I've got another question: is it possible to bind depth buffer texture as sampler to the pixel shader?


texts: Increase maximum tracking distance of Kinect

texts:
So according to the Kinect v2 SDK specs, the maximum skeletal tracking distance is only 4.5M.

Is there any way to increase this distance, perhaps with reduced skeletal tracking accuracy since I only need to track the head?


texts:
Version: Unity3D 4.6.2f1

I have a grid of tiles (Cube GameObjects with a Tile script attached). They are positioned at their index location [x][y] = (x, y, z=0) World Coordinates.

Below, I try to get the coordinates of the tile upon which the mouse left click is released.

Before into code:

  OnMouseDown() -  OnMouseDown is called when the user has pressed the mouse button while over the GUIElement or Collider.
  OnMouseUp() - OnMouseUp is called when the user has released the mouse button.

Based on these definitions, I assumed (mistake?) OnMouseUp() would be called by the object that above it, the mouse left click was released.

On the Tile script, I have the following :

public class Tile : MonoBehaviour
{
    // variables
    private Vector2 _gridPosition = Vector2.zero;

    public Vector2 GridPosition
    {
        get { return _gridPosition; }
        set { _gridPosition = value; }
    }

    // functions
    string Vec2toText(Vector2 v)
    {
        return String.Format("(" + v.x + ", " + v.y + ")");
    }

    void OnMouseDown()
    {
        Debug.Log("TILE:: ON_MOUSE_DOWN:: " + Vec2toText(_gridPosition));
    }

    void OnMouseUp()
    {
        Debug.Log("TILE:: ON_MOUSE_UP:: " + Vec2toText(_gridPosition));
    }

    void OnMouseEnter()
    {
        Debug.Log("TILE:: MOUSE_ENTER: " + Vec2toText(_gridPosition));
    }

    void OnMouseExit()
    {
        Debug.Log("TILE:: MOUSE_EXIT: " + Vec2toText(_gridPosition));
    }
}

And here is the output:

TILE:: MOUSE_ENTER: (15, 15)
TILE:: MOUSE_DOWN: (15, 15)
TILE:: MOUSE_EXIT: (15, 15)
TILE:: MOUSE_ENTER: (14, 15)
TILE:: MOUSE_UP: (15, 15)    %% This line
TILE:: MOUSE_EXIT: (14, 15)

I would expect OnMouseDown() to be called by the object on which the mouse button was pressed (no problem here) and OnMouseUp() to be called by the object on which the mouse button was released (instead, it is called by the same object as OnMouseDown()).

Is this -- calling two functions by the same object even though I pressed left click some object and released it on some other object -- intended?


texts:
Unity UGUI Outline it create fourfold vertexs, So I wirte shader to optimization ( vertex only create once ),
And I want to Keep one pass . (one drawcall)

There are four character , all character font size are same.
but this character edge look a little small.

I write shader like this

 fixed4 frag(v2f IN) : SV_Target
        {
            fixed4 color = (tex2D(_MainTex, IN.texcoord) + _TextureSampleAdd) * IN.color;

            float4 pClipRect = float4 (IN.uvOriginXY, IN.uvOriginZW);
            color.a *= IsInRect(IN.texcoord, pClipRect);
            half4 val = half4(_OutlineColor.r, _OutlineColor.g, _OutlineColor.b, 0);//(r,g,b,0)

            //black characters
            val.a += SampleAlpha(2, IN);
            val.a += SampleAlpha(5, IN);
            val.a += SampleAlpha(8, IN);
            val.a += SampleAlpha(11, IN);

            val.a = clamp(val.a, 0, 1);

            //blend
            color = (val * (1.0 - color.a)) + (color * color.a);

            return color;
        }

And the lower right picture is create by UGUI Outline it look like white color overlap black color , How can I do like this ?

The problem probably from here : color = (val * (1.0 - color.a)) + (color * color.a);

What should I do to make it look like UGUIOutline? thanks.


texts: When to Use Spatial Hashing vs Bounding Volume Hierarchy?

texts:
I've been slowly working on implementing a spatial hashing function into Bullet Physics to see how well it will work in my game engine as a general use. Though as I'm starting to design it, I do notice a few select problems about it's design.

So in the middle of research, I see that Spatial Hash functions start to suffer when objects take up too many cells.

Example: 1D's optimal case is at max 2. 2D's optimal case is 4. And 3D's optimal case is at most 8.

I can use a hierarchal method and hash larger objects to other tables to solve this.

But my biggest concern is exactly what are the best use cases for each of them?

BVH seems like it can generate a larger number of checks, and needs to bounce around on pointers

And Spatial hashing seems like it chews through memory, but is pretty good at what it does.


texts: How do you simulate frictionless movement?

texts: I am building a game in which I want to simulate smooth movement of an object upon pressing a key or any other event. Could someone advice me to get that feel of gliding of an object, sliding on a frictionless surface. How could I have that?


texts: Registering a C++ callback with Lua API without additional libraries

texts:
Basically, I'm trying to register a callback into a Lua state like this:

class MyClass
{
    public:
        int myLuaFunction(lua_State* L)
        {
            //do something
        }

};

I want to be able to call MyClass::myLuaFunction of a given instance (which could register itself).

I've spent a couple hours trying to do tricks with templates and lambdas in an attempt to get it to work, but I haven't got anything successful (mainly the fact that I couldn't pass a lamba function that uses parent scope variables to Lua's API).

Without having to download any other libraries (just Lua's standard interpreter implementation), how could I do this?


texts: How to fetch only the sprites in the player's range of motion for collision testing? (2D, axis aligned sprites)

texts:
I am working on a 2D sprite game for educational purposes. (In case you want to know, it uses WebGl and Javascript) I've implemented movement using the Euler method (and delta time) to keep things simple. Now I'm trying to tackle collisions.

The way I wrote things, my game only has rectangular sprites (axis aligned, never rotated) of various/variable sizes.

So I need to figure out what I hit and which side of the target sprite I hit (and I'm probably going to use these intersection tests). The old fashioned method seems to be to use tile based grids, to target only a few tiles at a time, but that sounds silly and impractical for my game. (Splitting the whole level into blocks, having each sprite's bounding box fit multiple blocks I might abide. But if the sprites change size and move around, you have to keep changing which tiles they belong to, every frame, it doesn't sound right.) In Flash you can test collision under one point, but it's not efficient to iterate through all the elements on stage each frame. (hence why people use the tile method).

Bottom line is, I'm trying to figure out how to test only the elements within the player's range of motion. (I know how to get the range of motion, I have a good idea of how to write a collisionCheck(playerSprite, targetSprite) function. But how do I know which sprites are currently in the player's vicinity to fetch only them?)

Please discuss. Cheers!


texts: Opengl create tunnel TRIANGLES and texture coords on a 3d path

texts:
I have a path, lets say a bezier, or a circle.

I d like to make a continously 3d cylinder (tunnel) on it (R=0.5f)

How can I calculate tha TRIangles (TRIANGLE_STRIP) coordinate, and the texture coords right?


texts: What are the correct steps to add Admob to Unity?

texts:
The official documentation leaves out really important steps.
Adding 'cocaopods' and 'Google Play Services'
They are just listed as prerequisites without even any links.
Another confusing thing is that, elsewhere I have seen that apparently I don't also need the Unity Google Play Games Services SDK for Admob to work. But in that case then why is 'Google Play Services' listed as a prerequisite on the official docs?


texts:
So i was wondering how games handle input so that the input is still handled even in cases of the frame rate being really low. Assuming the input logic is in the same thread as the rendering in the main thread. If the input is handled by some popular API (SDL/SFML/etc) the code will look something like this as a simple example:

if(KeyIsDown(keyCode))
{
    // do stuff
}

If the game is lagging then the above solution won't be able to catch the input cause the code won't be reached cause it is running behind. I notice in some games though when the framerate is low some games are still able to capture input. So if pressing Esc while the game is lagging eventually the key press will be registered. Is there any implementation of how this might work?


texts: Management of objects as targets of other objects

texts:
I have started my first game three years ago and learned a lot during that process. Now I would like to rewrite it to incorporate my "lessons learned" or try out new ideas.

My game consists of space ships that can target other space ships either for combating, trading or communicating. When they have no current target, they look for other ships in their area, lock them as target (by keeping a pointer to them as member variable) and do some stuff. After a ship is destroyed, its pointer used by other ships as a target becomes invalid. To avoid any dangling pointers and crashes, I add the to be destroyed Ship's id to a cleaning list. During the next World's update, I go through all of these to be destroyed ids and remove them as potential targets. See this pseudo code to demonstrate this:

class Ship
{
public:
    Ship();
    Ship::destroy(){
        // set to be destroyed flag
        _world.pointersToDelete(_id);
    }

private:
    void        destroy();

    int         _id;
    Ship*       _target;
    World*      _world;
    bool        _to_be_destroyed;

};

// in World::update
World::update()
{
    for (auto ship: all_ships)
    {
        for (auto id_to_delete: ids_to_delete)
        {
            if(ship._target != nullptr && ship._target->_id == id_to_delete)
            {
                ship._target = nullptr;
            }
        }
    }

    // now trigger the actual final destruction of the ships
    // ...
}

Question: Is this a good design in general?
I ran into some problems when I used it in practice:

There are more objects that communicate, combat and trade with ships like Space Stations, Planets, etc.. I would need to go through all of them every update loop to check whether they have no dangling pointers. I am concerned about the performance since my game allows space battles of thousands of ships at the same time.

I thought about using an id approach instead: the _target variable is not a pointer but an id that I can look up in an unordered_map of Ship objects. If the id is not found anymore, the target is not valid any longer. But this could lead to performance issues as well if every object has to check this during every update multiple times.


texts: When to use an Array vs When to use a Vector, when dealing with GameObjects?

texts:
I understand that from other answers, Arrays and Vectors are the best choices. Many on SE claim that Linked Lists and Maps are bad for video game programming.

I understand that for the most part, I can use Arrays. However, I don't really understand exactly when to use Vectors over Arrays.

Why even use Vectors? Wouldn't it be best if I simply always used an Array, that way I know how much memory my game needs?

Specifically my game would only ever load a single "Map" area of tiles, such as Map[100][100], so I could very easily have an array of GameObjectContainer GameObjects[100][100], which would reserve an entire map's worth of possible gameobjects, correct?

So why use a Vector instead? Memory is quite large on modern hardware.


texts: Why is Unreal Engine Blueprint Editor so slow?

texts: Blueprint Editor is extremely slow on my Ubuntu 16.04. Can I improve performance without upgrading?


texts: libgdx - Should I use OOP in ECS framework?

texts: For example I have OOP class of Bullet and I have created the pool and factory. Should I convert it to componet based? Like BulletComponent, then handle by BulletSystem? by the way I'm using Ashley ECS framework.


texts: Issue With setting Mesh.triangles in Unity Script

texts:
I have been having an issue in making floating islands. For this i have created an array filled with the position data for both the top and bottom half of the island. Everything works fine when i only have the top half of the triangles implimented, but when i add the bottom half of the triangles become triangles that are shifted to the top half of the island.

To be more precise, the traingle index data seems to change while writing it to mesh.triangles.

This happens after mesh.triangles = triangles in the following code

    mesh.Clear();

    transform.position = new Vector3(-width/2,0 * scale,-height/2 * scale);

    positionsAll = new Vector3[2 * width * height];

    setupHeightMap();
    int[] triangles = getTriangles();

    mesh.vertices = positionsAll;
    mesh.triangles = triangles;
    mesh.RecalculateNormals();

An example watch can be seen here, witth the first four showing the change in index, and the final four showing how the point is the same point but on the above surface.

    triangles[0]    30785   System.Int32
    triangles[4]    96322   System.Int32
    mesh.triangles[0]   30785   System.Int32
    mesh.triangles[4]   30786   System.Int32
    mesh.vertices[triangles[0]] "(65.0, 0.0, 120.0)"    UnityEngine.Vector3
    mesh.vertices[triangles[4]] "(66.0, -0.2, 120.0)"   UnityEngine.Vector3
    mesh.vertices[mesh.triangles[0]]    "(65.0, 0.0, 120.0)"    UnityEngine.Vector3
    mesh.vertices[mesh.triangles[4]]    "(66.0, 0.2, 120.0)"    UnityEngine.Vector3

This watch data was generated in an instance where all triangles that had positive values were not instanciated, but the same problem hapens if all Triangles are instanciated.

If anyone can tell me why this happens and/or how i can fix this problem that would be extremly helpful. thank you!


texts: Real-time movement client to server to client(s)

texts:
So the way that I tried to create a MMO like server communication was by sending strings to every-player containing information and making the client split the string.

Example

"John" , 42, 64 : "Bob", 0, 0 : "Lilly", 1943, 120

This worked make it so for every ':' it would create a new character with the following information. And just send it to every-player connected. But once I added bullets and the game world, this started getting long and hard to manage.

Example

"John", 42, 64 (42,43 / 45,12 / 45,12, / 46,5 / 12,5), "Help Me", "Running", "Red", "Red", "Blue", 12

I have made a Async multi-client fast server, which works very well, but how can I send information through the server so every client can respond to it correctly.

So for example:

You start the game it connects to master server (Done)
You get added the servers player list (Done)
Make so you spawn as a character on everyone's else's screen and move in real-time every update. (Problem)

Is there any way to get this working with-out using this really long string?
I hope I explained this question clearly.


texts:
So I am currently working on a simple game project that most people start of with: "breakout". part of my goal is to make a gamesave of the current gamestate the simplest way possible.

For example, lets say I lose the game or I want to exit the game. Then later, I want to reload the gamestate to the same position of the paddle, ball and bricks. The only problem is I have multiple forms and I just want to save this specific form in its specific state.

I have an idea on how to approach (I would find a way to save the position of the paddle, ball and the bricks and that exact time) just I have no clue how I would execute it.
How can I achieve this?


texts: Was my horizontal drag performed from left to right or from right to left?

texts:
I want to determine if a horizontal drag was performed from left to right or from right to left.
In addition, I want to do the same with the vertical drag.

How can I do that?

How can I check if the horizontal drag was performed from left to right or from right to left?

protected override void Update(GameTime gameTime)
    {
        while (TouchPanel.IsGestureAvailable)
        {
            GestureSample gs = TouchPanel.ReadGesture();
            switch (gs.GestureType)
            {
                case GestureType.HorizontalDrag:
                //from left to right
                Count += 1;
                //from right to left
                Count -= 1;
                break;
                case GestureType.VerticalDrag:
                //downwards
                Count += 1;
                //upwards
                Count -= 1;
                break;
            }
        }
        base.Update(gameTime);
    }


texts: How did Blizzard implement replay like in Warcraft 3 with not consistent data(attack damage)?

texts: Units in wc3 has range of attack damage and it isn't consistent most of the time e.g critical hit and so on. Yet, they managed to make a replay that could even reconstruct bugs scene. I am just curious how they do it. It could be useful for fighting games or perhaps to easily submit evidence of recurring bugs. The best part is it's not even a big of a file and even could be used on a customize games. Come back to the title, how did they do it?


texts: Why does this collision detection & resolution code only work for one side?

texts:
I am having a bit of trouble with my collision detection. It only works correctly for the right side, meaning, if I enter the tile from any other side, it brings me to the right side.

Here is my code:

const float spriteWidth = 5.0f;
const float spriteHeight = 14.0f;

float x = position.X;
float y = position.Y;

if (bounds.Intersects(tileBounds))
{
    if ((x + spriteWidth) > tileBounds.Left)
        position.X = tileBounds.Left - 5;
    if (x < tileBounds.Right)
        position.X = tileBounds.Right;
    if ((y + spriteHeight) < tileBounds.Bottom)
        position.Y = tileBounds.Bottom;
    if (y > tileBounds.Top)
        position.Y = tileBounds.Top - 14;
}

I just don't see why it would do that. I am calling this function from the Game1.cs Update function, FYI.

And it only works for one tile out of a possible many, but that's for a later question...

Does anyone have an idea why it would do this? Thank you very much.


texts: What is a good way to measure game virality?

texts:
I have added some social features to an iPhone game (Lexitect if you're curious), such as email, Twitter, and Facebook integration for sharing high scores.  Along with these features, I am measuring how many times users make it to each step. The goal of these features are to make the game more viral, and I am trying to get to a measure of game virality.

I would think that a game virality metric would produce a number based on 1.0, where 1.0 = zero viral growth, and 1.01 would represent 1% viral growth over some unit of time.

How is virality normally measured, and in what units?  How is time capped on the metric?  i.e. if I gave each player a year to determine how many recommendations they make, I wouldn't get any real numbers for a year from the time I start tracking it.  Are there any standards for tracking virality in a meaningful way?


texts: How do you get an object to orbit around a certain point on a 2d plane?

texts:
I had a concept for a game come to me this morning but I can't figure out how I'd go about implementing the movement.

The general idea involves the left and right controls causing a sprite to go round the center of the plane/(or the centre of the game area) in an orbit rather than moving left and right and the up and down will cause the orbit distance to either increase or decrease unless there is something in the way.

The best way I can think of doing this would be to maintain the polar coordinates of my sprite and convert that to Cartesian coordinates for drawing. Would that work? Is there an easier way?

Also how would I go about ensuring that the sprite was rotated such that it was at a right angle to the line from the center point?

Would I be better off implementing this using gravity and a using a repelling force to keep the character at the desired distance? If so How would I go about doing this?


texts: Multiple Sprite animation layers overlayed in Unity Animator

texts:
I have an animator with two layers, an axe layer and a body layer.

I would like to animate the two in sync with each other. They are both 64x64 sprite animations, frame-by-frame bitmaps.

The problem I'm having is I can't figure out how to alpha blend the layers. The axe either plays and the player body becomes invisible, or the axe isn't visible.

I have a bunch of states like this which each return to an idle state.
And link to an animation. I'd post a screenshot but I'm not allowed.

The axe layer is set to sync so the state machine looks the same, and I set the motion to the axe animations rather than the character body animations.


texts:
I am working on indicating on screen arrow to point towards the enemy. I have a environment which consist of a player and three enemy placed at different position on the environment.I need an arrow indicating the enemy,so that the player can move towards the enemy in the environment.

How can I do this?Can anybody please help me out.

I have got a script on searching.

public Texture2D icon; //The icon. Preferably an arrow pointing upwards.
public float iconSize = 50f;
[HideInInspector]
public GUIStyle gooey; //GUIStyle to make the box around the icon invisible. Public so that everything has the default stats.
Vector2 indRange;
float scaleRes = Screen.width / 500; //The width of the screen divided by 500. Will make the GUI automatically
//scale with varying resolutions.
Camera cam;
bool visible = false; //Whether or not the object is visible in the camera.

void Start () {
    visible = GetComponent<SpriteRenderer> ().isVisible;

    cam = Camera.main; //Don't use Camera.main in a looping method, its very slow, as Camera.main actually
    //does a GameObject.Find for an object tagged with MainCamera.

    indRange.x = Screen.width - (Screen.width / 6);
    indRange.y = Screen.height - (Screen.height / 7);
    indRange /= 2f;

    gooey.normal.textColor = new Vector4 (0, 0, 0, 0); //Makes the box around the icon invisible.
    visible=false;
}

void OnGUI () {
    if (visible) {
        Vector3 dir = transform.position - cam.transform.position;
        dir = Vector3.Normalize (dir);
        dir.y *= -1f;

        Vector2 indPos = new Vector2 (indRange.x * dir.x, indRange.y * dir.y);
        indPos = new Vector2 ((Screen.width / 2) + indPos.x,
            (Screen.height / 2) + indPos.y);

        Vector3 pdir = transform.position - cam.ScreenToWorldPoint(new Vector3(indPos.x, indPos.y,
            transform.position.z));
        pdir = Vector3.Normalize(pdir);

        float angle = Mathf.Atan2(pdir.x, pdir.y) * Mathf.Rad2Deg;

        GUIUtility.RotateAroundPivot(angle, indPos); //Rotates the GUI. Only rotates GUI drawn after the rotate is called, not before.
        GUI.Box (new Rect (indPos.x, indPos.y, scaleRes * iconSize, scaleRes * iconSize), icon,gooey);
        GUIUtility.RotateAroundPivot(0, indPos); //Rotates GUI back to the default so that GUI drawn after is not rotated.
    }
}

void OnBecameInvisible() {
    visible = false;
}
//Turns off the indicator if object is onscreen.
void OnBecameVisible() {
    visible = true;
}

}

The problem is start when I play the scene the arrow is seen at the start but its  get invisible soon


texts: Level loading works in Unity editor, but quits when deployed

texts:
In my level selection screen, all but the first level start out locked.

When I click on a level, it loads perfectly in Unity editor. However, when I build the game on a real device, the game stops as though I had pressed the back button on my device instead of launching the level.

What happened? How can I debug this, given it works fine in the editor?


texts: Weird texture binding bug on Mali-400 MP

texts:
On Mali-400 MP, there's a weird bug with texture binding.

Sometimes, shaders use textures from wrong samplers.

On other mobile and desktop GPUs, the same code works fine, but on Mali, almost every draw call is broken:

As you see, lightmap texture (at sampler 6) is used instead of diffuse texture (0).

Anyone knows a workaround to this?


texts: how to prevent call on OnValidate() when running game

texts: I need OnValidate() to be called only when I am designing my level (placing game objects at their respective positions and setting properties before running the project). But I don't want it to be called when I run the project. I can manually comment it out, but that will take a lot of time, since I have several OnValidate() calls. How can this be done, if it is possible?


texts: Maintain UI position with Aspect Ratio Fitter and anchor preset is set to stretch

texts:
So i have a text UI using Aspect Ratio Fitter with Aspect Mode Height Control Width and i set anchor preset to stretch upward  .

To make it easier to understand , i want my text to stretch upward only when screen height is increased , and at the same time , using Aspect Ratio Fitter , i want my text to keep width and height aspect ratio by stretching width when height is increased . And don't worry about screen height size become bigger than screen width size because i have separate UI for portrait .

When i apply both anchor preset stretch upward and Aspect Ratio Fitter , UI cannot maintain it position anymore if screen height is increased . So my question here is straightforward , how do i keep my UI inside my camera view while using Aspect Ratio Fitter and anchor preset is set to stretch ? , if possible , can it be done using unity built in feature ? (without me writing the script)

Here are screenshot below to show my problem :

(ps : ignore the error it doesn't have any correlation with this problem)

Before screen height change :

After screen height change  :


texts:
Is there any other recommended data I should store in the vertex buffers aside from a vertex' coordinates, normals and texture coordinates?
For example data I'd need for a feature that almost every mature game engine implements later on?


texts: Can polishing the GUI be ever considered a part of making the MVP?

texts:
I've read and watched about the MVP:

Minimum Viable Product for RTS game?
What should be created first in a video game?
And of course the video everything on the subject links to

I'm trying to apply this concept to the menu-based combat game I'm trying to make as a hobby project.

This is a little bit tricky because when I started the project I did not know about MVP. As a result, I first cut my original idea significantly down to what I considered the minimum release-worthy version of my game; so that I could, in the future, release my game and then iterate on this first release. This, obviously, was far more than what would be considered MVP. Out of necessity (the game started as a project for a Uni class) I first focused on coding the stuff so that I could show my code to my Prof.

The result is that I now have a large, working though bug-ridden and unplayable mess of a game that I'd now like to try to slowly bring to playability. In order to achieve this I'm finally trying to cut the game to MVP and only work on these parts of the game that form the MVP, ignoring the other parts; then iterate on this, until I hopefully finally bring order to everything I made earlier. (I even commented out lots of code that is not responsible for the MVP-ish parts of the game.)

Unfortunately, it has proven difficult for me to determine which parts of this game form MVP.

One such difficult case is the GUI. As far as I understand, GUI is only part of MVP insofar as absolutely necessary to allow me - the dev - to interact with the game. So monsters are to be represented as uncolored squares etc.

But the problem is also, as far as I understand, I should keep polishing the MVP until it seems fun and only then add any content. But I now think that polishing the GUI a little bit more is a prerequisite of this.

Example 1: In the spirit of the MVP, I do not have health bars now. Instead, I have bare numbers on top of the empty space where the monster's sprite is supposed to be placed in the future. However, I find it not very readable to have a monster's HP represented as 3649/6000. A bar filled to around 60% of its maximum length would be far more readable IMO.

Example 2: The status console. Originally, since I only focused on writing more code, the console was a mess. Status messages were often in a counter-intuitive order, were poorly broken into paragraphs, etc. I found that this itself was making it annoying for me to interact with the game. So I started working to fix the console, and I think I fixed it somewhat, but enough to make me satisfied. I would now like to continue working on fixing the console.

Both examples show why I have feeling that polishing the GUI beyond what would be considered MVP is a prerequisite of making the correct MVP. I don't know, maybe it's a peculiarity of menu-based combat games: the menus themselves are at the very core of the game so they should be usable and information from the game should be displayed in a clear way that makes it easy to comprehend what is going on?

Am I correct that stuff like adding health bars instead of bare numbers and breaking the status messages into paragraphs correctly, displaying some of them in a smaller font, adding sleeps between more important messages can be considered a part of making the MVP? Or am I misunderstanding the concept of the MVP?


texts:
I have this program that starts a loop when the key is pressed

The problem is that when i start the loop, i want to be able to stop it halfway with my mousepress.

The problem is that it doesn't register my mousepress until my loop is done.

How do I stop it halfway if the mouse was pressed in my loop? I tried  a flag, if(mousePressed) but the flag doesnt change until the loop is done


texts:
I'm using CUDA 4.1 to parse in the update of my Particle system that I've made with DirectX 10. So far, my update method for the particle systems is 1 line of code within a for loop that makes each particle fall down the y axis to simulate a waterfall:

m_particleList[i].positionY = m_particleList[i].positionY - (m_particleList[i].velocity * frameTime * 0.001f);

In my .cu class I've created a struct which I copied from my particle class and is as follows:

struct ParticleType
{
    float positionX, positionY, positionZ;
    float red, green, blue;
    float velocity;
    bool active;
};

Then I have an UpdateParticle method in the .cu as well. This encompass the 3 main parameters my particles need to update themselves based off the initial line of code. :

   __global__ void UpdateParticle(float* position, float* velocity, float frameTime)
{

}

This is my first CUDA program and I'm at a loss to what to do next. I've tried to simply put the particleList line in the UpdateParticle method, but then the particles don't fall down as they should.

I believe it is because I am not calling something that I need to in the class where the particle fall code use to be. Could someone please tell me what it is I am missing to get it working as it should?

If I am doing this completely wrong in general, the please inform me as well.


texts: How to deal with weapon power-creep in an RPG?

texts:
Power creep is a process that sometimes occurs in games where new content slowly outstrips the power of previous alternatives. This leads to players abandoning previous options in favour of the latest and more powerful alternatives, resulting in an inevitable increase in power throughout the game.

I am developing a private RPG that has approximately 10 players. Although the scale of the game is very small, it is falling victim to power-creep. Four players have reached the current "end-game" weapon and armor set and are running out of things to accomplish in terms of collecting the most powerful items.

I have a lot of great ideas planned, but many of them involve releasing weapons that are not stronger than the current strongest. The negative of this is that the players who have already achieved something greater don't look forward to the content update, and tend to come online less often. I don't want to release a weapon that is stronger, because this releases a lot of new issues with balancing in other areas of the game.

I have a couple of ideas that could slow this issue:

Although the new weapons may hit less damage, they may perform different effects that benefit the player in different ways
Reduce the damage of all weapons, so the slot for the previously-strongest weapon opens up for a new weapon.

How do I slow/stop power-creep of weapons and armors? (This question is not about finding ways to keep players online longer).


texts: How can the Server send a message to a single Client?

texts:
I'm trying to send an Rpc, or any sort of message, to a specific client instead of to them all.

I'm completely at the loss trying to associate a NetworkConnection with its own authoritative spawned player (from playerPrefab).

If I let the NetworkManager auto-spawn it, then I don't know how to get the connection from the player object.

If I override OnServerReady and I spawn it myself, then it has no authority on the client and I don't know how to give it.

I've browsed all sort of documentation but I couldn't find anything useful. Obviously there must be a way to do that, but I really can't find it.


texts: How to build a static version of cocos2d-x and link it to my project

texts:
Firstly, I'm using Cocos2d-x v3.6 for Win32 desktop + Visual studio 2013 and C++.

When building Cocos2d-x, always it has been built as a dynamic version not a static version as I want.

How to build it as static version ?
Then, How to bind it with the project ?


texts:
I want to draw a rectangle box to use as a text background for a visual novel library I'm writing, I wanted some flexibility of color and transparency and the ShapeRenderer class seems to fit the need but the doc brings this disclaimer:

This class is not meant to be used for performance sensitive applications but more oriented towards debugging.

If I use it as background the most action on screen would probably be the text scrolling over it.
Can someone more experient on the engine tell me if it is viable to use it under those premises, or it is really for debug only?


texts: OpenGL ES 1.1: Is it more efficient to use glClear or use glDrawArrays with primitives that render over used frames?

texts: For example, if I have several figures rendered over a black background, is it more efficient to call glClear(GL_COLOR_BUFFER_BIT) each frame, or render black triangles over artifacts from the past frame? Answers pertaining to other versions of OpenGL are also greatly appreciated.


texts: I know that it is more efficient than stencil test, but am I right assuming that the same functionality could be achieved using projection transformations with viewport?


texts: Godot: Possible to create a 2D tilemap and set it as a texture for a 3D surface?

texts: If I created tilemap of some sort of pattern or image and wanted to set it as the texture of a 3d surface or 3d model, how would I do it?


texts: Data model for unlockable card collection

texts:
My game has a collection of cards (about 64) that are unlocked (one by one) provided that 4 items are collected/gained in the game.

Right now the deck of cards is modeled with a plist file, like this:

<plist>
     <dict>
    <key>card1</key>
  <dict>
    <key>available</key>
    <true/>
    <key>series</key>
    <integer>1</integer>
    <key>model</key>
    <integer>1</integer>
    <key>color</key>
    <integer>1</integer>
</dict>
<key>card2</key>
<dict>
    <key>available</key>
    <false/>
    <key>series</key>
    <integer>1</integer>
    <key>model</key>
    <integer>1</integer>
    <key>color</key>
    <integer>2</integer>
</dict>

The value for the key named "available" marks if the item is locked or not. Right now I have to include the data for the items collected by the user, but including that inside the plist looks like too much hassle.

What kind of structure should be more suitable for this? How do you manage a collection of unlockable items like this?


texts: How do I make a low pass filter (average of readings over time) for compass?

texts:
I'm making a prototype for android that pulls compass data from the phone. I want to stabilize it so it is less jerky, by taking the average of the last couple of readings.

I have done this for accelerometer readings with great success, but adding every measurement to a queue and then collapsing it and dividing it by the queue size (= calculating the average) but for angles this is different.

If my measurements are for example:

  350, 359, 360

I could calculate the average as 356.3

But if my measurements are

  350 359, 1

Then my average is  236 which is a radically different angle.

Is there any way you guys can think of I could deal with this?


texts: Is it possible to design Android game(AndEngine) levels using XML?

texts:
I am developing a game. In the game there is a lot of levels. Is it possible to design game levels using XML? Or what are different ways to design game levels? Please help me.
Give some link or example so that i can understand easily...
Thanks


texts: How to calculate a simple swivel rotation? (no physics engine)

texts:
Assuming i know the geometry and the rotation angle of a cart, how can i calculate the rotation angle of a swiveling wheel?

To get the rotation angle of the wheel, i tried by calculating the distance from the rotation axis, and to apply a friction coefficient:

var dx = cartCX - wheelCX,
    dy = cartCY - wheelCY,
    dist = Math.sqrt(cartCX * wheelCX + cartCY * wheelCY);

var wheelRotation = Math.atan2(-dy, -dx) * dist * friction;

But all this has not brought me any acceptable result.

Which is a simple way to get the wheels rotation angle about the Y axis when the cart is rotating?

I don't need exact physics simulation, just a smooth rotation angle which i can tween. I think there should be no need to use any physics engine, or i'm wrong?


texts:
To measure CPU code, I use a Stopwatch. Using a Stopwatch in the Draw method is meaningless for the GPU side of things since the CPU and the GPU run asynchronously.

The questions is simple: Is it possible to measure the total time spent on a chunk of HLSL code? Perhaps as granular as the technique/pass.


texts: Entity Component System: Dependency Between Systems

texts:
Inspired by the Entity Component System Architecture, I started to refactor my 2D tiled-based game to follow the rule "favor composition over inheritance".
However, after writing the movement related components and system, I wasn't sure how to continue and implement the AIControllerSystem:
On one hand, I want to decuple as much as I can the MovementSystem and AIControllerSystem, and on the other hand I want to be able to send a movement action from AIControllerSystem to MovementSystem so I won't need to reimplement the movement logic.
Currently, my movement code looks like this:
public class PositionComponent : IComponent
{
    public int X { get; set; }
    public int Y { get; set; }
    public Direction FacingDirection { get; set; }
}

public class MovementComponent : IComponent
{
    public int Speed { get; set; }
    public Direction Direction { get; set; }
    public bool IsMoving { get; set; }
    public byte OffsetInTile { get; set; }
}

public class MovementSystem : ISystem
{
    private long _timer;

    // states the behavior depends on
    private PositionComponent _positionComponent;
    private MovementComponent _movementComponent;

    public MovementSystem(PositionComponent positionComponent, MovementComponent movementComponent)
    {
        this._positionComponent = positionComponent;
        this._movementComponent = movementComponent;
        this._timer = 0;
    }
    public void Update(long elapsedTime)
    {
        // some logic
    }

    public bool CanMove(Direction moveDirection)
    {
        return !this._movementComponent.IsMoving;
    }

    public void Move(Direction moveDirection, bool updateFacing=true)
    {
        if (this.CanMove())
        {
            this._timer = 0;
            this._movementComponent.IsMoving = true;
            this._movementComponent.Direction = moveDirection;
            if (updateFacing)
                this._positionComponent.FacingDirection = moveDirection;
        }
    }
}

My Approach
I thought about several ways to handle the AIControllerSystem->MovementSystem dependency:

Let the AIControllerSystem hold a reference to the MovementSystem, and send messages via a simple method call.
Let the AIControllerSystem send messages to the MovementSystem via a message queue.
Declare interface IMovable for movable game objects, and let the AIControllerSystem hold a reference   to such interface.
Sticking to the ECS architecture, expose the MovementComponent and PositionComponent to the AIControllerSystem, and "communicate" through them.

Personaly, I think options 3 and 4 are better, although option 4 may lead to code duplications (e.g. check if move is valid, unless the MovementComponent will be changed).
Option 3 will allow me to add game objects like the following:
public class Player : IMovable
{
    // states
    MovementComponent _movementComponent;
    PositionComponent _positionComponent;

    // behaviors
    MovementSystem _movementSystem

    //...
}

public class NPC : IMovable, IAIControllable
{
    // states
    MovementComponent _movementComponent;
    PositionComponent _positionComponent;

    // behaviors
    MovementSystem _movementSystem
    AIControllerSystem _aiControllerSystem // will be dependent on the NPC

    //...
}

I know my design is not "pure" ECS or even close to, but I think this hybrid approach is pretty modular to easily perform changes and add game objects with unique behavior combinations.
What do you think?
Thanks.
Edit
Some clarifications:

The MovementSystem is responsible for updating position (old tile -> neighbor tile) based on Speed, while the OffsetInTile represent a fixed point current movement progress (0-255).
For now, the AIControllerSystem is responsible for the movement "thinking" and operating of non-player entities (like NPCs).
The problem in short: keeping the described systems decupled, while letting the AIControllerSystem to communicate with the MovementSystem to perform movement actions.


texts: Good introduction to all things game dev?

texts: I saw a lot of books which cover specific topics, but is there a book or a recommendation of a few books which covers the basic of everything involved in making a game? I know this would only cover the basics, but that would be a good starting point to later read more into specific topics.


texts: How does "internet connection required" protect from piracy on mobile phones?

texts:
Sometimes I can't play a paid Android platform game because it requires an internet connection, and I'm in a place where 3G doesn't work.

Here is my understanding so far:

The game is a "good old platformer" which wouldn't normally require any network (no online features for the main solo story)
Because the publisher can't control the hardware (Android, iOS), they achieve anti-piracy by requiring an internet connection when launching the game and before each level.

My question is: how can they achieve to "obfuscate" the app enough to decrease the likelihood of piracy, where thousands of players would play the full game without purchasing? Is it extremely difficult for a hacker to record the successive states (memory snapshots) of the game when playing the full version, and recombine them in a pirate app that would skip the network traffic?

I understand that the anti-piracy internet requirement is part of a legit business model, and I'm still scratching my head about how this can be implemented and enforced in practice, and how I could do the same "from scratch".


texts: Network Message Registering message handler Problem

texts:
I have a confusion about when and where to use NetworkServer.RegisterHandler() and NetworkManager.singleton.client.RegisterHandler()? And also I am getting Unknown message ID 1002 error.

I have a message class

public class NetworkMsgHandler : NetworkBehaviour {

public const short movement_msg = 1002;

public class BulletMovementMsg : MessageBase {

    public string objectName;
    public Vector3 objectPosition;
    public Quaternion objectRotation;
    public float time;
}

}

I have ServerRelay which has ServerOnly authority has Script ServerRelay for registering Message Handler on Server.

public class NetworkServerRelay : NetworkMsgHandler {
private void Start()
{
    if(isServer)
    {
        RegisterNetworkMessages();
    }
}

private void RegisterNetworkMessages()
{
    NetworkServer.RegisterHandler(movement_msg, OnReceivePlayerMovementMessage);
}

private void OnReceivePlayerMovementMessage(NetworkMessage _message)
{

    BulletMovementMsg _msg = _message.ReadMessage<BulletMovementMsg>();
    NetworkServer.SendToAll(movement_msg, _msg);
}

}

Then I have Bullet GameObject it has script Projectile which is sending movement message this class is derived from NetworkMsgHandler.

public class NetworkProjectile : NetworkMsgHandler {

private void Start() {

    if (localPlayerAuthority) {

        canSendNetworkMovement = false;
        RegisterNetworkMsg();
    }
    else {

        isLerpingPosition = false;
        isLerpingRotation = false;

        realPosition = transform.position;
        realRotation = transform.rotation;
    }
}

private void RegisterNetworkMsg() {

    NetworkManager.singleton.client.RegisterHandler(movement_msg, OnReceiveMovementMsg);
}

private void OnReceiveMovementMsg(NetworkMessage networkMessage) {

    Debug.Log("Message received");
    BulletMovementMsg msg = networkMessage.ReadMessage<BulletMovementMsg>();

    if(msg.objectName != transform.name) {

        ProjectileManager.Instance.SpawnedBullets[msg.objectName].GetComponent<NetworkProjectile>().ReceiveMovementMsg(msg.objectPosition, msg.objectRotation, msg.time);
    }
}

public void ReceiveMovementMsg(Vector3 position, Quaternion rotation, float _timeToLerp) {

    //lerping between position
}

private void Update() {

        if(!canSendNetworkMovement) {

            canSendNetworkMovement = true;
            StartCoroutine(StartNetworkSendCoolDown());
        }
}

private IEnumerator StartNetworkSendCoolDown() {

    timeBetweenMovementStart = Time.time;
    yield return new WaitForSeconds((1 / networkSendRate));
    SendNetworkMovement();
}

public void SendNetworkMovement() {

    timeBetweenMovementEnd = Time.time;
    SendMovementMsg(bulletID, transform.position,transform.rotation, (timeBetweenMovementEnd - timeBetweenMovementStart));
    canSendNetworkMovement = false;
}

public void SendMovementMsg(string _bulletID, Vector3 position, Quaternion rotation, float timeToLerp) {

    BulletMovementMsg _msg = new BulletMovementMsg() {

        objectRotation = rotation,
        objectPosition = position,
        objectName = bulletID,
        time = timeToLerp
    };

    NetworkManager.singleton.client.Send(movement_msg, _msg);
}

}

So whenever a bullet spawns it generates an error on client side saying Unknown message ID 1002 connId:1
UnityEngine.Networking.NetworkIdentity:UNetStaticUpdate()


texts:
I've been using allegro for some time, and the timer event worked in all my previous projects, but I don't know what happened this time, I want to move a piece as long as the game is going, but it isn't moving at all, so the timer event isn't working, why is that? I've made sure all event sources are registered. Here is the code that reproduces the problem:-

int firstStuffXPos = 100;
int firstStuffYPos = 100;
ALLEGRO_EVENT_QUEUE *eventqueue;
ALLEGRO_DISPLAY *display;
ALLEGRO_TIMER *timer;
int width = 800;
int height = 600;
int FPS = 60;
 bool donePlaying = false;

class MyClass{
public:
int getXPos()
{
    return x;
}
int getYPos()
{
    return y;
}
int x;
int y;
 MyClass(int x, int y){
    this->x = x;
    this->y = y;
    stuffone;
}
ALLEGRO_BITMAP *stuffone;
};
MyClass stuff1[] = {
{ firstStuffXPos, firstStuffYPos},
};
void initialize(){
    al_init();
    if (!al_init()){
        std::cout << "Failed to initialize allegro5." << std::endl;
    }
    al_init_image_addon();
    if (!al_init_image_addon()){
        std::cout << "Failed to initialize image." << std::endl;
    }
    display = al_create_display(width, height);
    if (!display){
        std::cout << "Failed to create display." << std::endl;
    }
    al_install_keyboard();
    if (!al_install_keyboard()){
        std::cout << "Failed to install keyboard." << std::endl;
    }
    al_init_primitives_addon();

    eventqueue = al_create_event_queue();
    timer = al_create_timer(1.0 / FPS);

    al_register_event_source(eventqueue, al_get_display_event_source(display));
    al_register_event_source(eventqueue, al_get_keyboard_event_source());
    al_register_event_source(eventqueue, al_get_timer_event_source(timer));

    }
int main(){
initialize();
for (int nostuff = 0; nostuff < 1; nostuff++){
    stuff1[nostuff].stuffone = al_load_bitmap("blueblock.png");
}
    while (!donePlaying){
        al_clear_to_color(al_map_rgb(0, 0, 0));
        ALLEGRO_EVENT ev;
        al_wait_for_event(eventqueue, &ev);
        al_start_timer(timer);
        if (ev.type == ALLEGRO_EVENT_TIMER){
            firstStuffXPos += 5;
            firstStuffYPos += 5;
        }
        for (int i = 0; i < 1; i++){
            al_draw_bitmap(stuff1[i].stuffone, stuff1[i].getXPos(), stuff1[i].getYPos(), 0);
        }
        al_flip_display();
    }

    al_flip_display();
}


texts: Networking server/client library to setup p2p connection

texts:
I'm making a multiplayer game, and I want to setup a p2p network.
I'm coding a server in python to make the matches and send each player it's adversary ip and port, but I'm having trouble to make udp hole punching to work.
On the client side I'm using ENET library that works over UDP.
Is there any library specific for game networking that will include all necesary from making the match to setup the p2p?


texts: Nonsense error when increasing LightSource angle?

texts:
My project has a Light Source and a Sky Sphere Blueprint.

The rotation on the y axis (Light Source) defines the position of the sun (Sky Sphere Blueprint).

Character Blueprint (increases by 10 degrees on the y-axis rotation of Light Source, the updates the position of the sun):

When you click the button (Angulo, circled in pink), the angle increases by 10 and works to a certain moment:

Image with angle increased by 10:

When it reaches 100 degrees, it starts to go wrong. Each time I click the button it goes from 90 to 100 and vice versa in an infinite loop:

I've already tried to turn it around, subtracting instead of adding, but at one point it also gives error (in the case with 110 degrees).


texts: How should I handle sprite creation for customizable 2D characters?

texts:
I'm want to create avatar animations (sprites) for a browser-based MMORPG. The player is able to customize the character, and the content changes often (new weapons, armors, and so on). How can I structurally manage the creation and updating of all the sprite sheets?

The amount of different combinations are big enough that simply generating all permutations won't work.

This can be server- or client-based, but if it works entirely on the client, please keep it to just HTML5/CSS/Canvas/WebGL.


texts: SRV from UAV on the same texture in directx

texts:
I'm programming gpgpu raymarching (volumetric raytracing) in directx11. I succesfully perform compute shader and save raymarched volume data to texture. Then i want to use same texture as SRV in normal graphic pipeline. But it doesnt work, texture is not visible.

Texture is ok, when i save it file it is what i expect. Texture rendering is ok too, when i render another SRV, it is ok. So problem is only in UAV->SRV. I also triple checked if pointers are ok. Please help, i'm getting mad about this.

Here is some code:

//before dispatch
D3D11_TEXTURE2D_DESC textureDesc;
ZeroMemory( &textureDesc, sizeof( textureDesc ) );
textureDesc.Width = xr;
textureDesc.Height = yr;
textureDesc.MipLevels = 1;
textureDesc.ArraySize = 1;
textureDesc.SampleDesc.Count = 1;
textureDesc.SampleDesc.Quality = 0;
textureDesc.Usage = D3D11_USAGE_DEFAULT;
textureDesc.BindFlags = D3D11_BIND_UNORDERED_ACCESS | D3D11_BIND_SHADER_RESOURCE ;
textureDesc.Format = DXGI_FORMAT_R32G32B32A32_FLOAT;
D3D->CreateTexture2D( &textureDesc, NULL, &pTexture );

D3D11_UNORDERED_ACCESS_VIEW_DESC viewDescUAV;
ZeroMemory( &viewDescUAV, sizeof( viewDescUAV ) );
viewDescUAV.Format = DXGI_FORMAT_R32G32B32A32_FLOAT;
viewDescUAV.ViewDimension = D3D11_UAV_DIMENSION_TEXTURE2D;
viewDescUAV.Texture2D.MipSlice = 0;
D3DD->CreateUnorderedAccessView( pTexture, &viewDescUAV, &pTextureUAV );

//the getSRV function after dispatch.
D3D11_SHADER_RESOURCE_VIEW_DESC srvDesc ;
ZeroMemory( &srvDesc, sizeof( srvDesc ) );
srvDesc.Format = DXGI_FORMAT_R32G32B32A32_FLOAT;
srvDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
srvDesc.Texture2D.MipLevels = 1;
D3DD->CreateShaderResourceView( pTexture, &srvDesc, &pTextureSRV);


texts: Implementing cheat safe loot algorithm at clientside

texts:
I am developing a "city building" type of browser based flash/flex game. I was checking some of the implementation of existing one of the popular games in facebook using decompilers. I noticed they have implemented the loot algorithm the client side and sending the loot item to the server which I think is not cheat safe.

Knowing the fact that there are cheaters every where and it is easy to manipulate the messages and send the best loot always, is there any way we can counter this type of cheats?

I dont have a concrete solution designed for it yet but I am thinking to track the drops by maintaining the loot history.

So instead of mere updating the resources/inventory, I will implement a logic which will compare the loot with history to see if the player is receiving the rare drops excessively and flag the user or take a smart decision (which I don't have yet)

Or

Is it a good idea to implement the loot algorithm in the server side? Since this is "city building" kind of game, where it will not have extensive user actions like in typical RPG games which can trigger loot events.


texts: Implementing vector based movement in a 2d environment

texts:
Good evening.

I apologize if the title is a bit vague, I really could not come up with anything better.
I am currently reading a book called the nature of code and as a side project, I am working on a small 2d game in javascript.

One of the core concepts of this book states that a game object should incorporate three vectors, acceleration, velocity and location, where only acceleration is directly modified by the player. This translates to the following code;

    acceleration.add(0, 0.001);
    velocity.add(acceleration);
    location.add(velocity);

This works perfectly fine and so does the the .sub() method, when I want to move backwards.
However, this requires two functions. Also, all vectors have to be positive. This is quite a pain because I now have to decide whether the applied vector is a positive or a negative one, thus requiring methods like applyForceNeg(vec) and applyForcePos(vec). I'd much rather have one method where I could pass any vector.

I have pasted some of the code here.

How would I implement this without turning the code into a complete mess?

Any help would be much appreciated.

EDIT:

I figured out what actually caused all this;

As you can see here, I initially wrote the if statement so that upon every run, acceleration gets incremented by 0.001. Then acceleration gets added to velocity, which in turn gets added to location. The problem was that I did not set acceleration back to zero.
So in the first run, acceleration is set to 0.001, so is velocity and location. However, in the second run, acceleration increases by 0.001, yielding a total value of 0.002 which in turn gets added to velocity and location. Therefore we now have acceleration = 0.002, velocity = 0.003 and location = 0.003. After the third run, velocity and location are at 0.006 while acceleration is at 0.003.

Now, when I set acceleration to zero, it reduces the problem. Only if I also reset velocity, the problem is gone. However, I doubt this is the right way to do it...


texts: How to zoom image on Unity UI to particular point where mouse cursor is located?

texts:
I have some RectTransform on Unity UI. I have already implemented some Zoom functionality but now I need it to zoom to the area where the mouse cursor is located. Currently, it zooms to the anchor point. How can I zoom to the mouse cursor?

Here are some screenshots from a hierarchy.

I have already implemented zoom itself.

public class ZoomableRect : MonoBehaviour
{
    [SerializeField] private RectTransform rectToZoom;

[SerializeField] private ZoomConfigs zoomConfigs;

private bool onObj = false;

[SerializeField] private ScrollRect scrollRect;
public ScrollRect ScrollRect
{
    get { return scrollRect; }
    set { scrollRect = value; }
}

private bool isZoomAllowed;
public bool IsZoomAllowed
{
    get { return isZoomAllowed; }
    set { isZoomAllowed = value; }
}

private bool isFullScreen;
public bool IsFullScreen
{
    get { return isFullScreen; }
    set { isFullScreen = value; }
}

void Start()
{
    if (!rectToZoom)
        rectToZoom = GetComponent<RectTransform>();

}

void Update()
{
    float scrollWheel = -Input.GetAxis("Mouse ScrollWheel");

    if (isZoomAllowed && scrollWheel != 0)
    {
        ChangeZoom(scrollWheel);
        SetPosition(Input.mousePosition);
    }
}

private void ChangeZoom(float scrollWheel)
{
    float rate = 1 + zoomConfigs.zoomRate * Time.unscaledDeltaTime;

    if (scrollWheel > 0)
    {
        SetZoom(Mathf.Clamp(transform.localScale.y / rate,
         zoomConfigs.minSize, zoomConfigs.maxSize));
    }
    else
    {
        SetZoom(Mathf.Clamp(transform.localScale.y * rate,
         zoomConfigs.minSize, zoomConfigs.maxSize));
    }
}

private void SetZoom(float targetSize)
{
    transform.localScale = new Vector3(targetSize, targetSize, 1);
}

public void SetPosition(Vector2 mouseInput)
{
    float rectWidth = rectToZoom.rect.width;
    float rectHeight = rectToZoom.rect.height;

    float mousePosX = mouseInput.x;
    float mousePosY = mouseInput.y;

    float widthPivot = mousePosX / rectWidth;
    float heightPivot = mousePosY / rectHeight;

    Debug.Log("widthPivot = " + widthPivot + " heightPivot = " + heightPivot);

    rectToZoom.anchorMin = new Vector2(widthPivot, heightPivot);
    rectToZoom.anchorMax = new Vector2(widthPivot, heightPivot);

    rectToZoom.transform.position = new Vector2(mousePosX, mousePosY);
    Debug.Log("MousePosX = " + mousePosX + " MousePosY = " + mousePosY);
}

public void SetAnchors(bool isFullScreen)
{
    if (!isFullScreen)
    {
        rectToZoom.anchorMin = new Vector2(1, 1);
        rectToZoom.anchorMax = new Vector2(1, 1);
    }
}

}

But anchors always snap to the bottom left corner. And widthPivot and heigtPivot values are always bigger than 1.

Actually, after testing, I see that anchors are less than 1 when the cursor is located in the bottom left part of the screen. And bigger than 1 when the cursor is in the top right part of the screen.

When zooming it always snaps to the bottom left corner.

It seems that mouse position connected to the current resolution at the same time canvas on which zoomableRect is potisioned has reference resolution of 1920 x 1080.

Changing a pivot in the same way instead of anchors doesn't have any effect. Same result.


texts: Finding the correct speed for AI to turn to reach goal

texts:
I have a ship that travels at max speed maxSpeed and can turn rotationSpeed degrees per second. The ship always moves in the direction it is facing which means that the faster the ship is travelling the larger its turning radius is.

I know my position, and rotation and the target's position.

What I would like to figure out is whether a target is inside my turning radius at this speed, or better, what is the maximum speed I can travel at is in order to make the turn to the target without continually circling around it.

Is there an efficient(ish) way to do this?

Here is what I am thinking so far: because I know how far I am travelling per step and how much I am rotating per step, I can figure out where I will be in the next two frames. My current position is p1, my next position is p2 then p3. I can take the perpendicular bisectors of  (p1, p2) and (p2, p3). Their intersection point will give me the center of a circle. I can then test if the target is in that circle.

I'm unsure if this will work in 3D (I'm unsure how to calculate a sphere with my inputs). This solution also doesn't help too much with finding the right speed at which to travel, I would have to try a few times with different speeds to find a reasonable one.

Can anyone shed some light on a better solution?


texts:
I want to make a 2D walled map. the walls must be L,T,+,-,| shaped. (made from vertical and horizontal lines) There must not be a complete closed block (i.e. all parts of the map must be connected). Also the map is actually not tile based. All the data I should generate for the map must be in form of x1,y1,x2,y2. which indicates start and endpoint of a horizontal or vertical line.

One idea was using a DFS maze generation algorithm on different parts of my map in order to get a non-perfect maze that has a lot of entrances and exits. But I think it is not a very good solution. Can Anyone help me to get a working algorithm that results wall in forms of x1,y1,x2,y2 of a horizontal or vertical line start and endpoints.

I think I could say it is a pacman like map but it is not tile based.

For example see this picture:

I drew this with paint and is not a perfect map but I want some algorithm that generates a better looking map like this. this map don't have any closed block.

I should say that I don't really need any graphics. I just need an algorithm that generate start and endpoint x,y of a line.


texts:
I am trying to make a tile based game in LibGDX and I have run into some problem.
In earlier versions of LibGDX you were able to draw a certain section of a .tmx map instead of a whole and even a section of a layer.
Even though , in the nightly builds I cannot find anything about this methods the only thing I have found was drawing of a whole map or one of its layers.

Ideally I would like to draw portion of a map something like draw nao from coords (5,5) to (25,25) . Meaning only the square 20x20 tiles starting from tile in the 5th row/column at position no. 5.

Is it even doable in the newer builds ?


texts: Im looking for a tron AI algorithm on snap!/scratch. If not can you help me develop an AI for this game?


texts: OOP design principles that fit with Unity

texts:
So my current concept is top-down arcade style game. Meaning you have a character and you walk around a closed space killing waves of enemies coming at you. My question is how to structure my abstractions. Since I'm using Unity3d at the end of the day there must a  MonoBehaviour component that exist in the scene. For example I can have the following structure for the character.

public class CharacterController : MonoBehaviour
{
    ICharacter _character;
    IInputController _inputController;
    //and so on
}

Is this a good idea at all ? Unity3d doesn't really cater to normal OOP practices imho. I know this question can be flagged as opinion based but please find it in your heart not to. I want to figure out a pattern to write good and easily extensible code in unity.


texts:
I am trying to compile a glfw application on mingw.
I am using 64 bit windows and 32bit mingw compiler And I have downloaded 32 bit binaries from http://www.glfw.org/download.html I am trying do by linking to libraries as follows

-lglfw3 -lglew32 -lopengl32 -lglu32 -lgdi32

But I get the following error

c:/mingw/bin/../lib/gcc/mingw32/4.8.1/../../../libglfw3.a(init.c.obj):init.c:(.text+0x49): undefined reference to `__ms_
vsnprintf'
collect2.exe: error: ld returned 1 exit status


texts:
I'm thinking about how I should manage collisions in my game. I'm thinking about having a "Collision" class that checks for collision, and in case takes actions to resolve them.

My problem is this:

A and B moving to the other, when they collide they must bounce.

If I resolve the collisions sequentially, like calling:

A.collideWith(B)
B.collidesWith(A)

B will be stuck, because A has already updated his velocity and position, and when will be called B.collideWith(A) there won't be any collision anymore.

So, is it a good idea to use a double buffer pattern?

I'll write the values obtained by the collision resolver in some variables, they will be swapped to the real ones when all the collision has been resolved. In that way all should work fine.

But it is a good software design?

EDIT

I see, yes of course i check only for half.
So there should be a class that checks for collisions, and should be like:

checkedpairs.clear();
for( Object a : objects )
{
    for( Object b : objects )
    {
        if( ! a.collideWith( b ) || checkedpairs.contains( a, b ) ) return;

        Object a1 = copyf( a );
        Object b1 = copyOf( b );

        a.collideWith( b1 );
        b.collideWith( a1 );

        checkedpairs.add( a, b );
    }
}

Instead of putting the logic for the swap in the objects themselves...

But that way, I'm creating two objects for each collision, isn't too much overhead?

The problem is that I don't need only the position, but al lot of physics stuff like velocity, acceleration, mass... Should I pass them? Isn't it too hard-coded?


texts: How can I render from a buffer that exists and was created on on the GPU?

texts:
I'm looking for a unity API or function call to allow me to do the following ...

I wrote some really complex functions that are compute shaders. These compute shaders  manage a huge compute buffer containing voxel information. I then take portions of (or the entire) voxel buffer in another compute shader and produce a vertex buffer. All of this is done on the GPU with only compute shader calls from the CPU.

Now I want to render that vertex buffer but I must be looking in the wrong place because I can't find any information on how this is done within unity despite there being other examples on how to do this using raw DX or openGL approaches.

Can anyone point me in the right direction to determine how I can render using a specified shader a buffer already in graphics RAM (and ideally give it some textures too)?


texts:
My task: I want to split up a screen into 3 regions for buffs-bar (with picked items), score-info and a game-map. It doesn't matter are regions intersect with each other or not.

For example: I have a screen with width=1; height=1 and the origin of coordinates (0;0) is the left bottom point. I have 3 functions: draw items, draw info, draw map. If I use it without any matrix transformations, it draws fullscreen, because it's vertex coordinates are from 0;0 to 1;1.
(pseudo-code)

drawItems();
drawInfo();
drawMap();

And after that I see only map onto info onto items.

My goal: I have some matrixes for transformation vertexes with 0;0->1;1 coordinates to strict regions. There is only one thing, what I need to do - set matrix before drawing. So my call of drawItems-function is like:
(pseudo-code)

adjustViewMatrixes_andSomethingElse(items.position_of_the_region_there_it_should_be_drawn, items.sizes_of_region_to_draw);
setItemsMatrix();
drawItems(); //the same function with vertex coordinates 0;0->1;1,
             //but it draws in other coordinates,
             //because I have just set the matrix for region

I know only some people will understand me, so there is a picture with regions which I need to make. Every region has 0;0 -> 1;1 inner coordinates.


texts: Implementing game synchronization between clients and server

texts:
I'm creating a small online multiplayer game where I have multiple thin clients and an authoritative server. Both the client and the server have a fixed game loop.

Now I have a game entity with the following properties:

X position: float
Y position: float
Direction: float

In the client, the entity is in constant velocity changing its direction based on user input and sends an input event to the server.

[LEFT, PRESSED]: Entity moves to the left
[LEFT, RELEASED]: Entity moves to the right

Every event is queued on the server, and simulated the same way as on the client (calculating the new properties based on trigonometric functions) and the event is send to other players in the room. The other players apply the same simulation to that particular entity (keeping track of what key is pressed for each entity).

Now after some time playing, the position and direction start to drift and stop being in sync. I suspect this has to do with floating-point arithmetic(?)

Is this implementation correct, rather than sending its position and direction every step?
How would I solve this problem?
I think I need to make the server the single source of truth and send regular state snapshots to the the clients to correct possible mistakes/drifting? What would be a good interval to keep the clients up to date?
At the moment, I'm broadcasting an event to every player in the room. What would be a nice approach to only send events to players near the entity? Would a quadtree work here (the same I'm using for my collision detection)?


texts: Unity2D - Horizontal Scaling to Support Various Aspect Ratios?

texts:
I am trying to work out how to support various resolutions for my Android game. I have come up with a solution, but do not know how to implement it.

Automatically, I am told that Unity vertically scales the screen to match the screen, leaving more room at the sides. How can I change this behaviour? I am hoping to shrunk the game down till it fits horizontally, and filling it the background above and below with more decorative features. How can I achieve this?

I'm sorry if there is an obvious answer, I'm quite new working with the Unity UI system.

If it makes it any easier, my game is heavily based on UI, and is locked in landscape.

BIG EDIT: I completely rephrased this question because it was so broad and messy.