texts: Looking for a good technique for character movement in hack&slash game

texts:
I'm making hack&slash game and I want my characters move like for example in Torchlight, Diablo, etc.
Currently I generate set of nodes for all walkable areas of a floor. When I click somewhere player goes there
through interpolated path of nodes. This doesn't look very natural. Player moves like a robot.
Enemies also use this node system for movement and share the same issue but I have one more problem with them.
When enemies detect player they go to him by a shortest path. Sometimes they use the same path and line up
to the player instead of surrounding him. I don't know how to make enemies choose different paths and surround the player.
Do you know how can I solve this problems?
Maybe I should use different approach for character movement?

My current technique:

Torchlight screenshot:

---UPDATE---

I want to know how to deal with these situations:

Situation 1, I have dynamic/static obstalces on my way

Situation 2, Enemies have the sam path to player ( get into queue to fight with us )


texts:
I've just created another scene in Tiled and imported it into Unity using Tiled2Unity and I'm having a strange issue, while the image looks crisp and as it should in Tiled, when imported into Unity it's appearing blurry (all of the graphics in the prefab Tiled2Unity creates).

My tiles are 64x64 and the scale is PPU is set to 1.

Tiled (how I want it to look) -

Unity (how it imports)

Any help is appreciated, thank you.


texts: How to load additive scenes to the master client, per player, in unity using photon?

texts:
I have already successfully created a multiplayer scene where multiple users can join, however there are some issues like unity not allowing multiple sound listeners per scene. In order to alleviate this problem (hopefully) I would like to load an additive scene that connects to the master client. In the additive scenes will contain the other players. How can I achieve this using photon PUN2?

In normal unity non multiplayer it is a easy as SceneManager.LoadScene(sceneName,LoadSceneMode.Additive); With that code a new scene adds on to the scene already at play as a new scene. I wish to do so with photon PUN2 somehow, where the master client loads his scene and other players join the game using their own scenes. Currently the other players are loading into the scene with a simple instantiation of their prefabs PhotonNetwork.Instantiateand this is giving me errors such as the one stated above (multiple sound listeners)

Please help


texts:
I've recently started to learn some C# scripting in Unity. I've been able to make my PlayerCube move around using Vector3 Transform.translations, but I want my camera to follow my cube while moving around, and it's not working since Unity can't find PlayerCube. How do I make make it so it understands that there's a PlayerCube?

using UnityEngine;
using System.Collections;

public class CameraScript : MonoBehaviour {
    Player = GameObject.Find("PlayerCube");

    // Use this for initialization
    void Start ()
    {
    //  GameObject.Find(PlayerCube);
    }

    // Update is called once per frame
    void Update ()
    {
        Transform.LookAt (PlayerCube);
    }
}


texts:
My root node adds a scene - GameScene - in it's _ready function:

const game_scene = preload('res://scenes/game_states/game_state.tscn')
func _ready():
    var game_scene_instance = game_scene.instance()
    add_child(game_scene_instance)

And my GameScene, it adds my Level1 scene in it's _ready() function:

const level_1 = preload("res://scenes/stages/stage01.tscn")
func _ready():
    var level_instance = level_1.instance()
    add_child(level_instance)

In my stage01 scene, I have a Player scene that looks at input thru _unhandled_input() function, and does something based on that input.

func _unhandled_input(event):
    if event.is_action_pressed('ui_down'):
        print("Adding 15 points to the player's score")

But, I do not want my Player scene to receive any input. So, in my GameScene, I implemented it's _unhandled_input() function to mark every input it receives as handled.

func _unhandled_input(event):
    get_tree().set_input_as_handled()

But, if I press the 'ui_down' key on my keyboard, I still see "Adding 15 points to the player's score" printed in the console. Because I set the input as handled in the grandparent node, I thought that it wouldn't propagate downward?


texts:
How can I properly save rotation of the camera while swipe and pass it to  transform.rotation = Quaternion.Slerp() start start Quaternion?Right now after I swiped Gyro get his transform.position and I need to take the position after the swipe.

    protected void Update()
    {
        if (!using_Touch)
        {
            if (show_video)
            {
                   AttachGyro();
                show_video = false;
            }
            gyroEnabled = true;
            if (!gyroEnabled)
                return;
            if (from_touch)
            {
                transform.rotation = Quaternion.Slerp(First_position ,
cameraBase * (ConvertRotation(referanceRotation * Input.gyro.attitude) * GetRotFix()), lowPassFilterFactor);

            }
            else
            {
                transform.rotation = Quaternion.Slerp(transform.rotation,
cameraBase * (ConvertRotation(referanceRotation * Input.gyro.attitude) * GetRotFix()), lowPassFilterFactor);
            }
            from_touch = false;
        }
        int fingerCount = 0;
        foreach (Touch touch in Input.touches)
        {
            using_Touch = true;
            gyroEnabled = false;
            if (touch.phase != TouchPhase.Ended && touch.phase != TouchPhase.Canceled)
            {
                fingerCount++;

                float scalar = 0.8f;  //0.05f;
                transform.rotation = Quaternion.Slerp(transform.rotation,
    Quaternion.Euler(new Vector3(
                    transform.localEulerAngles.x + touch.deltaPosition.y *

scalar, transform.localEulerAngles.y + touch.deltaPosition.x * scalar, transform.localEulerAngles.z)), scalar);
    //need to set it to that variable
    First_position = Camera.main.transform.rotation;
                    from_touch = true;

            }
            else
            {
                using_Touch = false;

            }
        }
    }


texts: Vector-based fonts vs. bitmap fonts in (2d) games?

texts:
I know that many games are using bitmap fonts. Which are the advantages for vector-based font rendering / manipulation when compared to bitmap fonts and in which scenarios would they matter the most?

Prefer a focus on 2d games when answering this question.

If relevant, please include examples for games using either approach.

EDIT:
Please also include your personal preference if you have experience with the matter.

Some factors you might consider:

amount of text used in the game
scaling of text
overlaying glyphs and anti-aliasing
general rendering quality
font colors and styling
user interface requirements
localisation / unicode
text wrapping and formatting
cross-platform deployment
2d vs 3d

Background:

I am developing a simple falling blocks game in 2d, targeted for pc. I would like to add text labels for level, score, and menu buttons. I am using SFML which uses FreeType internally, so vector-based features are easily available for my project.

In my view, font sizes in simple games often don't vary, and bitmap fonts should be easier for cross-platform concerns (font-formats and font rendering quality). But I am unsure if I am missing some important points here, especially since I want to polish the looks of the final game.


texts:
I'm doing a little C# / OpenGL project and I can't manage to load textures properly.

So here is my texture class :

public class Texture
{
   public String Filepath;
   private int TextureID;

   public Texture(byte[] Filename)
   {
        Stream s = FileManager.FindTexture(Filename);

        if (s == null) return;

        Bitmap b = new Bitmap(FileManager.FindTexture(Filename));

        b.MakeTransparent(Color.FromArgb(255,0,255));

        //b = BitmapEx.Resize(b, b.Width * 2, b.Height * 2);

        //b.Save(DateTime.Now.ToFileTimeUtc().ToString() + ".png");
        //GL.Hint(HintTarget.PerspectiveCorrectionHint, HintMode.Nicest);

        GL.GenTextures(1, out TextureID);
        GL.BindTexture(TextureTarget.Texture2D, TextureID);

        BitmapData data = b.LockBits(new Rectangle(0, 0, b.Width, b.Height), ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);

        GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba8, data.Width, data.Height, 0, OpenTK.Graphics.OpenGL.PixelFormat.Bgra, PixelType.UnsignedByte, data.Scan0);

        b.UnlockBits(data);

        GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Linear);
        GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Linear);
        GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapS, (int)TextureWrapMode.Repeat);
        GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapT, (int)TextureWrapMode.Repeat);

        if(!GL.IsTexture(TextureID))
        {
            throw new Exception();
        }

    }

    public void Apply()
    {
        if (TextureID != 0)
        {
            GL.BindTexture(TextureTarget.Texture2D, TextureID);
        }
    }
}

As you can see, my bitmap loads well from the stream. I tried to save it after it loaded into a my debug folder and every texture loaded saves. So I'm pretty sure this part is not the problem. But everytime I try to do GL.IsTexture it returns false, I tried to apply my textures either it doesn't work.

I've used a similar method in another project where it was working.

        Bitmap bitmap = new Bitmap("Data/UI/" + File);

        GL.Hint(HintTarget.PerspectiveCorrectionHint, HintMode.Nicest);

        GL.GenTextures(1, out Texture);
        GL.BindTexture(TextureTarget.Texture2D, Texture);

        BitmapData data = bitmap.LockBits(new System.Drawing.Rectangle(0, 0, bitmap.Width, bitmap.Height),
            ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);

        GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba, data.Width, data.Height, 0,
            OpenTK.Graphics.OpenGL.PixelFormat.Bgra, PixelType.UnsignedByte, data.Scan0);
        bitmap.UnlockBits(data);

        GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Linear);
        GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Linear);
        GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapS, (int)TextureWrapMode.Repeat);
        GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapT, (int)TextureWrapMode.Repeat);

I can't see why it is not working right now.

My textures are loaded way after OpenGL is initialized.

I'm using C# .NET framework 3.5 with OpenTK 1.1 ( Runtime 2.0.5, fresh out of their websites ).

Can someone give me a hint on why it is not working, please ?

Warm regards, Chaussette.


texts:
I'm using LibGDX to implement rubber rope in which player can fly and launch. I know I could use Box2D as physics engine and I'm going to one day, but I'd like to learn it myself for now.

I've already got it working, but some unexpected movements are sometimes noticeable and I don't understand why. I feel like I haven't thought of something important. So I figured you guys might find a flaw in my implementation.

For starters, it looks like this:

My maths is basically taken straight from the physics class. There are two forces applied to the bird, because there are two fractions of the rope. Their sum is the actual force.

Both forces are obviously laid along the corresponding rope fractions. Magnitude of the force is |F| = kx, where k is some constant and x is how much this fraction had to stretch. I cache its initial length at the beginning of collision, then measure it each frame and calculate the difference. The code:

private void calculateForces() {
    //A and B are blue circles in the picture; M and Z are red

    //Negative number means no extension, hence Math.max call
    float modifierA = Math.max(0, A.dst(M) - mLengthA);
    float modifierB = Math.max(0, B.dst(Z) - mLengthB);

    mForceA.set(A.x - M.x, A.y - M.y).setLength(K*modifierA);
    mForceB.set(B.x - Z.x, B.y - Z.y).setLength(K*modifierB);
}

What am I not taking into consideration?

EDIT:

As requested, I made a video. You can see some weird movement at the end of second swing, and the third one is completely wrong.

I also tried getting rid of Math.max() call changing line to float modifierA = A.dst(M) - mLengthA;  and, suprisingly, it looks much better. Video. The question is why. Isn't it logical for the rope not to apply any force when it's not being stretched?


texts: How should I store a Game Database on Android?

texts:
I'm looking at creating a game for Android and while I have most of the ins and outs worked out, the one thing I'm struggling with is how to store data for the game.

Ultimately, the game will be based off of a lot of pre-defined data and statistics so the obvious choice to me would be something like SQLite, but as I'm pretty new to the realm of Android and Game Development, I'm not 100% certain if this is the right route to follow.

The data will be general pre-defined data as well as player data (along the lines of careers stats - what place finished, etc).

I was wondering if there was a better/best practice solution that wasn't SQLite and that would provide said functionality and if so, could you point me in the right direction?


texts: How can I make my image to be blur like the one in my message content?

texts:
Should I use post processing v2 depth of field or something else ? I want to do it for my main menu.
I have my own image and I want to make it blur like this one.
I changed my images texture type to Sprite (2D and UI) and assigned it to a ui image component.
Now the question how to make it blur ?


texts: How does Aspect Ratio and Resolution work in Unity?

texts:
I am trying to make progress in Unity on understanding how aspect ratios and resolution work. I can't quite wrap my head around the topic. For example, I am trying to make a simple breakout style game, but in order to do that, I need to consider the world units and how each brick would fit into the scene. From what I have read, world units are dependent on screen resolution and aspect ratio. How would I be able to make something like this if mobile games are played on different devices (and ones with notches nonetheless). Also I'd like to know how to achieve this without using the tacky black bars that some games use.
Any information regarding this would be extremely appreciated.


texts: Direct3D 11 : Vsync to 60 fps not matter the monitor refresh rate

texts:
I am working with Direct3D 11 and I am trying to figure out how to make my game run at 60 fps. Currently I use :

swapChain->Present(1, 0);

To max the fps with Vsync. This only works because my monitor is 60hz though. As I understood it, the first parameter of Present is used to divide the current screen's refresh rate to obtain a certain fps. So I can get 60fps by setting this to 2 on a 120hz monitor or even 4 on future 240hz monitor and so on.

My problem is this : what do I do with 144hz monitors? Is there any way to get 60fps vsync on those monitors?


texts: Avoiding particle "pop in" affect for Unity2D starfield

texts:
I've adapted a 3D starfield particle system for top-down 2D use. I'm aiming for what's shown in this video, which was based on this tutorial.

I've managed to reproduce the 3D particle system and I have a top-down view working correctly.

However, I'm trying to figure out what needs to change to achieve the effect in the first video. The difference for me is that this logic randomly spawns new particles within a radius around the camera, which in 3D seems fine, as if the stars are appearing as you travel towards them. But in "2D" this breaks because the player/camera can only move in two dimensions.

I need to find a way for stars to spawn off-screen, they can't "pop in" randomly as the player moves. Unfortunately I'm not sure how the developer of that video achieved it.

using UnityEngine;
using System.Collections;

public class Starfield : MonoBehaviour {
    private Transform tx;
    private ParticleSystem particleSystem;
    private ParticleSystem.Particle[] points;

    public int starsMax;
    public float starSize;
    public float starDistance;
    private float starDistanceSqr;

    void Awake() {
        particleSystem = GetComponent<ParticleSystem>();
        tx = transform;
        starDistanceSqr = starDistance * starDistance;
    }

    void Start() {
        points = new ParticleSystem.Particle[starsMax];

        for (int i = 0; i < starsMax; i++) {
            points[i].position = Random.insideUnitSphere * starDistance + tx.position;
            points[i].color = Color.white;
            points[i].size = starSize;
        }
    }

    void Update() {
        for (int i = 0; i < starsMax; i++) {
            if ((points[i].position - tx.position).sqrMagnitude > starDistanceSqr) {
                points[i].position = Random.insideUnitSphere.normalized * starDistance + tx.position;
            }
        }

        particleSystem.SetParticles(points, points.Length);
    }
}


texts:
Here is a litte sample that I drew in Blender to visualize what I am planing to create:

Cone with spheres sample

I already have the code to generate the cone and the spheres as mentioned in my former Post Combine 3D objects in XNA 4.

I thought that it would be nicer to generate a model and add these models to the sceen graph. My problem for now is that I wasn't able to generate a model out of my primitivas. I was planning to create one Mesh for the cone and one for each sphere that I want to attach to the cone and arrange all this in a Model, but there are no constructors for a Model or a Mesh.

So the question is: Is there a way to generate a model out of my primitives?


texts: How to set up a game loop for a project targeting iOS?

texts:
I'm a fellow game programmer who's done many game engines in Game Maker 8.1, Visual Studio XNA and MonoGame with C#, and one in Java Android with Eclipse. I'm very used to C# and love it plus the VS environment.

Now I'm trying to develop games for the App Store for iPhone and iPad (using Xcode 7 with a Macbook running Yosemite 10.10.5). I don't yet have an actual iPhone to test with, but the simulator is working with the blank and example projects I've found.

By way of googling, this is what I've looked at so far:

http://codewithchris.com/xcode-tutorial/

http://www.raywenderlich.com/40293/learn-to-code-ios-apps-2-strings-arrays-objects-and-classes

There was also a Storyboard example which I did not like. My intuition is to not use a wizard for anything, and the Storyboard builder seemed a lot like Windows Forms when I can just use the XNA draw functions.

Neither of those tutorials was very helpful and now I'm paranoid that I'm on the wrong track. Now I'm asking myself questions like should I be using SpriteKit or SceneKit? Should I be using Swift insteada Objective-C?

The thing is, if I can figure out how to draw pictures in a game loop, then I think I'm all set. However, I think I understand that I'm gonna need at least one UIView or Scene. What I want is a master_draw() function that gets called 30 times per second in main.m, and in master_draw() I loop through all objects and call their individual draw functions. Same thing with a master_update() function.

And I also found this open source example:
https://www.cocoacontrols.com/controls/1w-flappy

That example...I thought it would be the most helpful of all. But I couldn't find any game loop in it at all.

Am I on the right track? Does iOS stuff work totally different than a traditional game loop?

Specifically, I have 2 major questions:

What new project type should I chose? Blank, Single-View, or Game?
How to set up a game loop? (if possible)

What I'm thinking is something like this:

void master_update() // typically called 30 or 60 times per second
{
  foreach (GameObj G in ListOfGameObj)
    G.update(); // update all objects in the list of objects
}

and of course...

void master_draw() // typically called 30 or 60 times per second
{
  foreach (GameObj G in ListOfGameObj)
    G.draw(); // draw all objects in the list of objects
}

Where do I add that code and where do I call it? Is something like this possible in iOS or am i gonna hafta use a completely different architecture?

P.S. The kind of game I'm doing is a simple 2D puzzle where you hafta match up blocks. Nothing too fancy.


texts:
I'm trying to get Unity to filter through a list of nodes, but I am unsure on how to do so. This is what I have derived.

foreach (TileNode z in map.nodes)
        {
            int num = TileNode z;
            if(num%2==0){
                continue;
            }

            z.collider.enabled = true;
        }

However an error prompt states that 'z' is an unexpected symbol. Any advice on the proper syntax to deal with this will be greatly appreciated.

Also, an example of how do peform filtering using LINQ will be helpful.


texts: How could I handle non-rectangular tile collision in Tiled maps?

texts:
BrowserQuest map in question.

From what I understand, with tiled, there are two main ways to specify collision:

Create an object layer, and interpret the shapes in the engine as collision objects.
Create a tiled layer, and make all tiles in the layer have a collision property, and interpret all tiles in the layer as collision objects.

I'm using BrowserQuest as a big source of inspiration for my project, and I want to know how they handled collision on the level editing side.

I've checked through all their layers, expecting an object layer to be handling cliff collision like:

But there are no such object layers to be found.  Furthermore, the tile layers containing the tiles for such cliffs have no properties at all, meaning that they didn't just specify "collision" for such tile layers.

I especially need to know how they handled less rectangular shapes like:

I could imagine that they are not using explicit collision layers, but instead determining collision in the actual engine, based off the presence of specific tile layer sprites.  Only because BrowserQuest has whole-tile movement, and it wouldn't look too odd if a small apple, taking up only a fraction of the tile size, prevents movement over that entire tile.

But I'm creating a game with more precise movement, so collision has to be tight to the apple, and I really want to know how BrowserQuest approached collision defining.

If anyone knowledgeable with Tiled could take a quick look at the map, I'd appreciate it!  I'm tearing my hair out here :). Thanks


texts: Wise approach to becoming good at C# XNA

texts:
Would finishing an entire course about C# at HomeAndLearn.co.uk and then jumping into XNA be a wise path to take?

Ultimate goal is to create a multiplayer 2D game.


texts:
I have a prefab 'WhiteSmoke' that should render on top of the other objects on my game view but instead it just stays behind. The sorting layer some you see on the image named 'smoke' is the top layer, changing it to default and keeping the big order in layer number does not solve the problem.

The canvas render mode is ScreenSpace-Overlay.

Have any idea what I'm missing here? I don't know what else to try.


texts:
I am developing a game with a Minecraft-like terrain made out of blocks. Since basic rendering and chunk loading is done now, I want to implement block selecting.

Therefore I need to find out what block the first person camera is facing. I already heard of unprojecting the whole scene but I decided against that because it sounds hacky and isn't accurate. Maybe I could somehow cast a ray in view direction but I do not know how to check the collision with a block in my voxel data. Of course this calculations must be done on the CPU since I need the results to perform game logic operations.

So how could I find out which block is in front of the camera? If it is preferable, how could I cast a ray and check collisions?


texts:
I'm looking for some wise tips concerning a specific game development : Bomberman-like.

I am currently implementing a "random map" generation for the game, but I feel like I'm not doing in the best way :

I have a vector of Objects (fresh class having a type (like a Border, a Destructible Wall, a Bomb, a Player...) and two size_t for (x, y) coords) that I initialize when I create a map.
I generate Borders all around my Map that will define the game area.

This is the "I don't like that" part :

I generate some Unbreakable/Breakable Walls using random coords : if at these coords there is nothing but an empty space, I put a Wall there. So that the map is filled with a certain percentage of walls.

Do you have any ideas of how to generate a Map with Walls properly, or using a certain algorithm ? I looked for a Maze Generation Algorithm but I don't have a very good feeling with this.

Thank you for your help and have a great day !


texts: Creating Animal Crossing style world rendering with Python

texts:
I've dabbled a bit with writing 3D rendering code in the past, although I'm interested in knowing if there is existing code (libraries) written for/with bindings to Python that might facilitate the creation of a world effect similar to this.

The world is a tile map wrapped to barrel basically with the actor in the center and objects in the horizon falling behind a threshold.

My hope here is to try and spare myself as much as I can to do with the actual perspective, rendering, culling, etc... and focus more on the game and networking logic itself.  However any advice on the subject as to what approaches might be best suited here are welcome!


texts: How can I implement "quality levels" for models and textures?

texts:
I'm preparing to build a 3D game without an engine and am wanting to know how I could implement graphic detail levels for my models.

To do this, are the models made in the highest quality level and then the artists remove polygons and texture detail for each model of a lower quality? Or does it work in some other way?


texts: How to perform game object smoothing in multiplayer games

texts:
We're developing an infrastructure to support multiplayer games for our game engine.

In simple terms, each client (player) engine sends some pieces of data regarding the relevant game objects at a given time interval.

On the receiving end, we step the incoming data to current time (to compensate for latency), followed by a smoothing step (which is the subject of this question).

I was wondering how smoothing should be performed ?

Currently the algorithm is similar to this:

Receive incoming state for an object (position, velocity, acceleration, rotation, custom data like visual properties, etc).
Calculate a diff between local object position and the position we have after previous prediction steps.
If diff doesn't exceed some threshold value, start a smoothing step:

Mark the object's CURRENT POSITION and the TARGET POSITION.
Linear interpolate between these values for 0.3 seconds.

I wonder if this scheme is any good, or if there is any other common implementation or algorithm that should be used?

(For example - should i only smooth out the position? or other values, such as speed, etc)

any help will be appreciated.


texts:
I want to make it so that when the player presses start, a side menu slides out and gives a player some option on one side of the screen, similar to Angry Birds or Pokemon. I'm not sure how to go about doing this but I think its somthing like putting an if statement in the render method?

render(){
     if(menuVisible){
     //draw menu?
     }
}

I'm fairly new to libgdx so I do not know how to use it to its fullest extent yet.


texts: How to create and populate a 2D Texture Arrays in DirectX11

texts:
I have generated a bunch of ID3D11ShaderResourceView that are a 2D textures that have a depth map screen shot for my lights shadows. I would like to take all of these textures and put them into a single 2D Texture Array.

I have seen examples of how to create a 2D Texture array like in this question here but I don't know how to copy the data to the newly created texture array.


texts: How can I use an object pool for optimization in AndEngine?

texts:
I have read up on a tutorial that allows you to reuse sprites that are re-added to the scene such as bullets from a gun or any other objects using an ObjectPool.

In my game i have a variation of sprites about 6 all together with different textures.

This is how the object pool is set up with its own class extending Java's GenericPool class

public class BulletPool extends GenericPool<BulletSprite> {
private TextureRegion mTextureRegion;

 public BulletPool(TextureRegion pTextureRegion) {
  if (pTextureRegion == null) {
 // Need to be able to create a Sprite so the Pool needs to have a TextureRegion
 throw new IllegalArgumentException("The texture region must not be NULL");
 }
 mTextureRegion = pTextureRegion;
}

/**
* Called when a Bullet is required but there isn't one in the pool
*/
@Override
protected BulletSprite onAllocatePoolItem() {
return new BulletSprite(mTextureRegion);
 }

/**
 * Called when a Bullet is sent to the pool
*/
@Override
protected void onHandleRecycleItem(final BulletSprite pBullet) {
pBullet.setIgnoreUpdate(true);
pBullet.setVisible(false);
}

  /**
  * Called just before a Bullet is returned to the caller, this is where you write  your initialize code
* i.e. set location, rotation, etc.
 */
   @Override
 protected void onHandleObtainItem(final BulletSprite pBullet) {
  pBullet.reset();
}
}

As you see here it takes a TextureRegion parameter. The only problem i am facing with this is that i need to have 6 different sprites recycled and reused in the ObjectPool. This ObjectPool is set up to only use one TextureRegion.

Any idea's or suggestions on how to do this?


texts: Instantiate player prefab using player data

texts:
When my scene loads, I want to add my prefab to it along with its components.

Here is what I mean:

scene loads
player gender is determined via playerprefs or playfab sdk
player prefab is loaded and displayed using said gender

The prefab would have a script components attached for the current data etc.

I might be approaching this wrong, but I want this to work with multiplayer in the future, so that's why I didn't just add the prefab directly to the hierarchy.

What is the correct way of doing this?


texts: Initial force to achieve orbital velocity

texts:
I'm attempting to get asteroid to orbit a black hole that is asserting gravity. Some parts currently work, like the black hole asserting gravity, attracting asteroids in and destroying them. And sometimes the asteroids, or smaller chunks end up in orbit around the black hole. But my desire is to have them orbiting at random distances at the start of the game.

Gravity

First please note, I am certain the math behind a lot of this is off, I'm hacking a concept at the moment and once enough pieces are in place I intent to come back through and apply proper scale and units to everything.
Next, it's written in JS but concepts should be fairly universal.

  function attractBodyToBlackHole(body) {
    var sx = body.position[0];
    var sy = body.position[1];
    var bx = blackHoleBody.position[0];
    var by = blackHoleBody.position[1];

    var angleToBody = Math.atan2(sx - bx, sy - by);
    var distanceToBody = Math.sqrt(Math.pow(sx - bx, 2) + Math.pow(sy - by, 2));

    var magGrav = 0.8 - (distanceToBody / 14);
    if(magGrav < 0) {
      magGrav = 0;
    }

    body.force[1] -= magGrav*Math.cos(angleToBody);
    body.force[0] -= magGrav*Math.sin(angleToBody);
  }

This function is applied to each object on p2's step, attracting it closer to the black hole.

Asteroids

function addAsteroid() {
  var bx = blackHoleBody.position[0];
  var by = blackHoleBody.position[1];

  var a = Math.random() * (Math.PI * 2);
  var dist = 3 + (Math.random() * 3);
  var x = dist * Math.cos(a);
  var y = dist * Math.sin(a);

  var vx = ?;
  var vy = ?;

  var asteroidBody = new p2.Body({
    mass:10,
    position:[x,y],
    velocity: [ vx, vy ]
  });
}

So my question is, how can I calculate velocity x/y (or force x/y ideally) to get these objects, based on their position, distance and the force of attraction from the black hole?


texts: How can I color/un color object that don't have renderer and material?

texts:
I have a simple object:

I want to create a highlight effect.

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

public class Map : MonoBehaviour
{
    public Camera mapCamera;
    public Text objectWasHit;

    private Camera[] cameras;
    private GameObject mouseOvered;

    // Use this for initialization
    void Start()
    {
        cameras = Camera.allCameras;

        GameObject levels = GameObject.Find("_Level");
        foreach (Transform child in levels.transform)
        {
            child.gameObject.AddComponent<Renderer>();
        }
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.M))
        {
            if (mapCamera.enabled == false)
            {
                foreach (Camera cam in cameras)
                {
                    cam.enabled = false;
                }
                mapCamera.enabled = true;
            }
            else
            {
                foreach (Camera cam in cameras)
                {
                    cam.enabled = true;
                }
                mapCamera.enabled = false;
            }
        }

        bool rcHit = false;
        Vector3 mouse = Input.mousePosition;
        Ray castPoint = mapCamera.ScreenPointToRay(mouse);
        RaycastHit hit;
        Debug.DrawRay(castPoint.origin, castPoint.direction * 1000, Color.magenta);
        if (Physics.Raycast(castPoint, out hit, 1000))
        {
            rcHit = true;
            if (mouseOvered != hit.collider.gameObject)
            {
                mouseOvered = hit.collider.gameObject;
            }
            objectWasHit.text = mouseOvered.name;
        }

        if (!rcHit && mouseOvered != null)
        {
            //do your thing to undo the material change
            mouseOvered = null;
        }
    }
}

First I'm not sure if white color is the right way for highlighting.
Second there is no startcolor since the object don't have any renderer or material at the first time. Then how can I make the highlight effect ?


texts:
I am trying to create pause screen for my game. The game is developed upon continuous scrolling background (top to bottom) with obstacles which are moving independently (left to right).

Below is the code:

  PauseScene.h

@interface PauseScene : CCNode {}
@property (nonatomic, retain) HelloWorldScene *mainScene;
//+ (PauseScene *)scene;
- (id) init;
@end

  PauseScene.m

@implementation PauseScene

- (id) init {
    if (self = [super init]) {
        // Adding RESUME and QUIT button and few others to make the whole Pause screen
    }
    return self;
}

// Called the method when Resume button is selected
- (void) Resume:(id) sender {
    //[[CCDirector sharedDirector] startAnimation];
    //[[CCDirector sharedDirector] resume];

    self.mainScene.userInteractionEnabled = YES;
    [self.mainScene removeChild: self];
    [self.mainScene StartGame]; // StartGame in MainScene contains the same code which commented out above, I will paste StartGame method later
}

// Quit method is called when the Quit button is pressed
- (void) Quit:(id) sender {
    //[[CCDirector sharedDirector] resume];
    //[[CCDirector sharedDirector] startAnimation];

    self.mainScene.userInteractionEnabled = YES;
    [self.mainScene removeChild: self];
    NSLog(@"Pre Reload", nil);
    //[self.mainScene scheduleOnce:@selector(ReloadGame) delay: 1.0f];
    [self.mainScene ReloadGame]; // Reload method contains the code commented above
}

@end

PauseScene is mere node class.

  StartGame and ReloadGame methods in MainScene file

- (void) StartGame {
    // Create and display HUD layer, like, scores, navigation buttons, etc.

    // Resuming the game
    //[[CCDirector sharedDirector] stopAnimation];
    [[CCDirector sharedDirector] resume];
    [[CCDirector sharedDirector] startAnimation];
}

- (void) ReloadGame {
    // Resume the game
    //[[CCDirector sharedDirector] stopAnimation];
    [[CCDirector sharedDirector] resume];
    [[CCDirector sharedDirector] startAnimation];

    [[CCDirector sharedDirector] replaceScene:[HelloWorldScene scene] withTransition:[CCTransition transitionFadeWithDuration:1.0f]];
}

  The pause button is displayed in HUD layer of MainScene, so, when the pause button is clicked, we will pause the game and display the PauseScene

- (void)onPauseClicked:(id)sender {
    // Code to display the pause node of this scene

    // Pause the game
    [[CCDirector sharedDirector] stopAnimation];
    [[CCDirector sharedDirector] pause];
}

When I comment out that stopAnimation and pause part the Pause and Resume works perfect. But when I implement any of these, at the time of quitGame, replaceScene is not working somehow. I think this is because game goes in pause mode but it is not working even if I call replaceScene using scheduler on delay of 5-10 seconds.

And if I don't use these stopAnimation and pause, some sprites which are given CCAction are not being paused and goes on even when my game is paused.

Your help is appreciated because I am using Cocos2d 3.0 and unable to find any proper help.


texts: Why is anti aliasing not being applied to my 2D objects in Unity?

texts:
I am drawing 2D objects in Unity.  Some of these objects are drawn using the standard sprite method that is built into Unity.  Others are computed as distance functions in a shader.

In both cases I can't get Unity to apply anti aliasing despite the setting being set.

Is there an extra step that I am missing that is required to get anti aliasing to work properly?

Would it be better to implement my own form of AA in a shader?


texts: Unity Non-shader method of combining two RGB Textures into a single RGBA Texture

texts:
I work in a broadcast environment that delivers video signals over SDI as Fill (RGB) and Key (A) signals. My SDI rendering method produces a Texture for each SDI input and applies it to a material. I'm currently using a shader to populate two texture slots on the material in order to use the Key signal as an alpha mask.

This works pretty well, but it would be ideal to produce a single RGBA Texture from the two, and feed the material with the single Texture. A shader would not produce a new Texture I could get a handle on, so I'm looking for an alternate solution. So far, my google-fu has only produced shader-based approaches, or use somewhat inefficient getPixel/setPixel loops. Is there any affordance for generating a new Texture and defining channel-based inputs?


texts: Changing the duration of motion state transitions in Animator Controller

texts:
Anyone around who is experienced with Unity animation states and the Animation Controller? I wonder is it possible in Unity to change the duration of time it takes between motion transitions in the Animator Controller?

To give an example let's say I have a human character that has an initial state of Grounded and in this state I have several motions like idle, running forward/backward and strafe left/right. When I now have the character in idle and I move left/right to go into strafe motion, the duration of the transition from idle to strafe left/right takes too long and I want it to be faster. I only want that transition between the motion states to be faster but not the actual animation itself. I think there should be a way to do this but I can't find any options for changing the duration between motions.

I'm aware that the duration between states can be changed by selecting a transition connection between states but what I'm talking about here are the motions inside a state.


texts:
I would like to have in-game grid lines similar to ones found in Unity editor. There is simple solution(first listing) based on shaders found on unity forums(on right image). However, that solution does not take in account antialiasing and drawn lines looks terrible even few units away from camera.

float4 frag(vertexOutput input) : COLOR {
    if (frac(input.worldPos.x / _GridSpacing) < _GridThickness
        || frac(input.worldPos.z / _GridSpacing) < _GridThickness) {
        return _GridColour;
    }
    else return _BaseColour;
}

In order to address that, I tried using typical fwidth/smoothstep combination:

float4 frag(vertexOutput input) : COLOR{
    float distX = min(frac(input.worldPos.x / _GridSpacing), 1.0 - frac(input.worldPos.x / _GridSpacing));
    float distZ = min(frac(input.worldPos.z / _GridSpacing), 1.0 - frac(input.worldPos.z / _GridSpacing));
    float dist = min(distX, distZ);
    float delta = fwidth(dist);
    float alpha = smoothstep(_GridThickness - delta, _GridThickness, dist);
    return lerp(_GridColour, _BaseColour, alpha);
}

Even though it has nice fade, the result is not quite near to perfect - not only the lines looks thinner(which can be somewhat fixed by increasing width), but also have various artifacts(e.g. in joints) and horizontal lines disappear much sooner than vertical ones. Detail image(anti aliased on left):

I am interested in shader solutions, since according to answer to similar question relying textures there in can be no solution with textures. In addition I would like grid lines fade at reasonable distance(when closely inspecting aliased overview image you can see where plane ends) rather than continuing to infinity.
Full current version(for testing purposes) with signed distance.


texts: Use an instance or a class for game resources (wood,iron,gold)

texts:
So I'm making a game where you can send ships to locations to sell or buy resources like wood, iron, gold, etc.

Now I was wondering how the resources should be created in de game. I came up with 2 options

Create a class for each resource:

public class ResourceBase {
    private int value;
    // other base properties
}

public class Gold : ResourceBase {
     public Gold {
         this.value = 40 // or whatever
     }
}

Create instances of a Resource class

public class Resource {
    string name;
    int value;

    public Resource(string name, int value) {
        this.name = name;
        this.value = value;
     }
 }

// later on...

Resource gold = new Resource("Gold",40);

With the second option it's possible to fill the game resources from a resources.json file, I kinda like that structure.

New ideas / design patterns / structures are always welcome!

EDIT: It's a little bit like Assassins Creed Black Flag's companion app. See the resource bar on the image below

EDIT 2: I've done some more research on the "load items/resources from JSON file" and found this blog: Power of JSON in Game Development - Items. It shows the best of option 1 and option 2. You're still able to add functionality to each resource :)


texts: Unity: How to take in multiple textures for Image Effect

texts:
I am trying to write a composite Image Effect shader with a script that works as such:

The camera texture is taken, and stored into two different variables. For examples sake they will be tex1 and tex2.
tex1 is modified by a shader.
Both tex1 and tex2 are taken into another shader, which composes them together. The result is stored as tex.
tex is printed to the screen.

I am not having an issue with the actual content of the shader manipulating the image-- But I do not know how to pass in both textures to one shader as needs to be done in step three. Thanks in advance if anyone can help.


texts: Preferred way of calculating run chances in Game of Cricket

texts:
For modelling a simple game of cricket, Considering a batsman has a single attribute rating. I can go about deciding run chances by weighted probabilities. Something like
    if batsman.rating <= 30:
        # map of run: probability
        probabilites = {0: 0.7, 1: 0.1, 2: 0.1, 3:0.5, 4:0.5, 6:0 }
    elif 30 <batsman.rating < 60
        probabilites = {0: 0.7, 1: 0.1, 2: 0.1, 3:0.5, 4:0.5, 6:0 }
    else:
        probabilites = {0: 0.7, 1: 0.1, 2: 0.1, 3:0.5, 4:0.5, 6:0 }

Now there are two challenges:

What if I want finer control over batsman.rating and probabilities? How do I manage to keep the sum of all probabilities equal to 1?
How to manage a second attribute to a batsman, let's say aggression. Which can lower chances of 0 and increase chances of 6?

Initially tried dealing to have finer control like below:
# map of batsman.rating: probability,
rating_to_zero_chances = {0: 0.9, 10: 0.7, 30: 0.5, 60: 0.3, 90: 0.1}
rating_to_one_chances = {0: 0.9, 10: 0.7, 30: 0.5, 60: 0.3, 90: 0.1}
chances_of_zero =  <some library>.interpolate(rating_to_zero_chances).yvalue(batsman.rating)
chances_of_one =  <some library>.interpolate(rating_to_one_chances).yvalue(batsman.rating)
.
.
.
#do this for each run

The problem with this is that I cannot interpolate the probabilities such that they are equal to 1, Since the slope of runs for the interpolated data are different
For challenge 2, Initially tried handling it by making a probability density function and shifting the mean of the curve if the aggression is more. This creates a problem when there is a 3rd or 4th attribute added (such as timing etc are added).
Currently am planning to deal with a single run with its chance, rather than having to sum their probabilities to 1 like below:
zero_chance = interpolate(rating_to_zero_chances).yvalue(batsman.rating)
zero_chance += aggression / 100  # assuming aggression on 1-100
is_zero_scored = binom([0,1], p=zero_chance).random()
if is_zero_scored:
    return 0
one_chance = interpolate(rating_to_one_chances).yvalue(batsman.rating)
one_chance += aggression / 90  # assuming aggression on 1-100
is_one_scored = binom([0,1], p=one_chance).random()
if is_one_scored:
   return 1
. # similarly for 2
.
.

Is there any neater way to do this? I am new to game development and had learned about probability distributions recently. Are there some theoretical/ practically established concepts I should be looking at?
How do game developers handle and balance different chances of an event?


texts: openGL managing images, VBOs and shaders

texts:
I'm working on a game where I use shaders with vertex attributes (so not immediate mode). I'm drawing lots of images and changing the width/height of the quads I use to draw them a lot. To optimize this it's probably a good idea to have one buffer but then one needs to update the complete buffer when one image changes (or only a part of the buffer using glBufferSubData...)

I was just wondering what kind of strategies you guys are using?


texts: Unity 2d - Vector3.Lerp Not Working as Expected

texts:
I have asked this question on other community but still get no response after a month, so I decided to ask it here.

I am trying to put player position to the middle of camera when it is reaching near the edge of the camera. It works correctly with the following code:

transform.position = playerPosition;

where playerPosition is the current position of the player.

But, when I try it with Vector3.Lerp or Vector3.MoveTowards, it won't reach the player's x position.

Here is how it looks when using Lerp or MoveTowards

https://www.youtube.com/watch?v=E50RpycrUxI

And here is when not using Lerp or MoveTowards

https://www.youtube.com/watch?v=ng_A4AfDQFE

The script:

 public GameObject player;
 private Vector3 playerPosition;
 private Vector3 pos;
 public float offsetSmoothness;
 void Update () {
     // player's position relative to camera
     pos = Camera.main.WorldToViewportPoint(player.transform.position);
     playerPosition = new Vector3(player.transform.position.x,
                                    transform.position.y,
                                    transform.position.z);
     // if player reach the edge of the camera do the following
     if (pos.x < 0.1 || pos.x > 0.9)
     {
          transform.position = Vector3.Lerp (transform.position,
                                                playerPosition,
                                                offsetSmoothness * Time.deltaTime);
          // transform.position = playerPosition;
     }
 }

Why Vector3.Lerp is not positioning the player to the center of the camera when this condition is used to execute it: if (pos.x < 0.1 || pos.x > 0.9) ?

And how to make it working as expected, which is making the Vector.Lerp position the player to the center of camera when the player close to the edge of the camera?


texts: How to make particle based fluid simulator like Algodoo?

texts:
I need to create swim mechanism which is interaction between object actuator and water.
I've play Algodoo and I can make simple swiming mechine. Which priciple to achieve this?
As far as I know it just round particle bouncing and update its momentum with viscositiy.
I just want what I need to know.


texts: Is there an easy and automatic way of converting a Windows XNA project into a Monotouch Monogame project?

texts:
I have just started with XNA development on Windows. But as I'm a fan of iOS I had to try porting my test code over to Monotouch on the Mac.
I used these instructions: http://www.facepuncher.com/blogs/10parameters/?p=42
But this is so much (manual) work!
And it really doesn't answer open topics like: why would I copy all the XNB files and in addition all the resources, like PNGs?

Is there maybe a tool that automatically converts a Windows XNA project into a Monotouch iOS project or at least creates the correct folder structure?


texts: Javascript and PHP for real-time multiplayer?

texts:
I'm wondering if combining Javascript clientside with PHP/mysql serverside is a good idea for HTML5 real-time multiplayer (small scale) browser games?

My technical knowledge is very limited, and even though I plan on learn node.js in the future, the learning curve is rather huge right now.

Since I'm already familiar with PHP I feel I would get it functioning much faster.

The scale I'm thinking is 2-8 players at the time. And trying to keep the client to server message count as low as possible.

The values I intend to store/handle are:

Player name and ID.
X and Y position.
Health.
Equipped items (maximum 8 slots, probably less).
Actions (walk, attack, use etc but only 1 action/player at a time).
Bullet X,Y coordinates and trajectory.
Guild/Clan name.
And some basic chat/mailing function.

My guess is even though it's not the best solution, but aslong as I keep the logic small, that this is completely doable.
Am I right?


texts:
I'm pretty new to Unity and trying to figure out what a good way of transferring objects in a grid to a dictionary would be.

For example, if i have a grid of 2D objects (squares) such as below

-------------
| 0 | 1 | 2 |
-------------
    | 3 | 4 |
    ---------
    | 5 |
    -----

I would expect my dictionary to be something like

myDict =
{
 {"0", 1},
 {"1", 0, 2, 3},
 {"2", 1, 4},
 {"3", 1, 4, 5},
 {"4", 2, 3},
 {"5", 3}
}

What i want to do is generate a random grid and then make a dictionary of neighbors of each grid piece that i can later use for other purposes.

Being new to Unity, i'm not really sure what a good way of this would be.


texts: NullReferenceException when using GetComponent

texts:
I have a script that is attached to all the NPCs in my game.

Here's what the variable declarations and Awake() function look like:

Dialogue dialogue;
TextMeshProUGUI UIText;
GameObject textBox;
Image portrait;
AudioSource audioSource;

private void Awake()
{
    audioSource = GameObject.Find("Audio Source").GetComponent<AudioSource>();
    UIText = GameObject.Find("Canvas").GetComponentInChildren<TextMeshProUGUI>();
    textBox = GameObject.Find("TextBox");
    portrait = GameObject.Find("Portrait").GetComponent<Image>();

    textBox.SetActive(false);
}

All of this works fine, until it gets to

portrait = GameObject.Find("Portrait").GetComponent<Image>();

For some reason, it throws a NullReferenceException on that line.

Two things about this confuse me:

The GetComponents above (for the audioSource and UIText) appear to work fine, despite being called for each of the NPCs. I'd assume it'd either work for all or none of them.
The portrait variable is used to show a portrait of the NPC when the player is talking to them, and even with the errors, one of the NPCs still has their portrait. It's like one NPC grabs the Image component, and none of the others can snag it or something...?

Anyway, very grateful for any wisdom y'all may provide, and happy to provide any other info that could lead to a resolution. Thanks! Hope your new year is going well!

EDIT: There is a Portrait GameObject in my scene under the Canvas, with an Image component attached to it. This I can confirm.


texts:
I'm making an isometric game using a Tiled map with libgdx. As I want my character to be rendered before or after the tiles depending his positions, I create an ArrayList<Renderable> and I add in it my character and the tiles.

    TiledMapTileLayer midlayer = (TiledMapTileLayer) map.getLayers().get(4); //The layer containing my tiles.
    int width = midlayer.getWidth();
    int height = midlayer.getHeight();
    ArrayList<Renderable> renderables = new ArrayList<Renderable>();
    renderables.add(character); //Adding the character in the list;

    //We add to the list every midlayer's tile, so we can later sort
    for (int i=0;i<width;i++) {
        for (int j=0;j<height;j++) {
            if (midlayer.getCell(i, j)!=null) { //As the cell can or can't exist in that position.
                renderables.add(new RenderableTile(midlayer.getCell(i, j).getTile().getTextureRegion(),i,j));
            }
        }

RenderableTile is a class I created containing a x and y position and the TextureRegion.

public class RenderableTile implements Renderable, Comparable<Renderable> {

private int x;
private int y;
private TextureRegion texture;

public RenderableTile(TextureRegion text, int x, int y) {
    this.x = x;
    this.y = y;
    this.texture = texture;
}

@Override
public void render(SpriteBatch batch, BitmapFont font) {
    batch.begin();
    int rX = Translations.TransX(x, y);  //Transformation orthogonal position to isometric rendering
    int rY = Translations.TransY(x, y)-15;
    batch.draw(text, rX, rY);
    batch.end();
}

The sorting works perfectly, and the ArrayList seems containing the right tiles. But when I render I get this:

Instead of something like this:

This is really akward, when I try to render a single tile in a specific point it works normally.

Maybe there is an alternative solution?


texts: I would like to procedurally generate planets, but I don't know how to wrap a heightmap around a sphere. I already know how to generate plane heightmaps, but not how to generate spherical ones. Can someone push me in the right direction?


texts: SharpDX - Character Skinning Different in Windows Phone 8.1 Emulator and Real Device

texts:
I have an engine written using SharpDX, that can load a character mesh and animation stored in a FBX file, then it renders a scene and animates a character. It is written as an Universal Windows Store App, so it runs on Windows 8.1 desktop, tablets and Windows Phone 8.1 devices. The Windows 8.1 part of the app works fine. It was a bit tricky to rewrite the code for the Windows Phone 8.1 part, because Windows Phone 8.1 only supports DirectX feature level 9_3, so I had to change some unsupported DXGI formats, compile the shaders with 4_0_level_9_3 shader profiles instread of 5_0 and reduce some attributes in order to fit 256 register limit for 4_0_level_9_3.

Now, I have this problem. When I try to run the engine in Windows Phone 8.1 Emulator, it runs fine. The character shows and animated fine. There is a tiny man, who waves his hands. See this screen:

But When I try to run the exact same code in the real Windows Phone 8.1 device, it is not doing the same. The character shows, but it is not standing and waving, instead it is in TPose and floating in space in a rotation-like movement.

It is very confusing, because it is the exact same code, only I try to run it in an emulator and real device. What could be different for emulator and real device, that it is not rendering the same thing - the thing that it should?

I've been stuck at this for over a week and I am kind of desperate now.. so thank you for any advices, comments and tips.. anything.


texts:
Am making an android game with unity and i want to add an in-game purchase feature, i looked around and all the suggestion lead to non-free plugins (mainly prime31 plugin) but in the current moment i cannot afford to invest in some of these plugins, does anyone of you have a free solution for this "problem" ?

thank you


texts: Libgdx FillViewport vs FillCamera unproject issue

texts:
I have no idea why this happens. But I have the following scenario:

Rendering a tiled map works fine.
Rendering the sprites texture region works fine.
Rendering the shapes of the sprites using a ShapeRenderer works fine
Unprojecting from the fill viewport works fine.

What doesn't work:

The box 2d lights when the camera is at the top or at the bottom of the map.
(at the bottom they appear a little lower than what they should, and at the bottom, a little higher)
Unprojecting from the fill camera.

Both issues do not occur when the screen resolution is 1.5. Which is the screen resolution that I use to create the fill viewport.

This is the code that I use to create the camera and the viewport.

fillCamera = new OrthographicCamera();
fillViewport = new FillViewport(Constants.CAMERA_PIXEL_WIDTH, Constants.CAMERA_PIXEL_HEIGHT, fillCamera);
fillCamera.position.set(Constants.CAMERA_HALF_PIXEL_WIDTH, Constants.CAMERA_HALF_PIXEL_HEIGHT, 0);
fillCamera.update();

public static final float CAMERA_PIXEL_WIDTH = 375F;
public static final float CAMERA_PIXEL_HEIGHT = 250F;
public static final float CAMERA_HALF_PIXEL_WIDTH = CAMERA_PIXEL_WIDTH / 2;
public static final float CAMERA_HALF_PIXEL_HEIGHT = CAMERA_PIXEL_HEIGHT / 2;

What could the issue be?


texts: I have an array of lights that I need to sample from randomly, but deterministically so that all the lights are sampled. Currently I use random numbers to pick a light, and then put processed lights into another list, but I'm wondering if there is a way to use something like a hammersly or halton sequence to do this instead. A biased solution would be ok.


texts: Gradle generated LibGDX project does not work in NetBeans

texts:
I have to do rework of Worms (game) and I've chosen LibGDX. So, I've installed Gradle and generated a new project in LibGDX app - as they have in the documentation. But when I'm trying to load it as a project in NetBeans, it does not work. NetBeans sees it as a pure folder, not a project folder. I've also tried to manually create a project and paste there just the main that was generated and as expected, I've got errors with the imports (it does not know those imports).

What do I have to do? Thanks for any advices.


texts: Is there a global "low resolution" filter for OpenGL?

texts:
I'm trying to learn a little about OpenGL, so I'm making a simple 2D game (with OpenTK), and so far it's coming along well. I thought it would be fun to give it that, for lack of a better word, retropixelated look of games from the early nineties. I figured it would be an easy thing to do -- simply draw everything at half its normal size and scale up with no anti-aliasing.

But I can't find any resources on how to do this. I can set the min/mag filters of my textures to nearest and that works fine for my sprites, but I'm using lots of primitives and I'd like the effect to apply to them as well.

The one idea I had was to draw everything at half size, then somehow copy the render buffer to a texture, then render that texture full-size, but I don't know how to do that, and it seems like there must be a better way. Can anyone help me out?


texts: Unity AudioSource.PlayClipAtPoint - controlling attenuation

texts:
New developer here, looking to do some raycasting and controlling audio positioning in 3D space based on the raycasts interactions with other objects.
I've got the raycast 'casting' and able to report back where it collides other objects and managed to get audio to play back at that raycast point using AudioSource.PlayClipAtPoint()

However, PlayClipAtPoint doesn't allow me to change the audio 3d attenuation settings as a one shot audio object is generated and then removed immediately and I can't find any parameters to control this new object apart from a volume 0-1 float value.

I came across this post by Aldonaletto:

function PlayClipAt(clip: AudioClip, pos: Vector3): AudioSource; {
   var tempGO = GameObject("TempAudio"); // create the temp object
   tempGO.transform.position = pos; // set its position
   var aSource = tempGO.AddComponent(AudioSource); // add an audio source
   aSource.clip = clip; // define the clip
   // set other aSource properties here, if desired
   aSource.Play(); // start the sound
   Destroy(tempGO, clip.length); // destroy object after clip duration
   return aSource; // return the AudioSource reference
 }

But can't seem to get the local function to work in Unity as it complains about not using C# version 7 or above. If I upgrade the C# version in visual studio I get compiler errors on Unity's side.

Little bit stuck, would appreciate some advice! Some code below, just not sure what to put into the result of the if statement to get this to work.

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

public class raycasting : MonoBehaviour
{
    public float raycastlength = 3;
    public AudioClip playthis;
    public float ER_Volume = 1F;

    // Use this for initialization
    void Start()
    {
        //Debug.Log("I'm a sphere, yo!");
    }

    // Update is called once per frame
    void Update()
    {
        RaycastHit hit;
        Ray forwardray = new Ray(transform.position, Vector3.forward);

        //draw the raycast in scene view
        Debug.DrawRay(transform.position, Vector3.forward * raycastlength, Color.white);

        if (Input.GetMouseButtonDown(0))
        {
            //Debug.Log("We pressed the fire button!");
            if (Physics.Raycast(forwardray, out hit, raycastlength))
            {
                if (hit.collider.tag == "evil")
                {
                    Debug.Log("Raycast Hit!");
                    Debug.Log("Distance to object:" + hit.distance);
                    //Debug.Log("Object hit point:" + hit.point);

                    //play a sound using playclipatpoint, but this doesn't allow us to change attenuation settings
                    AudioSource.PlayClipAtPoint(playthis, hit.point, ER_Volume);
                }
            }
        }
    }
}


texts: Do professional 3D modelers use human bases?

texts:
I tried to find an answer on google and didn't get much.
I wanna know, do professional 3D modelers (Specifically in the video game industry) work off generic base human models to make their own? Or do they make their entire body and face models from scratch?

Bases like these for example:


texts: How to make animated buttons in a menu with Cocos2d?

texts:
How do I make animated menus with cocos2d, I just want to animate the buttons and not the entire scene. Effects I look for is flipping buttons (like the back of the button is the next menu), buttons that retract once selected and re appear with new button.

Basically what I ask for is cool effects between menu transitions.


texts: How to get max viewable X-Value in Viewport

texts:
How can I calculate or get the farthest X-Value of a Viewport during gameplay?

Say a model is moving in from the right-hand side (beyond Viewport) and starting from a certain X-Value it is visible on the viewport. I'd like get that certain X-Value.

But the more I zoom out (Z-Axis) the greater the farthest visible X gets (Max X). How could I approach this?


texts: Fitting tilemap to any screen resolution

texts:
My game is a 2D Single-Screen (i.e. non-scrolling) platformer for Android, but the question here doesn't require a code-specific answer.

Basically it's easier for me to show the problem using a graphic, which I've attached below.

My game screen consists of a grid of 25 x 12 tiles.  I am already scaling my viewport so that my ratio stays consistent (by introducing letterboxing / pillarboxing when required) - this works correctly.  I am also scaling my tile sizes by the current viewport dimensions so they appear the same size relative to the current display.

However, clearly, dividing my screen width by 25 to get the tile size will produce a slightly different gap at the right hand side.  (if the starting position is 0 (left edge)).

I get this problem also vertically but this isn't so much of an issue as I can just keep the gap - see the first 2 graphics below.

So, horizontally, what would be the best method to 'cover' this gap up.

I know I can make it more 'symmetrical' by moving all the tiles to the right by 1/2 of the gap width.  But then I would just have smaller gaps on both sides.

Another solution would be to simply draw an extra tile to the right (make my grid 26x12) but this would mean that I would be drawing extra tiles that weren't needed on some screen resolutions (where screen width divided by 25 didn't produce a noticeable remainder / gap).  So I'm all out of ideas and really have no clue how to proceed.  How are these issues dealt with?

I know questions regarding the scaling of graphics are in abundance here on GDS but they do not answer this question.  This question is specific to fitting a tile-grid onto multiple screens in an aesthetically pleasing way.

Help would be appreciated.


texts: How to calculate the direction a ball must bounce

texts: I have a tile engine I have made. I can detect collision between the ball(the player) and the tiles. When a collision is detected all the colliding tiles are stored inside a list. My question now is, how do I figure how should I change the velocity of the ball using the collided tiles? I tried to figure out a way to calculate the direction the ball is hitting but I am lost.


texts:
How can I make the borders (stationary / non moving) of my 2d Unity game glow?
I need a method that is not so expensive. I've read that post processing is very expensive, but I quite liked adding bloom to my scene. It was pretty straight forward.
But now I'm reading that one shouldn't use it, it's expensive, not so good etc.


texts:
Does anyone know of any good examples of 3D being faked in 2D (not necessarily code, but games I could look up)? The player has the perspective that they are going 'into' the screen and things are coming out at them. At the moment, I'm simply scaling the 2D enemies to give the illusion that they're coming closer, but it still feels quite flat. Are there any tips on how to give it more of a 3D illusion without actually using a 3D engine?

Edit: Just came across the term 'Mode7' and this video which shows pretty much what I'm trying to figure out. (especially the games at 0:13 and 1:03). What's a good way of implementing something like this?


texts:
I am trying to share this across multiple effect files:

matrix worldMatrix : register(vs_4_0, b0);

If I set this from one effect file, will it effect every effect file which has the same type of variable assigned to that specific register?
What is the difference between this and the cbuffer struct?


texts: Best visual way to build a "near isometric" 2D view

texts:
I'm working hard in a 2D platform game, as far as I got is a standard 2D view (only x and y are visible)

But I want to change the perspective so I can see the floor also.

But the MapBuilder I developed works perfectly based on TILES (so my 2D works very well)

I wanna know the easiest way to add the ground on top of the floor without switching to full 3D with rotationed Rectangles.

The best I tought is to create a "magic" rectangle on top of my ordinary floor to make this fake perspective. But this still lead me to problems on multi-floors.


texts: How can I more efficiently paint grass onto a large terrain object in Unity?

texts:
I'm trying to paint a grass onto a large terrain and I want it to cover the entire terrain. Since the brush size can't go past 100 it would seem that I'm stuck painting the entire thing with a small brush relative to the terrain size.

How can I more efficiently paint grass onto a large terrain object?


texts:
I am looking ways to improve the efficiency of my draw method in XNA/Monogame and understand how things work. I have just a group of 4 models (bricks), (red, green, blue, yellow) I am drawing multiple times on the screen (100-120 total models, so drawing each model 25-30 times) on the current frame.

Here is how i am drawing 1 of the 4 types of models (the red ones) right now:

Matrix[] transforms = new Matrix[Brick.Red.Bones.Count];
Brick.Red.CopyAbsoluteBoneTransformsTo(transforms);
ModelMesh mesh = Brick.Red.Meshes[0];
BasicEffect effect = (BasicEffect)mesh.Effects[0];
effect.EnableDefaultLighting();
effect.View = Matrix.CreateLookAt(cameraPosition, Vector3.Zero, Vector3.Up);
effect.Projection = Matrix.CreatePerspectiveFieldOfView(MathHelper.ToRadians(45.0f),
   aspectRatio, 1.0f, 10000.0f);
foreach (Brick brick in Bricks)
{
    int i = brick.Index / Columns;
    int j = brick.Index % Columns;
    modelPosition = new Vector3(-HalfWidth + j * BrickWidth,
        HalfHeight - i * BrickHeight, 0.0f);
    effect.World = transforms[mesh.ParentBone.Index] * Matrix.CreateScale(scale) *
        Matrix.CreateTranslation(modelPosition);
    mesh.Draw();
}

This code seems to not perform as well as I expected (since its just 4 models drawn many times on different locations) when I timed it with a StopWatch. Is there something silly in my code that could be done better and i'm missing it ? I can't tell because so far I have only worked with sprites and 2D.

Edit: From other codes I saw that they used effect.Parameters["World"].SetValue(...); to set the BasicEffect values, but that gave me a null exception, and I am not sure what is the difference of that function since in my mind it seems the same with effect.World = ...;


texts: I'm trying to create a font atlas with SDL_TTF. My idea was to create an SDL_Surface for every character using TTF_RenderGlyph_Blended() and use TTF_GlyphMetrics() to get glyph metrics so that I can position the surface relative to a baseline. I'm struggling with a correct positioning of a glyph. It looks like SDL_TTF creates a surface with height which is at least the height of the font and width which is at least advance of a glyph, so the surface is bigger than just the glyph. How do I extract glyph's rectangle from the created surface? How do I position the glyph correctly relative to the base line on the screen? I thought y position of the glyph it should be baselineY - maxy (where maxy is from TTF_GlyphMetrics), but that places glyph too high above the base line.


texts: Game Maker: Studio - Make objects avoid other instances of same object with A* pathfinding

texts:
I have a game where there are multiple enemies who must chase a single player.  I have pathfinding set up using the GML A* pathfinding with mp_grid and a path.  However, these enemies can walk on top of each other when seeking the player.  To fix this, I also told the path to ignore enemies as well with mp_grid_add_instances, but then they stop moving altogether because they see themselves as obstacles, thus trapping themselves within a bounding box.  Is there a way I can add "all other enemies BUT self" with mp_grid_add_instances?

Here's my grid creation code (in a CONTROLS class for initializing variables):

global.zombie_ai_grid = mp_grid_create(0, 0, room_width / 50, (room_height - sp_dashboard.sprite_height) / 50, 50, 50);
mp_grid_add_instances(global.zombie_ai_grid, obj_obstacle, false);

This is my path initialization code (in Zombie class):

path = path_add();
alarm[0] = 5;

This is my path creation code in Alarm 0 (path updates every 2 seconds):

mp_grid_path(global.zombie_ai_grid, path, x, y, nearest.x, nearest.y, true);
path_set_kind(path, 1);
path_set_precision(path, 8);

path_end();
path_start(path, MAX_SPEED, 0, true);

alarm[0] = room_speed * 2;


texts:
I'm trying to create a flexible tile-based game engine to make all sorts of non-realtime puzzle games, just as Bejeweled, Civilization, Sokoban, and so on.

The first approach I had was to have a 2D array of Tile objects, and then have classes inheriting from Tile that represented the game objects. Unfortunately that way I couldn't stack more game elements on the same Tile without having a 3D array.

Then I did something different: I still had the 2D array of Tile objects, but every Tile object contained a List where I put and different entities. This worked fine until 20 minutes ago, when I realized that it's too expensive to do many things, look at this example:

I have a Wall entity. Every update I have to check the 8 adjacent Tiles, then check all of the entities in the Tile's List, check if any of those entities is a Wall, then finally draw the correct sprite. (This is done to draw walls that are next to each other seamlessly)

The only solution I see now is having a 3D array, with many layers, that could suit every situation. But that way I can't stack two entities that share the same layer on the same tile. Whenever I want to do that I have to create a new layer.

Is there a better solution? What would you do?


texts: Blender / Unity - Which one do I paint on? low poly or high poly

texts:
I created two versions of my object. One high poly and one low poly. I sculpted the high poly one and plan on baking a normal map so that my low poly one can have more detail.

My question is, once all the sculpting is done and I get everything ready to create a normal map. Which object do I begin painting on the high poly (sculpted) or low poly(non sculpted)?


texts:
I hear in many game reviews, how gamers complain about the controls of a game, when they hate it, or how they praise them when they work right. This expression comes up: "Tight controls".

It seems like when it comes to games, "controls" is a critic point for a game to succeed, so I was wondering if we could have a discussion about what exactly are tight controls.

What makes "controls" feel good?
What kind of things do gamers hate when it comes to "controls"?
What examples could be given?


texts: How can I keep chase camera behind player when player rotates?

texts:
I have implemented a follow camera in Unity 3D. However, if the player object rotates, the camera does not rotate with it. To fix this I used RotateAround as follows:

playerRotation = CastPositive(player.EulerAngles.y) //guarantees 0-360
cameraRotation = CastPositive(transform.EulerAngles.y)
difference = playerRotation - cameraRotation
transform.RotateAround(player.position, Vector3.up, difference * time.deltaTime)

This works in general. However at some point the difference snaps from -50 to 210. When this happens, the camera swings in the opposite direction all the way round the player object, instead of continuing on its orbit.

How can I avoid this value jump?

I've tried clamping the various values to no avail, but maybe I've missed something?
Quaternions?


texts:
I'm messing around with Unity 2017's post processing tools while making a 2D game that benefits from the parallaxing effect using a perspective camera.
Please note that the game is mostly made using sprites.

Now, I have a playerGround, a backGround and a foreGround. I wish to blur the background and foreground only but not the playerground.
I'd like to know how to do this as playing with the focal length didn't do anything, everything receives the same blur amount regardless of the distance from camera.


texts: computer language like arduino language for visualization or game development

texts: Is there a language similar to Arduino language (c++ language with fewer functions) for software visualization?


texts:
I want to create an effect similar to the following in XNA / MonoGame:

There's a background and a semi-transparent shadow consisting of several objects (two circles in this example). However, the shadows merge without darkening their overlapping region!

My current approach was the following:

Render all required shadow objects using a DepthStencilState and a AlphaTestEffect.
Then, render a single-pixel semitransparent black texture over the entire screen using another DepthStencilState to display shadows.

However, it didn't work as expected: the shadow objects get rendered to the target, and the stencil buffer seems unaffected.

Here's what I want:

A way to render a sprite to Stencil Buffer only, with absolutely no visible modifications to the target.
A way to render a semitransparent texture using the stencil buffer.

Stencil states and effects are initialized as follows:

StencilCreator = new DepthStencilState
{
    StencilEnable = true,
    StencilFunction = CompareFunction.Always,
    StencilPass = StencilOperation.Replace,
    ReferenceStencil = 1
};

StencilRenderer = new DepthStencilState
{
    StencilEnable = true,
    StencilFunction = CompareFunction.Equal,
    ReferenceStencil = 1,
    StencilPass = StencilOperation.Keep
};

var projection = Matrix.CreateOrthographicOffCenter(0, GraphicsDevice.Viewport.Width, GraphicsDevice.Viewport.Height, 0, 0, 1);
var halfPixel = Matrix.CreateTranslation(-0.5f, -0.5f, 0);

AlphaEffect = new AlphaTestEffect(GraphicsDevice)
{
    DiffuseColor = Color.White.ToVector3(),
    AlphaFunction = CompareFunction.Greater,
    ReferenceAlpha = 0,
    World = Matrix.Identity,
    View = Matrix.Identity,
    Projection = halfPixel * projection
};

MaskingTexture = new Texture2D(GameEngine.GraphicsDevice, 1, 1);
MaskingTexture.SetData(new[] { new Color(0f, 0f, 0f, 0.3f) });

What am I doing wrong?


texts: How do I create a sky box with OpenGL ES 2.0?

texts:
Can you give me hint to any good sky box example in OpenGL ES 2.0? I have found only OpenGL and does not work for me.
I am doing it this way:
Initialization:

glUseProgram(m_programSkyBox.Program);
glGenBuffers(1, &skyBoxVertexBuffer);
glBindBuffer(GL_ARRAY_BUFFER, skyBoxVertexBuffer);

float vertices[24] = {
    -1.0, -1.0,  1.0,
    1.0, -1.0,  1.0,
    -1.0,  1.0,  1.0,
    1.0,  1.0,  1.0,
    -1.0, -1.0, -1.0,
    1.0, -1.0, -1.0,
    -1.0,  1.0, -1.0,
    1.0,  1.0, -1.0,
};

glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);

glGenBuffers(1, &skyBoxIndexBuffer);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, skyBoxIndexBuffer);

GLubyte indices[14] = {0, 1, 2, 3, 7, 1, 5, 4, 7, 6, 2, 4, 0, 1};
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW);

Drawing the skybox:

glClearColor(0.5f, 0.5f, 0.5f, 1);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glUseProgram(m_programSkyBox.Program);

glDisable(GL_DEPTH_TEST);   // skybox should be drawn behind anything else
glBindTexture(GL_TEXTURE_CUBE_MAP, m_textures.Cubemap);

glBindBuffer(GL_ARRAY_BUFFER, skyBoxVertexBuffer);
glVertexAttribPointer(m_programSkyBox.Attributes.Position, 3, GL_FLOAT, GL_FALSE, 0, (void*)0);
glEnableVertexAttribArray(m_programSkyBox.Attributes.Position);
glBindBuffer(GL_ARRAY_BUFFER, 0);

glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, skyBoxIndexBuffer);
glDrawElements(GL_TRIANGLE_STRIP, 14, GL_UNSIGNED_BYTE, 0);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
glEnable(GL_DEPTH_TEST);

Texture loading is working. Shader is correctly compiled and looks like this:
Vertex shader:

attribute vec4 position;
varying mediump vec3 texCoord;
void main() {
   texCoord.xyz = position.xyz;
}

Fragment shader:

uniform samplerCube Sampler;

varying mediump vec3 texCoord;

 void main() {
     mediump vec3 cube = vec3(textureCube(Sampler, texCoord.xyz));
     gl_FragColor = vec4(cube, 1.0);
 }

But I can't get the cube visible. Am I doing anything wrong?


texts: How to get an affect for balloon bursting in XNA?

texts:
I am a noob in XNA. I want to create an effect which shows a balloon bursting?

Any pointers would be highly appreciated.


texts: Keep world changes in sync in client/server architecture

texts:
Imagine having a big room (4000w x 4000h) which contains players and items (world objects). The room is spatially partitioned in a 10 x 10 grid for collision detection and changes in the viewport of the player.

Green rectangle: Item
Red rectangle: Player viewport

At the moment, on the server, every player contains a list of all world objects in his current viewport. When the player changes his position, new items are found in the viewport, compared with his current list of visible objects and the changes are send to the client. His current visible list is updated with the new found objects

HashSet<WorldObject> changes = new HashSet<>(foundObjects);
changes.removeAll(player.getVisibleObjects());

The client maintains a list of all entities that it has seen, renders them in the world and waits for new input.

Now my problem arise when another player picks up an item, it notifies the surrounding players, update the local list of items accordingly and stops rendering the item. This works fine. But players outside the viewport are not notified about these changes, so once they are in the grid, they will still see the item being rendered.

How are these kind of problems commonly solved? Is my approach good?


texts:
There are plenty of articles about open world game design and writing plots. But have you guys come across articles or blog entries about designing an engaging plot in an open world game? What i mean by this? In TES:Morrowind you're introduced to mechanics and are given the "main quest" within the first 5 minutes and then you're free to go, learn, kill, do whatever you want. I've spent hundreds of hours playing the game, but i have never got to doing the "main quest" and i'm sure alot of people are in the same situation, be it Morrowind, Oblivion or Skyrim. Maybe it's the power of TES games and a true testiment to how great RPGs they are, however for me, thinking as a designer, it seems like a massive design failure. Maybe it's the fact that there's no actual threat that needs to be dealt with, maybe it's that, amongs all the well designed and interesting quest within the game, the "main quest" just doesn't seem so interesting.

I've got a game idea in the back of my head, i want to create an action platformer, but the "level selection" would be open world style "dunegons" like you find in MMOs. This is a vague and undeveloped idea, so don't focus on it, i didn't give this design much thought, however an issue arose, i can't figure out, in general, how to make the player care about the open world aspect (f.e. dealing with roaming, pillaging parties, doing a gauntlet run to get some special armor, clearing a water source from enemies, etc.) while "forcing him" to finish the game, carrot-on-a-stick kind of way. There are "crazy" people who will go search everywhere between cutscenes in FF games, but i'm aiming at the general audience. I want to create  a subtle system for guiding people throughout the game to a goal, while giving them an option of gaining power any way they want. This may aswell be impossible, but it doesn't hurt to ask.

I'm looking for articles or musings on this matter. Not solutions (since there's no design document, no direct solutions matter at this point), just thoughts from other people, probably with other games as a reference.


texts: How do I run a headless Unity server in a Windows Docker (without GPU)?

texts:
I am trying to run a headless Unity server on a Windows Docker.
On Linux, there is Xvfb, but I don't know how I could get similar results on Windows.
How would I do that?


texts: In Unreal why is it safe to access a UTexture2D's properties from the render thread despite the documentation stating this is not allowed?

texts:
I've been trying to implement something that will update textures on the render thread from a background thread. And from what I've read of the unreal engine documentation you should never access a descendant of UObject from the render thread since the game thread could deallocate it at any time. Epic describes an example of this situation in their documentation

  Here is a simple example of a race condition / threading bug:

/** FStaticMeshSceneProxy Actor is called on the game thread when a component is registered to the scene. */
FStaticMeshSceneProxy::FStaticMeshSceneProxy(UStaticMeshComponent* InComponent):
    FPrimitiveSceneProxy(...),
    Owner(InComponent->GetOwner()) <======== Note: AActor pointer is cached
    ...

   /** DrawDynamicElements is called on the rendering thread when the renderer is doing a pass over the scene. */
    void FStaticMeshSceneProxy::DrawDynamicElements(...)
    {
        if (Owner->AnyProperty) <========== Race condition!  The game thread owns all AActor / UObject state,
            // and may be writing to it at any time.  The UObject may even have been garbage collected, causing a crash.
            // This could have been done safely by mirroring the value of AnyProperty in this proxy.
    }

However the actual code they write violates this rule all of the time. There are numerous examples in FTexture2DResource accessing its Owner property which is a UTexture2D* from the render thread. Just one is

/**
 * Called when the resource is initialized. This is only called by the rendering thread.
 */
void FTexture2DResource::InitRHI()
{
  FTexture2DScopedDebugInfo ScopedDebugInfo(Owner);
  INC_DWORD_STAT_BY( STAT_TextureMemory, TextureSize );
  INC_DWORD_STAT_FNAME_BY( LODGroupStatName, TextureSize );

#if STATS
  if (Owner->LODGroup == TEXTUREGROUP_UI) <========== Accessing LODGroup from owner should be unsafe
    {
        GUITextureMemory += TextureSize;
    }
...
}

This seems to directly contradict the documentation given by Epic even though this is commonplace in their source code.

From the source it doesn't look like FTexture2DResource or any of its ancestors perform any smart pointer magic or add the UTexture2D object to the root set to prevent GC and even then race conditions would still apply.

I'll probably end up answering this one myself, but it would be great if someone happened to know this.


texts: How can I highlight words in a word search puzzle?

texts:
For days I am struggling to implement the highlighting functionality in game as there is not much tutorial also for this. I did how ever make the cell of the grid change the material color but it looks ugly that's why I prefer to choose this method (see pic).

How can I implement a highlighting method that will work the same on link.

My try:

 private bool first_sel = false;
    private void Update() {
        if (Input.GetMouseButton(0)) {
            ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            if (Physics.Raycast(ray, out pressed)) {
                if (pressed.transform.tag == "cell") {
                    if (!first_sel) {
                        GameObject sel = Instantiate(sel_cell, new Vector3(pressed.transform.position.x,
                            pressed.transform.position.y, pressed.transform.position.z - 0.55f), Quaternion.identity);
                    }

                }
            }
        }


texts:
I have a project where I have 1 character (playable) and 2 NPC's (AI).

The NPC's are programmed to meet 2 target points.

Below is an image to facilitate understanding:

As you can see, this green path is the full extent of the terrain that both my character and NPC's can walk through.

I know that in order for my character to traverse the full extent of the terrain, it is only necessary to add a nav mesh bound that covers the entire length of the terrain, but doing so the NPC's would cut their path:

CODE NPC'S:

I've made the target variable editable, so I can choose the target in the level editor.

I would like to know the simplest way to make the playable character go all over the terrain and the NPC's to follow the green route.


texts: Character on Character fighting animations

texts:
sorry about the vague title, but these couple of videos/images might explain my situation a bit better:

https://www.youtube.com/watch?v=MG1mNyjNuXk (Wolfenstein the Old Blood)
https://www.youtube.com/watch?v=NVmsucYKlvo (Mad Max the Game)
https://www.youtube.com/watch?v=XYWQ-UzTpZ8 (at 0:49 seconds, Credits go to: Ranon Sarono AKA Hyper)

I am basically wondering how you would animate the 2 characters if 1 of them knifed the other one, do they both have their separate animations? or do they just take the animation file?


texts: LibGDX - Getting Tile Map Layers Problem

texts:
While following a tutorial with LibGDX, I am working with tile maps.

This is the method that I'm using:

tilemap.getLayers().get("Collision Layer");

or

tilemap.getLayers().get(1); //1 is the second layer, the collision layer

The problem is, is that when I try to get a certain layer from the tile map, it return a null pointer error like so:

  Exception in thread "LWJGL Application" java.lang.NullPointerException at com.mytut.game.Player.Init(Player.java:25)
      at com.mytut.game.MyTutGame.create(MyTutGame.java:70)
      at com.badlogic.gdx.backends.lwjgl.LwjglApplication.mainLoop(LwjglApplication.java:147)
      at com.badlogic.gdx.backends.lwjgl.LwjglApplication$1.run(LwjglApplication.java:124)

I have tried various ways of getting the layer but none of them seem to work.

Here's an image of my tile map in the Tiled map editor:


texts: Whenever I try to draw from the tile palette, this is the result. why does this happen? I have tried messing around with the palette, how the sprite editor has sliced the tiles and played around with the anchors and cell sizes, but to no avail. I found a few threads about offset tiles in the tile map, but it doesn't help at all. Any leads as to why this happens?


texts: LibGDX: Shader files in assets - Access is Denied

texts:
I stored the glsl files in android -> assets -> shaders directory, but when I run the app, an error is displayed:

Error:Gradle: Execution failed for task ':android:mergeDebugAssets'.
Error: java.io.FileNotFoundException: ...android\assets\shaders (Access is denied)

But the problem goes away if I put those files in assets root folder. Can I not store shader files in asset subdirectories? Using Gdx v1.9.3.

EDIT: The issue is not there when running on Desktop, but only on Android. Didn't check others.

UPDATE: Apparently the issue got resolved today. I didn't make any changes but it's working now!


texts: How to check if gun may shoot again (because animation has stopped playing)?

texts:
When the user presses the fire button, I set a trigger:
_animator.SetTrigger("HG_Shoot");

This trigger causes a "pistol shoot" animation to be played.
The gun should only be able to shoot again as soon as the shoot animation has finished.
I could check at each Update() if that certain animation is still being played like this:
 bool isAnimationStatePlaying(Animator anim, int animLayer, string stateName)
 {
     if (anim.GetCurrentAnimatorStateInfo(animLayer).IsName(stateName) &&
             anim.GetCurrentAnimatorStateInfo(animLayer).normalizedTime < 1.0f)
         return true;
     else
         return false;
 }

But I don't like the frequent checks. I would rather like to have a variable to would be set by the animator. Or I would set it at the beginning of the shoot animation.
Because there are other animations that I have to check that would disallow shooting of the gun, too, like reloading the gun.
This would make everything even more complicated.
How can I solve this problem?


texts: In Text ui in the Inspector when showing text sometimes the text is bigger sometimes smaller how can I set it to be the same size in each case?

texts:
This is the Text component settings in the Inspector:

The script DialogueManager:

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

public class DialogueManager : MonoBehaviour
{
    public Text dialogueText;
    public float sentencesSwitchDuration;
    public bool animateSentenceChars = false;

    private Queue<string> sentence;

    // Use this for initialization
    void Start ()
    {
        sentence = new Queue<string>();
    }

    public void StartDialogue(Dialogue dialogue)
    {
        Debug.Log("Starting conversation with " + dialogue.name);

        sentence.Clear();
        foreach(string sentence in dialogue.sentences)
        {
            this.sentence.Enqueue(sentence);
        }

        DisplayNextSentence();
    }

    public void DisplayNextSentence()
    {
        if (this.sentence.Count == 0)
        {
            EndDialogue();
            return;
        }

        string sentence = this.sentence.Dequeue();
        dialogueText.text = sentence;

        StopAllCoroutines();
        StartCoroutine(DisplayNextSentenceWithDelay(sentence));
    }

    public IEnumerator DisplayNextSentenceWithDelay(string sentence)
    {
        if (animateSentenceChars)
        {
            dialogueText.text = "";
            foreach (char letter in sentence.ToCharArray())
            {
                dialogueText.text += letter;
                yield return null;
            }
        }

        yield return new WaitForSeconds(sentencesSwitchDuration);
        DisplayNextSentence();
    }

    void EndDialogue()
    {
        Debug.Log("End of conversation.");
    }
}

Then the DialogueTrigger:

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

public class DialogueTrigger : MonoBehaviour
{
    public Dialogue dialogue;

    public void TriggerDialogue()
    {
        FindObjectOfType<DialogueManager>().StartDialogue(dialogue);
    }
}

And last Dialogue:

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

[System.Serializable]
public class Dialogue
{
    public string name;

    [TextArea(3, 10)]
    public string[] sentences;
}

Then in the editor in the Dialogue Trigger in the Inspector I added some text to each of the 3 sentences:

Now when I'm running the game the text is changing between the 3 sentences.
But since each sentence have different amount of letters(text content) it display it in a different size:

This is the first sentence when the game is running it seems like to me a good size for the text:

The second sentence. It seems like to me the text size is too small.

The last sentence is the same size like sentence 2.

How can I make that the text will be the same size in each sentence ?
And how can I make that the lines will start from the same position from the left ?

How in other games they are aligning the text ?


texts: 2D Grid based game - how should I draw grid lines?

texts:
I'm playing around with a 2D grid based game idea, and I am using sprites for the grid cells. Let's say there is a 10 x 10 grid and each cell is 48x48, which will have sprites drawn there. That is fine.

But in design mode, I'd like to have a grid overlay the screen. I can do this either with sprites (2x600 pixel image etc) or with primitives, but which is best? Should I really be switching between sprites and 3d/2d rendering?

Like so:

Thanks!


texts: Moving the camera as in a first person shooter

texts:
I am trying to implement the movement of the camera with the mouse. The result I want to achieve is the same that you get when you move your aim in a first person shooter.

Here is the code I wrote, where "camera" is the vector which contains the location of the camera, "center" is the vector which contains the location of the point to which the camera is pointing at, and "move_vector" is simply "center" minus "camera"

    if(mouse_move_x != 0 || mouse_move_y != 0){

        float a0 = Array_norm<float>(move_vector,3);
        Array_copy<float>(move_vector,move_vector2,3);

        //perform mouse horizontal axis movement
        current_x_angle = atan2(move_vector[2],move_vector[0]);
        current_x_angle = current_x_angle + mouse_move_x * input::MOUSE_sensitivity * 0.017;

        move_vector[0] = cos(current_x_angle)*a0;
        move_vector[2] = sin(current_x_angle)*a0;

        //perform mouse vertical axis movement
        temp = sqrt(move_vector2[0]*move_vector2[0]+move_vector2[2]*move_vector2[2]);

        current_y_angle = atan2(move_vector2[1],temp);
        current_y_angle = current_y_angle - mouse_move_y * input::MOUSE_sensitivity * 0.017;

        move_vector2[1] = sin(current_y_angle)*a0;
        if(move_vector2[0]==0){
            move_vector2[2] = (move_vector2[2] >= 0) ? cos(current_y_angle)*a0 : -cos(current_y_angle)*a0;
        }
        else{
            temp2 = move_vector2[2]/move_vector2[0];
            temp = cos(current_y_angle)*a0*sqrt(1/(1+temp2*temp2));
            move_vector2[0] = (move_vector2[0] >= 0) ? temp : -temp;
            move_vector2[2] = move_vector2[0]*temp2;
        }

        //join x and y movements
        Array_sum<float>(move_vector,move_vector2,move_vector,3);
        Array_normalize<float>(move_vector,move_vector,3);

        center[0] = move_vector[0] + camera[0];
        center[1] = move_vector[1] + camera[1];
        center[2] = move_vector[2] + camera[2];

    }

Two questions:

the code works only when I consider only one of the due movements
(either horizontal movement or vertical movement). The code does not
work when I get both movements combined and I cannot understand why
Is there a better (and more mathematically compact) approach to compute the new camera position and focus point? I am sure there is :)

Thank you


texts:
Followup to securing-http-data-from-a-javascript-game-to-server.

I'm working on something similar, in that I have a PHP backend and a JavaScript frontend, which plays around with the HTML5 canvas element for drawing.

There will be some heavy client-server communication required, as the player will get timely updates from the server with regards to actions that other players are taking.  In turn, the client will update the server with his actions that have been taken.

My question is what is the best way to secure such data?  Since the client is basically JavaScript, what are some good ways to secure my game data / game states from being tampered with.

I had a thought (spurred by answers to the previous question), about generating a hash based on the currently active session, storing that in a game state database, and validating it server-side.  However, I would imagine that any data sent back to the server via AJAX can be scrubbed for any key that I send back.