texts: How to program an experience-based levelup system where experience carries over to the next level?

texts:
I'm new into programming, and i've tried to do a system of level up. Here it is :

if ($exp >= $max_exp)
{
        $query=$db->prepare('UPDATE users SET level_up = 1 WHERE username = "'. $username .'"');
        $query->execute();
        $query->CloseCursor();
}

if ($level_up >= 1)
{
        $query=$db->prepare('UPDATE users SET exp= 0, level = (level + 1 * level_up), max_exp = (max_exp * 1.2), spoint = (spoint +5 * level_up), level_up = 0 WHERE username = "'. $username .'"');
        $query->execute();
        $query->CloseCursor();
}

Explaination :

If the user get more xp (exp) than xp needed to level up (max_exp), he get a level up (level_up)
When the user level up, his XP is set to 0, his level goes up by (1 * the number of times he leveled up), same thing for his spoint (Special points). And next, his xp needed to level up goes up by 1.2.

Here are the problems with my badly coded system :

If max_exp is 100 and the user get 1000 xp, he will only get 1 level and loose the 900 xp because when he level up, the xp go down to 0. Any way to fix this ?
If the user level up twice, the max_exp will only multiply once by 1.2, so if a user is level 1 and level up to 3, he will get the max_exp of a level 2 user.
If there is another way than doing it without the level_up, i will gladly take it.

Thanks for the help !


texts: Performance overhead on Non-POT Texture in POT Atlas

texts:
Using atlas, we can reduce memory and draw call. And the atlas is usally POT(Power of Two) Texture.

And I know non-POT texture have a lot of GPU and memory performance overhead. (link)

I have many rendering objects and they have also their non-POT textures.
And I packed the images into one 1024*1024 POT atlas and applied them to the objects.

(each textures is non-pot, and the atlas is pot texture)

In this case, Can I avoid non-pot texture overhead?
Are they treated as non-pot texture or not internally?


texts:
I am finishing my game project and I already have my steamworks registration, I am just fine-tuning details and preparing marketing for the start.

But I look a little short of cash, I would like to invest more in marketing, when I heard this, a friend recommended that I sell some educational games that I had done a while ago (type "dora the explorer") but I don't want to publish them in my account , since my current project is a game of gore, blood, violence etc. I don't think it's right that they are "together", can I generate a new steamworks account to publish my other games?

I have not found anything in the document confirming that yes or no


texts:
I'm making a basic survival RPG in Unity 3d. I'm separating my world into different scenes to save memory but I'm not sure how I'm going to program NPC daily routines.

For example, if the player arrives in a town scene in the morning, how do I ensure that the NPCs are working in appropriate places with the appropriate equipment? I suppose I could hard code it so NPCs are in certain places at certain times. Therefore, if the player arrives at 9:00am then all the NPCs will move to their 9:00am places. I'm just wondering if there is a better way of doing it than that. I can see myself needing to write a lot of code to cover all the possibilities so it could get really messy. I was hoping there was some way I could have the NPC routines continue seamlessly in the background but this would be taxing on memory -if it's even possible.

Any ideas/pointers on this issue would be appreciated.


texts: How to make two connected rigidbodies pull each other?

texts:
I'm making a game in Unity where a ship can connect to a rock in space, and drag it. Both are Rigidbody2D. I want the ship to be affected by the rock like this:

If I drag the rock, then stop the ship, the rock keeps moving with the velocity it had.
If the rock gets pulled away by something, it should drag the ship when the rope is fully extended.
If the rock is heavy, the ship has more trouble pulling it
The rope might be a little elastic to make it more appealing

Is there a joint like this, or should I manually code it so they can affect each other? It seems like a basic game physics thing, but I can't find anything about it.
I tried using a distance joint with "Max Distance only" for this, but it doesn't work, as the rock stops when the ship stops:

For the visual part, I'm using verlet integration, with a slight gravity on the rope to make it more "springy", the current is a little too much but that's finetuning and not the problem of this question. :)


texts: Any problems with Event usages within XNA on Xbox/Phone

texts:
This is a slightly vague one but I am currently looking at a couple of areas of my current framework, such as spatial partitioning and UI based menus, and with UI menus it makes sense to have an event based system so you can tell if the user has clicked on it etc... its like your own small version of winforms.

However for some other areas it got me thinking that I could expose a lot of evens for other things, such as when an object moves so it could be re-allocated in a spatial tree of some kind if needed, or if it needed to calculate a collision it could return an event.

Anyway I quite like using events everywhere as it decouples you from having to know about who needs to know what, however I was wondering if there were any hidden gotchas with using events on the Xbox/Phone. I read a few older posts that mentioned that there are performance penalties with events on non PC platform (i.e http://blogs.msdn.com/b/shawnhar/archive/2007/07/09/delegates-events-and-garbage.aspx)

So is this still an issue or has XNA and the .net implementation on these machines improved in this area, as it would be nice to add events of all kinds to high level entities, like Player.HealthChanged, Creature.AnimationStateChanged etc, but I dont want to go exposing these for usage if there is a major performance overhead with doing so...


texts: How do I prevent raycast car wheels sliding sideways?

texts:
I've been writing a non-realistic car physics engine as a learning exercise, using this article as a reference.

I have a car that correctly collides with a terrain and applies the correct suspension forces for each wheel. My next problem is to prevent lateral movement of the wheels. For example, if I drop my car on a slope, it will slide sideways down the slope and then never stop sliding sideways (as there is no friction of any kind).

The linked article says that a "side force" must be applied, combined with the forward force, but it glosses over how that side force is calculated.

Given the collision info for each wheel (intersection normal, etc.) and the information about the car's rigid body, how can I calculate the appropriate side force to apply to the rigid body to prevent sideways motion?


texts: How can I easily test & visualize different math things?

texts:
For example, I've asked about the breakout formula to calculate the ball bounce. Inside of XNA, I don't know where I would code this and to even display something I would need a lot of code.
Is there something simple way visualize math formulas such as the one above?


texts:
I have created a wall using a cube in Unity. Now I want to create a door in it.

How can I make a door in that cube?

Consider that the cube is automatically generated, so i have to generate the door in a C# script.


texts: How can I control an object with tilt gestures?

texts:
I want an object (for example a ball) to move right when I tilt my Windows Phone device to the right. The same with the directions left, up and down. If the Windows Phone device isn't getting tilt in a direction, the object should rest in place.

How can I do that?

Update:
I updated my code but it's still not working. The ball doesn't move if I tilt my Windows Phone device. In addition, the ball just moves continuously upwards.

What is wrong?

I don't know how to normalize the ball's velocity vector afterwards. How can I do that?

public class Game1 : Microsoft.Xna.Framework.Game
{
    GraphicsDeviceManager graphics;
    SpriteBatch spriteBatch;
    Motion motion;
    Texture2D Ball;
    Vector2 BallPos = new Vector2(400, 300);
    Vector2 BallVelocity;
    float m_pitchForwardThreshold = 1f;
    float m_pitchBackwardThreshold = -1f;
    float m_speed = 0.5f;
    float m_rollForwardThreshold = 1f;
    float m_rollBackwardThreshold = 1f;

    void motion_CurrentValueChanged(object sender, SensorReadingEventArgs<MotionReading> e)
    {
        UpdateUI(e.SensorReading);
    }

    private void UpdateUI(MotionReading e)
    {
        float pitch = e.Attitude.Pitch;
        float roll = e.Attitude.Roll;

        if (pitch >= m_pitchForwardThreshold)
        {
           BallVelocity.Y = m_speed;
        }

        if (pitch <= m_pitchBackwardThreshold)
        {
            BallVelocity.Y = -m_speed;
        }

        if (roll >= m_rollForwardThreshold)
        {
            BallVelocity.Y = m_speed;
        }

        if (roll <= m_rollBackwardThreshold)
        {
            BallVelocity.Y = -m_speed;
        }

        BallPos = new Vector2(BallPos.X + BallVelocity.X, BallPos.Y + BallVelocity.Y);
    }

    public Game1()
    {
        graphics = new GraphicsDeviceManager(this);
        Content.RootDirectory = "Content";
        TargetElapsedTime = TimeSpan.FromTicks(333333);
        InactiveSleepTime = TimeSpan.FromSeconds(1);
    }

    protected override void Initialize()
    {
        if (Motion.IsSupported)
        {
            motion = new Motion();
            motion.TimeBetweenUpdates = TimeSpan.FromMilliseconds(20);
            motion.CurrentValueChanged += new EventHandler<SensorReadingEventArgs<MotionReading>>(motion_CurrentValueChanged);
            motion.Start();
        }

        base.Initialize();
    }

    protected override void LoadContent()
    {
        spriteBatch = new SpriteBatch(GraphicsDevice);
        Ball = Content.Load<Texture2D>("BallSprite");
    }

    protected override void Update(GameTime gameTime)
    {

        base.Update(gameTime);
    }

    protected override void Draw(GameTime gameTime)
    {
        GraphicsDevice.Clear(Color.CornflowerBlue);

        spriteBatch.Begin();
          spriteBatch.Draw(Ball, BallPos, null, Color.White, 0, new Vector2(Ball.Width/2, Ball.Height/2), 1f, SpriteEffects.None, 1);
        spriteBatch.End();

        base.Draw(gameTime);
    }
}


texts:
From other frameworks I know methods for easy ordering sprites within a spritebatch (to determine if a sprite has to be drawn in front or behind another sprite). For example in MonoGame/XNA this is called Sprite.depth or Pyglet has its OrderedGroups.

But I cannot find anything like that in libgdx. I've read that libgdx' scene2d has something like that but I don't want to use that as I use a entity system (ashley) and want to keep rendering separeted from the other logic.

What is the appropriate way to set the draw-order of libgdx sprites?


texts: Applying transformations in Geometry Shader

texts:
So, I am trying to program in opengl (3.3) a kind of robot. The idea is that I have some simple blocks that represent his body (4 rectangles for his arms, one for the torso and the last one representing the head). To simplify a made a bad picture of my idea.

So now what I want to do is to make him move his arms depending on keyboard commands. Doing that would be just rotating each arm the amount that you want (translating too).
But I am stuck because the only way I found to make striped rectangles (just the borders) is using the geometry shader. From the little I know about opengl, transformations are applied in the vertex shader, which would not work for my idea. Would be inefficient to apply the transformations on the geometry shader? (It is from what I know). If so, is there an easier way of drawing those rectangles?

EDIT: Ok, I can simplify a lot this question. The thing is that I want to draw those "skeletal" rectangles, but the only way I know how to do it is using the geometry shader. But with this comes the problem of the transformations, so I would want to avoid doing that. There is another way to draw those skeletal shapes?


texts: How to generate random waves for a bullet hell game that feel balanced and natural

texts:
My game consists of 'waves' of objects called 'spawners', which once every certain amount of time (their firetime), move to a new place on the screen and spawn an enemy. Each wave has 4 important properties:
1: the amount of spawners the wave has
2: the interval of time between creating new spawners
3: the total length of the wave
4: the types of spawners that can appear in a wave (represented as a std::vector<std::pair<std::string, int>> where the string is the spawner name, and the integer is its spawn weight.
The game works by picking a random spawner from the possible spawner types (with a weighted rng) every new spawner interval. Currently waves are set and are loaded from a file at runtime.
My problem is that I cannot find a good way to randomly generate waves that feel balanced and natural. Currently, I am trying to generate waves based on a difficulty value, mostly using weighted random number generation. However, this does not produce balanced waves that correspond well to the target difficulty. Even after trying several different techniques, I am unable to get a system that generates waves that fell balanced and natural (like the ones hand made).
Is there any way to generate waves that feel natural, based off of the difficulty value? How should I approach this problem?
Also if it's of any help, each spawner also defines its own difficulty value.
Example Waves:
Easier wave:
SpawnerTypes = {'BasicSpawner': 100} (basic spawner has a difficulty of 10)
SpawnerAmount = 5
NewSpawnerInterval = 4
WaveLength = 30
This is a good easy wave because it the spawner it has is simply shoots bullets that move in one direction at a slow speed, which are easy for the player to dodge. It also does not overwhelm the player with large amounts of them, and the wave is not too long
Medium Wave
SpawnerTypes = {'LaserSpawner': 60, 'BasicSpawner': 40} (basic spawner has a difficulty of 10, laser spawner has a difficulty of 20)
SpawnerAmount = 8
NewSpawnerInterval = 3
WaveLength = 30
This is a good medium wave because its combination of spawners requires the player to be paying close attention to multiple parts of the screen other than just right near the character, while still remaining relatively easy. It also spawners more spawners, but balances that by having a small interval between spawners and a small wave length.
Hard Wave
SpawnerTypes = {'RicochetSpawner': 100} (ricochet spawner has a difficulty of 60)
SpawnerAmount = 2
NewSpawnerInterval = 10
WaveLength = 30
Note that this wave has only one spawner type and only 2 of them, but is still much harder than the other listed waves
This wave is hard because the spawner it contains is challenging to keep track of, and in large numbers quickly because almost impossible, so it only spawners two spawners. However, the wave still lasts for 30 seconds, which provides the player with a decent challenge while not completely overwhelming them.
Extremely Challenging Wave
SpawnerTypes = {'RandomSpawner': 30, 'LoopSpawner
: 70} (random spawner has a difficulty of 90, loop spawner has a difficulty of 60)
SpawnerAmount = 4
NewSpawnerInterval = 5
WaveLength = 40
This wave is a perfect example of a wave which is extremely challenging, but is possible for a skilled player. It has two very hard spawners, one of which is very unpredictable (hence the name 'random'). It also spawns 4 spawners, and the wave lasts a total of 20 seconds longer than when the last spawners is created


texts:
What would be the fastest method for doing anti-aliasing for a flash game that is drawn via blitting to a BitmapObject?

A method I thought of would be to make games stage smaller than the BitmapObject that the game is drawn to, and then somehow shrink it to the size of the stage.

Would that method work? If so what would be the fastest and highest quality to shrink the bitmap? Or would there be a completely different way to do it?


texts: C++ exensible resource manager class with dynamic registration of factories

texts:
I've done some some research on my own, so I hope someone can help me finish it. I'm trying to replicate the design of an extensible asset manager featured in this answer.

At the moment I have created this and have no clue on how to proceed.

class ResourceManager {
    public:
        template<typename T>
        bool addFactory( std::unique_ptr<ResourceFactory<T>> factory ) {
            std::type_index ti = std::type_index(typeid(T));

            auto searchResult = factories.find(ti);
            if(searchResult != factories.end()) {
                return false;
            } else {
                factories[ti] = std::move(factory);
                return true;
            }
        }

        template <typename T>
        ResourceHandle<T> load(const std::string &path) {
            std::type_index ti = std::type_index(typeid(T));
            auto searchResult = factories.find(ti);

            if(searchResult == factories.end()) {
                throw NoValidFactory(std::string("No registered factory of type ") +
                                     ti.name());
            }

            // TODO SOMEHOW DO LOADING
            //return searchResult->second->load(path);
        }
    private:
        std::unordered_map<std::type_index,
                           std::unique_ptr<ResourceFactoryI>> factories;
 };

I assume that TextureHandle featured in the answer is probably a typedef for something like a custom reference counted smart pointer (e.g. ResouceHandle<Texture>, like in my engine) but how do I return something like that? I'm not (YET) good with templates but I know that it's impossible to have a virtual specifier with a template method, so I CAN'T do something like this:

class ResourceFactoryInterface {
    public:
        template <typename T>
        virtual ResourceHandle<T> load(const std::string &path) = 0;
};

template <typename T>
class ResourceFactory : public ResourceFactoryInterface {
    public:
    ResourceHandle<T> load(const std::string &path) {
        // loading
    }
};

// TODO Template specializations for object types? Inherit from ResourceFactory?

What should I do? Am I even close or am I doing a complete nonsense? How should I proceed?

If someone wants to know why I need something like that: at the moment I have one huge, difficult to maintain and extend ResourceManager class with a different method (loadTexture, loadMesh, loadSound, etc.) for each resource type. Having something that can be extended dynamically would make my hobby engine's resource management system more reusable. Moreover, I have a few places where I'd benefit from instantiating separate resource managers with only several registered (level specific) resource types.


texts: How to create communication with node.js server to client browser about monsters(object)

texts:
First hello and sorry for my English, and now about my problem.
I create node.js server that communicates with the browser-client for player position, life, def, etc ... with sockets.io. And my question is how can i do and communication between server and client about this monster(bot) object?


texts: Why might my Object Attributes become linked after refactoring?

texts:
As part of a game design class I'm taking this semester, I'm developing the basics of a game engine. I shared what I had in the GameDev chatroom, earlier, and everything was working as expected.

Then, because I knew it needed it, I started work on refactoring the core classes within my code. I modified the ancestor GameObject class, and after the tedious process of renaming all the method and field calls (I combined two float's, xPosition and yPosition into a single, Vector2d class - yes, I realize there are existing classes out there, but it was easier to simply write a new one, given that I can't make any assumptions on the installed libraries when it comes time for grading my work. I digress), prepared to test my newly refactored code.

The results were... perplexing. Suddennly, my SpawnPoint object was moving. Not only that, but it seemed attached to the PlayerEntity object itself, always matching the position of the controllable playerEntity (though it lagged a bit behind if you moved fast enough). And yet, I know that I never move the SpawnPoint, only the player entity; a quick search (ctrl+f) through my code confirmed that. But despite this, I had somehow managed to achieve quantum entanglement of these disparate objects.

I've reproduced both constructors below. Is this a case of passing by reference instead of by value? If so, is there a general way to avoid such troubles when instantiating objects with other objects as parameters?

Original Code:

public class PlayerEntity extends GameObject{

  SpawnPoint playerSpawn;
  public boolean isDead = true;
  float xVelocity;
  float yVelocity;

  //constructor, single dimension
  PlayerEntity(SpawnPoint spawn)
  {
    this.objClass = "entity";
    this.playerSpawn = spawn;
    this.xDiameter = 15;
    this.yDiameter = 15;
    this.xVelocity = 0;
    this.yVelocity = 0;
  }

  void respawn(){
   isDead = false;
   this.xPosition = playerSpawn.xPosition;
   this.yPosition = playerSpawn.yPosition;
  }

Refactored (Bugged) Code

public class PlayerEntity extends GameObject{

  SpawnPoint playerSpawn;
  public boolean isDead = true;
  Vector2d velocityVector;
  float xDiameter;
  float yDiameter;
  //constructor, single dimension
  PlayerEntity(SpawnPoint spawn)
  {
    this.objClass = "entity";
    this.playerSpawn = spawn;
    this.xDiameter = 15;
    this.yDiameter = 15;
    this.velocityVector = new Vector2d(0,0);
    this.positionVector = this.playerSpawn.positionVector;
  }

void respawn(){
   isDead = false;
   this.positionVector = playerSpawn.positionVector;
  }

The first thing first thing the PlayerEntity does in its update() method is call "respawn()" if isDead = true (which is why I think I got away without initializing the position in the first, working, code).

With the help of a debugger, I've narrowed down the method call which (unintentionally) modifies the spawnpoint's position. I'll probably edit that into the question when I have exactly identified the culprit.

Edit: Here is the method where the value is changing (though I don't know why), taken from playerEntity.

Original (working correctly)

void moveEntity()
      {

    this.xPosition += this.xVelocity;
    this.yPosition += this.yVelocity;
}

Refactored method (bugged behavior)

void moveEntity()
      {

    this.positionVector.xCor += this.velocityVector.xCor;
    this.positionVector.yCor += this.velocityVector.yCor;
  }

for whatever reason, this is causing the spawnPoint's positionVector to alter as well.

This program is written in Processing (which is just a java library, albeit one with its own IDE).


texts: Unity JSON parsing Array of Objects problem - error: JSON must represent an object type

texts:
I'm trying to use Json to hold game dialog in a text asset file. I've tried to make a barebones project to test this and it is failing with the Error Message: ArgumentException: JSON must represent an object type.

I have a class called LineData which has a few properties each line of dialog contains. In the Json there are just two lines for now. When I import and parse it to try and make a reference to one of the lines of dialog it fails.

Here is all the code:

dialogJson.JSON:

[
{
    "lineID": "BEDROOM_DAVE_0001",
    "lineDialog": "Yaawwn, up i get for another fun packed day.",
    "lineDuration": 3
},
{
    "lineID": "BEDROOM_DAVE_0002",
    "lineDialog": "Well I think I need a cigarette before I get to work!",
    "lineDuration": 3
}
]

LineData.cs

using System;

[Serializable]
public class LineData
{
    public string lineID;
    public string lineDialog;
    public float lineDuration;
}

GameController.cs

using UnityEngine;

public class GameController : MonoBehaviour
{
    TextAsset Dialog_Data;

    private void Start()
    {
        Dialog_Data = Resources.Load<TextAsset>("txt/dialogJson");

        LineData line1 = JsonUtility.FromJson<LineData>(Dialog_Data.text);
        Debug.Log("line 1 dialog = " + line1.lineDialog);
    }
}

NOTE: I read here (https://answers.unity.com/questions/1503047/json-must-represent-an-object-type.html) that Unity "can't parse if the json consists of an array of objects". But I don't understand his explanation on how to get around this. Thanks

EDIT: I now have it without error, but the debug message is just empty didnt seem to get any data) . Here is the json now after the edits:

{ "LineData":
[
{
    "lineID": "BEDROOM_DAVE_0001",
    "lineDialog": "Yaawwn, up i get for another fun packed day.",
    "lineDuration": 3
},
{
    "lineID": "BEDROOM_DAVE_0002",
    "lineDialog": "Well I think I need a cigarette before I get to work!",
    "lineDuration": 3
}
]
}

I've also altered the GameController.cs like this (but now it says Index is outside array bounds:

public class GameController : MonoBehaviour
{
TextAsset Dialog_Data;

private void Start()
{
    LineData[] lines = new LineData[2];
    Dialog_Data = Resources.Load<TextAsset>("txt/dialogJson");
    lines = JsonUtility.FromJson<LineData[]>(Dialog_Data.text);
    Debug.Log("line 1 dialog = " + lines[0].lineDialog);
}
}


texts: Getting OpenGL hardware acceleration with SDL on Linux

texts:
I'm trying to use SDL + OpenGL but I don't believe hardware acceleration is working because the framerate for around 18000 polys is about 24fps on a quad core machine but is a hopeless 1-2fps on an Intel Atom. Even the quad core starts to struggle when the poly count rises above this.

I've checked my code over but I'm clearly missing something obvious. I've changed my SDL initialisation code to use the same code as in the SDL OpenGL test. It reports that SDL_GL_ACCELERATED_VISUAL is 1 but that hw_available in SDL_VideoInfo is 0

Also the vendor is reported correctly as Nvidia on both machines and accelerated apps such as Compiz and glxgears work fine.

Any ideas of what to try?

Thanks


texts: How to change transform.position.x after a state is changed?

texts:
When I press attack button, player will change to Normal Attack state to perform Normal Attack animation and you will notice the player seem like step back a little bit as the width of sprite for Normal Attack animation is longer than Idle animation.

http://youtu.be/hnPXt-kprqQ

To solve this issue. I need to change the transform.position.x =+ 0.5 to move a bit further to match the position of Idle animation stands and transform.position.x =- 0.5 when Normal Attack state done its animation and back to Idle state.

How can I perform transform.position.x =- 0.5 when when Normal Attack state done its animation and back to Idle state?


texts:
While editing spline, I need to make one of the vertexes to be an absolute corner. I.e. bezier control points should be in zero distance from the vertex.

How to do that?


texts: Sphere / Simple Gravity (relative magnitude) - Push-back force C++

texts:
To save time in my game with pathfinding, I have a lower quality pathfinder, but the way units move between points is direct using

double distance = sqrt(xDistance * xDistance + yDistance * yDistance + zDistance * zDistance);
util_timer_movedelay += updatetime;
if (util_timer_movedelay > speed / 1000)
{

//  cout << "Distance:" << distance << endl;
    if (distance > 0.05)
    {
        unit_x += (0.5 * xDistance * speed * updatetime / distance);
        unit_y += (0.5 * yDistance * speed * updatetime / distance);
        unit_z += (0.5 * zDistance * speed * updatetime / distance);
        util_timer_movedelay = 0;

    }

Diagram
I would like help with a formula to help 1 push objects away from the sphere, but also attract objects to the sphere, now I already know how to calculate the distance that is easy as the above method is also spherical.

precision is an issue, due to the nature of how I've developed my game and the engine, the units are very compact, I'm having to use .3 float accuracy, so being as accurate as is reasonable is important (don't want to get stuck inside the planet or too far away for my path-finding to work), I don't want to push out 1 whole unit of location if the units on the surface of the globe are only 0.5 units in.

And obviously this would be able to work in the same way for the opposite direction yes ?

Basically simple question, how do I find the relative magnitude off distance for my red dot in the diagram to move exactly to the surface, or as close as possible. Should I just project a dot outwards ? I'm unsure / can't remember how to translate the point outwards relative to the sphere.


texts: How standardized are joystick / gamepad configurations?

texts:
Right now I'm working on input for my game.

The only controller I own is an XBOX 360 one.

From what I can see, if a controller's stick has a Z axis, these are actually triggers.

Essentially I'm wondering if from one controller to the next, will this be consistent?


texts:
I'm trying to make a window, then use the pack method to get the right size, but the window maximizes instead. Here's my code:

private Table buildOptionsWindowLayer() {
    winOptions = new Window("Options", skinLibgdx);
    // (...) building some widgets

    Gdx.app.log(TAG, "pref width is " + winOptions.getPrefWidth());
    // displays: "pref width is 247.0"

    winOptions.pack();

    // move the window
    winOptions.setPosition(Constants.VIEWPORT_GUI_HEIGHT - winOptions.getWidth() - 50, 50);
    return winOptions;
}

The window ends up with a width of 800.0f. Why?

What it is supposed to render:

What it does render:


texts: How can I create a slope/hillsde tileset?

texts:
I struggle to create a 2D slope/hillside for a tileset. Not an impassable mountainside like in Pokemon, more a gentle slope which you can walk both directions. When you see the tilemap, one should get a feeling that the two sides of the slope have a different heigth.

Ideas and suggestions are welcome.


texts: how to calculate initial Y velocity required to reach target?

texts:
I am trying to calculate the y velocity necessary for my player character to jump up and reach a y position within 1 second.

Given that my game engine is at 60fps, I am doing:

velY = (targetY - playerY) / 60

..  However, I need to account for gravity which is being applied to the character on every update, so I am doing:

velY = ((targetY - playerY) / 60) - (gravity * 60)

This results in the player character always jumping significantly higher than expect.

UPDATE

Attempting to try the Equations of Motion approach, I am setting a timestamp when the player character should begin moving to the target position...  So then in my update loop, I am calling a function with currentTime - timestamp.

update: function(paceFactor) {
    // paceFactor in this game engine is how many nominal 60FPS game “ticks” have elapsed. So if the game is running at 30FPS, then paceFactor will be 2.0, if it's 60FPS, then 1.0 will be passed in.

  this.timer += paceFactor * (1 / 60);

  if (this.setVelocityAt) {
    this.setVelocityFor(this.timer - this.setVelocityAt, this.targetPoint);
  }

  this.position.x += this.vel.x * this.speed * paceFactor;
  this.position.y += this.vel.y * this.speed * paceFactor;
  this.position.y += (gravity * (paceFactor * paceFactor) * 0.5);
  this.vel.y += gravity * paceFactor;
},

setVelocityFor: function(time, target) {
  if (time > 1) {
    time = 1;
    this.setVelocityAt = undefined;
  }
  this.character.vel.x = (target.x - this.character.position.x) / time;
  this.character.vel.y = (target.y + (0.5 * GRAVITY * time * time) - this.character.position.y) / time;
},

Then later the position and gravity is applied to the character as described in the previous update.

However, the velocity being set is a huge number which is... wrong.


texts: How do I provide incentive to a player to choose a specific option in a choice driven narrative

texts:
I am making a game where the choices you make are very real and have consequences that change the way the game plays. The game is styled after Chrono Trigger or Final Fantasy, in the way it plays and the style of art.

I am writing the flow-chart for the choices and the inciting event happens when the player chooses a specific choice. I want the game to stay open and I don't want to force the player into any choice by only presenting one option.

The inciting event occurs when the player goes out to get food for his dog (or cat, depending on what pet the player chose when he was creating his character) How do I provide enough incentive to cause the player to go out and get food for his pet?


texts: Aggregation of value in GLSL loop results in 0

texts:
I'm banging my head against a wall trying to understand why this code is giving me some reasonable results with some visible colors on parts of the screen...

#version 130

in vec2 vTex; // must match name in vertex shader
flat in int iLayer; // must match name in fragment shader

out vec4 fragColor; // first out variable is automatically written to the screen

uniform sampler2DArray tex;
uniform sampler2DArray norm;

#define MAX_LIGHTS 4

struct Light {
    vec3 position;
    vec4 color;
    vec3 falloff;
    vec3 aim;
    float aperture;
    float aperturehardness;
};

uniform Light lights[MAX_LIGHTS];

void main()
{
    vec4 DiffuseColor = texture(tex, vec3(vTex.x, vTex.y, iLayer));
    if (DiffuseColor.a == 0)
        discard;
    vec3 NormalMap = texture(norm, vec3(vTex.x, vTex.y, iLayer)).rgb;
    NormalMap.g = 1.0 - NormalMap.g;
    vec3 FinalColor = vec3(0,0,0);

    for (int i=0; i<MAX_LIGHTS; i++)
    {
        vec3 LightDir = vec3((lights[i].position.xy - gl_FragCoord.xy) / vec2(320.0, 200.0).xy, lights[i].position.z);
        float D = length(LightDir);
        vec3 N = normalize(NormalMap * 2.0 - 1.0);
        vec3 L = normalize(LightDir);
        vec3 Diffuse = (lights[i].color.rgb * lights[i].color.a) * max(dot(N, L), 0.0);
        vec3 sd = normalize(vec3(gl_FragCoord.xy, -1.0) - lights[i].position);
        float Attenuation = smoothstep(lights[i].aperture * lights[i].aperturehardness, lights[i].aperture, dot(sd,lights[i].aim))
            / (lights[i].falloff.x + (lights[i].falloff.y*D) + (lights[i].falloff.z*D*D) ) ;
        vec3 Intensity = Diffuse * Attenuation;
        FinalColor = max(FinalColor, DiffuseColor.rgb * Intensity);
    }
    fragColor = vec4(FinalColor, DiffuseColor.a);
}

... but when I change FinalColor = max(FinalColor, DiffuseColor.rgb * Intensity); to FinalColor = clamp(FinalColor + DiffuseColor.rgb * Intensity, vec3(0,0,0), vec3(1,1,1)); everything goes black. Is there something I don't understand about aggregation of variables in loops in GLSL, or about the + operator operating on vectors? By my logic, the changed code should return more brightness than the original code because the changed code would be adding all the values whereas the old code would just be taking the highest one.


texts: How to always draw a child mesh in front of its parent mesh

texts: I need to display a gizmo-like mesh at runtime, and it must be always in front of its target mesh. How can I achieve that?


texts: How to manage the lifetime of Ogre3D objects?

texts: I haven't found tutorials that are concerned about deleting scenenodes and entities. I assume that the scenemanager will take ownership of them when they are attached (am I right?). However, I can imagine many situations where I would like to deterministically and selectively terminate objects, for example if I were to use OGRE to display a huge open-world level, I would like to dynamically load and unload parts of the world. How can I do this while also telling the scenemanager that his pointer is no longer valid?


texts:
I have a theory on AI that I would like to write a "whitepaper" about. The distinction I want to explore in AI is learning vs. strategizing. My question is, where can I read other material about this subject?

Let me give a chess example. Let's look at a chess AI as a max-tree, where capturing an enemy unit adds that unit's value to the "move score" for that decision (and likewise losing a piece subtracts that value to the score). Capturing a pawn might net 1 point, a knight 4 points, a rook 5 points, etc.

Strategizing would be AI to apply these points and determine the next move; eg. given ten possible moves, pick the best (max score) at the end of three moves.

Learning would be applying statistical observation to determine those values. If you play 100 games, the AI might decide that capturing a pawn is 2 points, and a knight is worth 7 points, while a rook is only worth 3 points (based on 100 gameplays).

Does this distinction already exist in literature, and if so, where can I read about it?

Edit: Does anyone know a Chess game (with source-code preferably) that utilizes this approach? Maybe Chess960@Home?


texts:
I'm working on developing a game with C++, SDL, and OpenGL. I created the engine from scratch, and implemented my own state machine to handle menus and general gameplay.
Each State gets pushed into a stack and the last one gets updated and drawn, after initialization on entry. They also handle input on a per-State basis. Right now I have a State for entry point, a 'Press Any Key' prompt, a main menu, as well as a new game menu where the player enters their name.
I also batch my Sprites together for easy drawing. I simply pass a vector of Sprite pointers (as some animated sprites may be mixed in as well) to the drawing function which uploads the Sprites to a buffer and draws them. These vectors of Sprites are organized by batch type - mostly based on texture.

I'm moving on to the Exit Game menu, which displays a confirmation that the game will close and the player will be returned to their desktop. I wanted this menu to display on top of the Main Menu with a transparent black layer that darkens everything but the exit game prompt.
I can figure out the drawing part easily enough, but the problem is that the Sprites are local to the same State that created them. I am having troubles trying to decide how to 'share' the main menu sprites with the Exit Game State.
Likewise, I have the title screen background and logo. The logo animates as well. These two Sprites are visible to every title screen State. Which means I again need some way of continuously displaying a select few Sprites until further notice, such as on entry of the main game. When I get to cutscenes, I will typically need every Sprite used by the gameplay part of the game as well.

One idea I had was to store Sprites in the State Machine as opposed to the State itself. This would mean all Sprites are visible to every State, and the current State would decide which Sprites to delete and which to keep. This means that accessing the Sprites through the State would be a little more roundabout - some sort of access function through the State Machine.

EDIT: I've started implementing the first solution but putting Sprite batches into my Game Engine. The drawback is the scope of each Sprite is not so clearly defined per-State, they need to be directly deleted by the following State to determine which Sprites to keep and delete. It does also make identifying Sprites a little more difficult on transition, though I'm thinking of implementing a std::map of strings to Sprites as I'll need a naming system for cutscene scripting anyway.

I had another idea that would involve 'inheriting' Sprite batches from the previous State but that would also complicate identification of the Sprites.

ANOTHER UPDATE: I'm thinking of getting rid of AnimatedSprite as a distinct class. It just complicates the storage part. By merging it in with regular Sprites, Sprites can be animated but don't need to, and as for the extra storage needed for animations, I'm not too concerned as almost every one of my Sprites animates in some way. With this edit I store my sprites in a vector for batching, a map for naming, and a third optional pointer in my States that optimizes some menus by directly accessing Sprites rather than using map lookup. Going to try that and see how it works out.


texts: Any downsides to exporting an audio file at double-speed then have the game engine playback at half-speed?

texts:
I want to cut back on my game's file size and music and SFX are taking up a good chunk.

If I make a song or sound effect at 120bpm and then apply a tempo and pitch doubling using a DAW or standalone program, then record the new double speed audio file, it ends up being half the original file size (because the song length is now halved).
Then I use my game engine (Unity) to play back the 240bpm audio file at half speed, so now it sounds normal. No artifacts or distortion.

So here's the question: am I sacrificing anything like processing power in order to play it at half-speed? I am loading in a file that's half the size so there must be some kind of trade-off somewhere right? I have a feeling nobody in their right mind would do this but why not?


texts: Should I switch to a game development library?

texts:
I'm making an RPG-like 2D game from scratch with Java.

By now I'm in a pretty advanced stage with my game, but I encountered a problem- my game using too much CPU.

I know it's because my game loop doesn't use Thread.sleep. I looked for a solution on the internet but most of the answers were "you should move to LWJGL or LIBGDX". I also didn't find any good advice for using Thread.sleep in my game loop.

So, should I move my platform to some of those libraries, or could someone give me some advice how to deal with my CPU usage problem?

Here is my game loop:

public void run(){
    int fps = 60;
    double timePerTick = 1000000000 / fps;
    double delta = 0;
    long now;
    long lastTime = System.nanoTime();

    while (running){
        now = System.nanoTime();
        delta += (now - lastTime) / timePerTick;
        lastTime = now;

        if (delta >= 1) {
            tick();
            render();
            delta--;
        }
    }

    stop();
}

I will just mention that I don't think that moving to one of those libraries will make things easier in the future, and that's because I'm in a pretty advanced stage in my game.


texts: Why is the light following my camera around?

texts:
I have implemented a simple Phong shader without specular highlights for now (just ambient + diffuse components)

The problem however, is that the calculations seem to be done in camera space; as I move the camera around, the light source seems to move along with it. This is evident by me not being able to see the dark side of the models

(Note: Image is a gif, if it is not animating, open in a new tab)

My light is a point light, that I would like to have fixed somewhere in the world. It has a defined position. To my shader, I also pass in the M, V, P matrices, as well as the normal matrix, which is the inverse transpose of the MV matrix

cameraPosition=glm::vec3(8,8,8);
cameraTarget=glm::vec3(0,0,0);
cameraUp=glm::vec3(0,0,1);
glm::vec3 cameraDirection=glm::normalize(cameraPosition-cameraTarget);
cameraRight=glm::cross(cameraDirection, cameraUp);
view=glm::lookAt(cameraPosition, cameraTarget, cameraUp);
glm::mat4 model_view = view * modelMatrix;
glm::mat4 normal_matrix = glm::transpose(glm::inverse(model_view));

The following is my shader code

attribute vec3 vertex_position;
attribute vec3 vertex_colour_in;
attribute vec3 vertex_normal;

uniform mat4 model;
uniform mat4 view;
uniform mat4 projection;
uniform mat4 normal_matrix;
uniform vec3 ambient_light_colour_in;
uniform vec3 light_position_in;

varying vec4 fragment_colour;

void main(void){
  //position
  gl_Position = projection * view * model * vec4(vertex_position, 1.0);

  //ambient colour
  vec3 ambient_colour = ambient_light_colour_in * vertex_colour_in;

  //diffuse colour
  vec3 normal = normalize(vec3(normal_matrix * vec4(vertex_normal, 0.0)));
  vec4 pos4 = view * model * vec4(vertex_position, 1.0);
  vec4 lightPos4 = vec4(light_position_in, 1.0);
  vec3 lightDirection = normalize((lightPos4 - pos4).xyz);
  vec3 diffuse_colour = vertex_colour_in * max(0.0, dot(normal, lightDirection));

  fragment_colour.rgb = ambient_colour + diffuse_colour;
}

As far as I understand, the problem is that these lighting calculations are done in Camera space, and hence change when the camera changes position. So, my question is How would I change that to get the light to be at a fixed position, ie: do the light calculations in World space


texts: Generating "tile map" by stamping a full map

texts:
I'm building a game using Tiled tilemap editor.

I was originally creating tilesets to stamp around and create my map in Tiled.

Id prefer to create the base map in a Adobe Illustrator and stamp in the whole map as the level. Then stamp in trees or whatever on more layers as needed.

What are the implications on performance doing it this way vs creating the tilemaps and stamping them in tiled?

Example:

Tile:

Stamped Map:


texts: Can all DirectX11 games be deployed to Xbox One?

texts: If I program a game with DirectX 11 and C++ and make my own implementation can I deploy it on an Xbox one to test it? Otherwise, what do I need to do so?


texts: Modern OpenGL, billboarding, alpha transparency

texts:
I'm having some transparency issues when rendering billboards in modern OpenGL.

I've created two billboard sprites, each one with alpha transparency, just for testing.

When I render two sprites without any transparency, it all works as expected:

Whenever I render two sprites with alpha transparency, part of one of the sprites is blocked by the other:

At first I though it had something to do with the render order, so I tried to change the order by simply render the second sprite before the first one, but then the issue is on the first sprite instead:

Blending is enabled by calling glEnable(GL_BLEND); at the start of the application.

I feel like I've tried every glBlendFunc() combination (glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) etc) that exist in OpenGL but nothing helps.

I've also tried disable the depthmask by calling glDepthMask(GL_FALSE);but that doesn't help either.

I am using VBO's (one per sprite) when rendering.

In the vertex- and fragment shader I'm not doing anything more than setting the vertex position, the texture coordinate and the pixel color.


texts: Unity Cloud Build: Corrupted reffernces. Reimport All Assets possible?

texts:
When references in scenes or prefabs are missing, usually a reimport all fixes all issues. But when those problems occur in a cloud build that get's its data from a git repository the solution seems much harder. The AssetDatabase API allows for a reimport in a prebuild script:
using UnityEditor;
using UnityEditor.Build;
using UnityEditor.Build.Reporting;

class Reimporter : IPreprocessBuildWithReport {

    public int callbackOrder { get { return 0; } }
    public void OnPreprocessBuild(BuildReport report) {
        AssetDatabase.ImportAsset("Assets", ImportAssetOptions.ImportRecursive);
    }
}

But the UnityEditor libary isn't accessible in a cloud build.
Is there a way to fix missing references in a cloud build or trigger a reimport via a pre build script or something similar?
PS: Local builds after a fresh checkout of the github project do not have this issue, and only Cloud builds suffer from these missing references. Maybe someone knows the root of the issue and how to overcome it, so that none of these hacky solutions would be required.


texts: How to use Monogame Content Pipeline with XML

texts:
I have an XML file that I'm trying to import into my MonoGame project using the content pipeline.  I'm having trouble getting the MonoGame Pipeline tool to convert the XML file into a .xnb file before I can even run the program.

The XML file is as follows:

<?xml version="1.0" encoding="utf-8"?>
<XnaContent>
  <Asset Type="GameObjects.ObjectInstruction">
    <FrameNames>
      <Item>Image_1</Item>
      <Item>Image_2</Item>
    </FrameNames>
    <FrameSpeed>10</FrameSpeed>
    <HorizontalOrigin>0.5</HorizontalOrigin>
    <VerticalOrigin>0.5</VerticalOrigin>
    <HorizontalScaling>1</HorizontalScaling>
    <VerticalScaling>1</VerticalScaling>
    <HorizontalOffset>0</HorizontalOffset>
    <VerticalOffset>0</VerticalOffset>
    <Subset Null="true" />
    <RotationRadians>0</RotationRadians>
    <Tint>
      255
      <G>255</G>
      <R>255</R>
      255
      <PackedValue>4294967295</PackedValue>
    </Tint>
  </Asset>
</XnaContent>

The GameObjects namespace is in a Visual Studio project that creates a .dll file, and I have another MonoGame project that references GameObjects and is the one in which I'm trying to do all the content stuff.

Inside the Pipeline tool I've got a reference set to the GameObjects.dll file.  This file shows up in several places, and if I pick the wrong one the Pipeline tool fails with the error "Assembly is either corrupt or built using a different target platform than this process. Reference another target architecture (x86, x64, AnyCPU, etc.) of this assembly."

If I change the reference to the .dll file in the GameObjects project folder, the Pipeline tool still fails when trying to process my XML file.  The error message looks like "System.Xml.XmlException: 'Element' is an invalid XmlNodeType. Line 19, position 8."  This part of the XML file would be the G field of the Tint part of the ObjectInstruction object (Tint is a Color).

I've been knocking my head against this problem and getting nowhere.  How do I use the Monogame Pipeline tool with XML files?  How do I get it to recognize the definition of ObjectInstruction and process the XML file into a .xnb file?  I'm pretty sure the rest of my program will run if I can solve this bit.  Thanks for any help.


texts: Get a warning about extension when compile GLSL code with glslc compiler shipped with vulkan SDK

texts:
Trying to compile my pixel shader,and a warning generated:

D:\CS\ComputerGraphics\vulkan\WindowsProject1>D:\ProgrammingTools\vulkan\Bin\glslc shader.frag -o frag.spv
shader.frag:3: warning: '#extension' : extension not supported: GL_KHR_vulkan_glsl
1 warning generated.

The following is my pixel shade code:
#version 460
#extension GL_ARB_separate_shader_objects : enable
#extension GL_KHR_vulkan_glsl : enable
#extension GL_EXT_debug_printf : enable
//Input
layout(location = 0) in vec3 fragColor;
layout(location = 1) in vec2 fragTexCoord;
//Output
layout(location = 0) out vec4 outColor;
//uniform
layout(set = 0,binding = 2) uniform sampler2D texSampler;
void main() {
    outColor = texture(texSampler, fragTexCoord);
}

how do I fix this?


texts: Will performance suffer if I have a really large depth range but not very many objects?

texts:
I don't know where the impression came from, but somehow it got in my head that having too small a "near" and too large a "far" in your projection at the same time would impact performance. In general that seems to hold true if there are many objects in your world like a crowded city where distant things are more likely not to be drawn because they're obstructed by closer objects. But what about fewer objects that don't obstruct each other?

I'm working out a game idea that has an "eye in the sky" camera that is expected to see a large portion of terrain kind of like an RTS (actually the camera is attached to a drone flying at altitude). I tried bringing my camera closer to the terrain and trying to make it behave like it's 50k ft in the air but nothing quite beat the feel of actually putting the camera very far away from the ground and using the field of view to zoom in and out. To make this work, I had to increase my Far plane by an extra order of magnitude.

All objects are on or near the ground in a relatively tight Y range compared to how far my camera is. I'm not drawing an obscene amount of things (at least not yet, it's still early in development) and very few objects are completely obscured by larger/closer objects. Is the large render distance of my camera going to be an issue or have side effects as I progress through development? Or should I re-approach the idea of bringing my camera closer to the world and having it simulate a larger distance (and how exactly would I do that)?

I'm using Unity 5, but I imagine my question won't be too specific to a framework.


texts: Workflow for tagging a sprites with collision boxes

texts:
I have some hundred of sprites and I need to mark collision boxes of them.

What kind of workflow can I use to help this proceed smoothly?

I've thought of using Tiled initially, however one of my requirements would be to not only mark multiple collision boxes per sprite but also to mark each one with a name or type category.

I would love to have final structure equivalent to:

<Bodies>
    <Body id="1">
        <CollisionBox>
            <Name>BODY_COLLISION</Name>
            <Vertices>
                <Vertex>12;13</Vertex>
                <Vertex>12;17</Vertex>
                <Vertex>11;17</Vertex>
            </Vertices>
        </CollisionBox>
        <CollisionBox>
            <Name>GROUND_DETECTOR</Name>
            <Vertices>
                <Vertex>12;11</Vertex>
                <Vertex>13;17</Vertex>
                <Vertex>14;17</Vertex>
            </Vertices>
        </CollisionBox>
    </Body>
</Bodies>

How can I build this data quickly & intuitively?


texts: How do I draw two lines of text in GMS and keep one static?

texts:
I am making an intro sequence for my game, but I'm having some difficulty drawing two lines of text. The first line is "DEVELOPED BY:" referenced from a separate language file as "IntroSequence", "DevelopedBy". The next line (made by using + chr(13) + chr(10) +) is my name which I want to be kept static. I would essentially like the user to be able to make different language files being able to change the string reference "DEVELOPED BY:", but not the developer name. Now, I can get the text to draw if I use "DEVELOPED BY:#Mr.Mendelli" in the language file, or keeping both strings static in the script by declaring mytext = get_text("DEVELOPED BY:" + chr(13) + chr(10) +"Mr. Mendelli");. But If I use the second method, the DevelopedBy string cannot be translated in the language resource any more.

When I use the below script, GMS says two arguments are declared, but three are provided:

mytext = get_text("IntroSequence", "DevelopedBy" + chr(13) + chr(10) +"Mr. Mendelli");
image_alpha = 0;
statetime = 0;

How do I use my alias as an unchangeable separate line?


texts: How to compute a transformation matrix that describes each position and rotation on a sphere?

texts:
I am having an issue constructing my transformation matrices, for this sphere problem.

I know the 3d coordinate of the center, and the radius of, the sphere.

Since I know the radius and center of the sphere, it's easy to compute all positions on the sphere, but I'm not sure how I should compute the rotation matrix?

Each point has to be rotated such that it points toward the object, and the only thing that tells me the orientation of the vector is the difference between the 3d point on sphere and the 3d point of the object.. But one vector doesn't seem enough to construct a whole rotation matrix?...

Could I extract a rotation matrix, that "tells" the point how it should be rotated to look at the object?


texts: Changing gamma values in video settings screen?

texts: So I am trying to change the gamma values and brightness in my game. I think it has something to do with IDirect3DDevice9::SetGammaRamp function but I am not exactly sure how to use it. Anyone has any input on this?


texts: Clamp view direction vector to nearest axis

texts:
In JMonkeyEngine, given any view direction Vector3f instance, I'd like to get a new vector facing the nearest x or z axis (positive or negative), with y set to 0.

For example

[-0.99915564, -0.036672898, -0.018518358]
// -> should return [-1, 0, 0]

[-0.01313778, 0.042407744, 0.99901414]
// -> should return [0, 0, 1]

Is there a nifty math trick for this or do I need to manually check x and z and then set y to 0?

Thanks.

Update

So far, what I do is this

dir.x = dir.x >= 0 ? Math.floor(dir.x + 0.5) : Math.ceil(dir.x - 0.5);
dir.y = 0;
dir.z = dir.z >= 0 ? Math.floor(dir.z + 0.5) : Math.ceil(dir.z - 0.5);

Which produce the desired output. I was wondering if this can be done in a more elegant fashion (i.e. through some nifty matrix operation).


texts:
I am trying to add bloom in my unity game for mobile phones using URP,
The problem is, everything works perfectly in the editor/pc,
But the bloom effect vanishes on the actual apk build.
This is how it looks in the editor - Upper window is game view and below is the scene view

This is what it ends up on the mobile -

All the other post processing effects works except bloom...
Unity Version - 2020.1.2f1
URP Version - 8.2.0
Post processing is enabled on the camera component
HRD is enabled in the SRP settings asset
I don't know what am I missing or even it is possible to have bloom on mobile.
I've tried all sorts of things, but nothing works, Even tried on multiple android devices,
But I get same results every time...
Anyone who knows how to make it work, please help me,
I'll be really grateful.


texts:
Is it possible to use Hybrid ECS with some components and the standard MonoBehaviour with all your old code?

I want to know because I already have some game mechanics build with the "old" way and I want to build the new ones using hybrid


texts: How can I render a texture to the screen in SDL2?

texts:
I've recently started upgrading my SDL version from 1.2 to 2.0.3, and while on the SDL Wiki, I've come across SDL_Renderer, SDL_Window, and SDL_Texture. I did some research and found a link at StackExchange to be particularly informative. However, I'd like to know more about the process of getting a texture on the screen with this new software version.

My Question

By what process does SDL2 display a texture to the user's screen?

My Current Understanding

My current understanding is that a renderer is tied to a single window, which allows the coder to blit a texture (or multiple) to a renderer, which is then displayed to the window. Is this approximation correct?


texts: unable to use two gestures simultaneously

texts:
I have a class implementing gesture listener in libgdx. I want to use longpress gesture in one half of the screen and fling gesture in other part of the screen simultaneously.

public class FlingHandler implements GestureDetector.GestureListener{

GameWorld world;
Bmw bmw;
private float  w,h,xunit, yunit;
private float spd = 1;
private float xtouch = 0, ytouch = 0;
private float xVel = 0, yVel = 0;
private int p = 0;

public FlingHandler(GameWorld world) {
    this.world = world;
    w = SS.WIDTH;
    h = SS.HEIGHT;
    xunit = SS.x;
    yunit = SS.y;
    bmw = world.getBmw();

}
public void update(float delta){
    updateLongpress(delta);
}

public void updateLongpress(float delta){

    if(longPress(xtouch,ytouch)==true && world.getBmw().isDead()==false) {
        if(spd <1600 && Gdx.input.isTouched()){
            spd += 0.9f*delta;
            Gdx.app.log("speed ","increasing"+spd);
        }
    }

    else if(longPress(xtouch,ytouch)==false && world.getBmw().isDead()==false){

            if(spd > 1 ){
                spd -= 8f*delta;
                Gdx.app.log("speed ","decreasing"+spd);
            }
    }
    else{

    }
}

@Override
public boolean fling(float velocityX, float velocityY, int button) {
    xVel = velocityX;
    yVel = velocityY;
    xtouch=Gdx.input.getX();
    ytouch=Gdx.input.getY();
    p = button;

    if(xtouch > SS.WIDTH/2 && world.getBmw().isDead()==false) {
        if (Math.abs(xVel) > Math.abs(yVel)) {
            if (xVel > 0) {
                if (world.getBmw().getPosition().x < 8 * xunit) {
                    world.getBmw().getPosition().x += 4 * xunit;
                }
            } else if (xVel < 0) {

                if (world.getBmw().getPosition().x > 7 * xunit) {
                    world.getBmw().getPosition().x -= 4 * xunit;
                }

            } else {}

        }
        return true;
    }
    else
    return false;
}

@Override
public boolean longPress(float x, float y) {
    xtouch = Gdx.input.getX();
    ytouch = Gdx.input.getY();

    if(xtouch < SS.WIDTH/2 && world.getBmw().isDead()==false){
        return true;
    }
    else if (xtouch > SS.WIDTH/2){
        return false;
    }
    else
    return false;
}


texts: NodeJS setTimeOut - How to run callback before delay time exceeded

texts:
I'm developing a card game server.
I want to do this :
While server process a turn for players, players have 20 seconds to do something. If players send a request to server within 20 secs, timer will stop and the callback will fire.

I'm doing like this :

self.tables[table.id].currentTimer = setTimeout(function () {
    callback();
}, 20*1000);

How should I run the callback before delay time exceeded ?


texts: What is the component for the AI system in a component-based entity implementation?

texts:
In order to wrap my head around component-based systems, I started making my own little framework. Unfortunately I am not completely sure how systems are supposed to be used in some specific cases.

For example I can understand the use of a RenderSystem or a CollisionSystem but how would one implement AI and how would the component look like? I am especially confused when it comes to actions. Could actions be stored in the components as objects?


texts:
I'm trying to wrap my head around coordinate projection, and can't seem to solve the problem I am having. Here is an illustration of it:

The cubes represent 3d space, and the 2 red lines represent the positions of 3 points (which could be n points). I'm then trying to project these lines onto the green plane shown on the second cube.

My code so far for this is the following:

private List<Vector3> ProjectPoints(List<Vector3> points, Vector3 axis1, Vector3 axis2)
{
    var projectedPoints = new List<Vector3>();

    // first point is already on plane
    projectedPoints.Add(points[0]);

    // blue line
    axis1.Normalize();
    // yellow line
    axis2.Normalize();

    var planeNormal = Vector3.Cross(axis1, axis2);

    float totalRotationAngleSoFar = 0;

    // project remaining points
    for (int i = 1; i < points.Count; i++)
    {
        // get point relative to origin (prev point)
        Vector3 pointRelativeToOrigin = points[i] - points[i - 1];
        Vector3 pointDir = Vector3.Normalize(pointRelativeToOrigin);

        // rotate point by all the angles from previous points, this is so if we had
        // a curve where the points went in on themselve, this rotation would see the
        // curve 'unfolding' into a straight line on the plane
        Vector3 rotationAxis = Vector3.Cross(pointDir, planeNormal);
        Vector3 rotatedPoint = Vector3.Transform(pointRelativeToOrigin, Matrix.CreateFromAxisAngle(rotationAxis, totalRotationAngleSoFar));

        // get rotation axis and min angle between point and plane.
        float minAngleBetweenPointAndPlane = TODO_GetAngleBetweenPointAndPlane();

        // add to total rotation for the next point to use (TODO minus or plus?)
        totalRotationAngleSoFar -= minAngleBetweenPointAndPlane;

        // rotate point in line with plane
        Vector3 projectedPoint = Vector3.Transform(rotatedPoint, Matrix.CreateFromAxisAngle(rotationAxis, minAngleBetweenPointAndPlane));
        projectedPoint += projectedPoints.Last();
        projectedPoints.Add(projectedPoint);
    }

    return projectedPoints;
}

I 'think' this is the right approach, though not 100% sure. Also I've no idea how to calculate TODO_GetAngleBetweenPointAndPlane() with the data I have. I expect you can use the dot product, but I'm not sure what data I would plug in.


texts: Implementing traffic conditions in TORCS

texts:
I am working on a project about "Effects of Traffic conditions and Track Complexity on Car Driving Behavior".

Is it possible to implement traffic in TORCS, or should I use another car simulator? By the word "traffic" I mean there are cars running on both tracks in both directions and I can detect the distances, direction and speed of these cars. Depending on this information I can decide whether I should slow down, speed up and calculate the correct timing to overtake.


texts: Texturing in OpenGL, Should texture coordinates be assigned to vertices in the shader?

texts:
I attempting to texture 3D models (a cube for example) using ibo’s, with OpenGL in Java. Currently, my textures are distorted. I believe this is because only a single texture coordinate is being assigned to each vertex, as the meshes are loaded from wave front (.obj) files.

As each vertex should correspond to multiple texture coordinates, should I be assigning texture coordinates to vertices as the data is loaded from file or would it be better to assign texture coordinates to vertices in the shader?

I would appreciate example code.


texts:
I'm looking for some math, nothing language dependant.

"Standard" gravity for a character in a 2D game would go something like this:

if player.y > ground.y {
   player.velocity.y = player.velocity.y - gravity
}

In the little game I'm implementing I would actually like the gravity to weaken, and the velocity to slow, as the player approaches the ground.

IE: When the character is 100m above ground he should fall faster than when he is 1m above ground. He should land like a feather in a way.


texts: Unity / Animation / Change the "Transition Speed" between 2 animations during runtime

texts:
I need to change the Transition Duration per Runtime.
I just didnt find a way to do access it.
I found questions with similar problems though (links below)- those didnt work for me because they accessed it to change it via editor - script. But I need it in runtime.
Is that even possible?

https://stackoverflow.com/questions/29315507/unity-5-access-modify-animatorcontroller-from-c-sharp-script-in-editor


texts: Canvas Drag and Drop children within parent

texts:
I have a working drag and drop script for gameobjects within a canvas panel.
I would like to prevent the panels children from being dragged outside of the panel.
I have a somewhat working (although very ugly) way to do this but it fails when the children of the panel are various different sizes they tend to come off the panels edges slightly depending on how large they are.
Here is my drag and drop script that is attached to the children of the panel:
public class DragAndDrop : MonoBehaviour
 {

     private bool isDragging;

     public void OnMouseDown()
     {
         isDragging = true;
         PlayerController.Instance.currentObject = gameObject;
         GameObject sceneController = GameObject.Find("SceneController");
         sceneController.GetComponent<SceneController>().enableEditor();
     }

     public void OnMouseUp()
     {
         isDragging = false;
     }

     void Update()
     {
         if (isDragging)
         {
             Vector2 mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position;

             transform.Translate(mousePosition);

         } else
         {
             if (transform.position.x <= -3f)
             {
                 transform.position = new Vector3(-3f, transform.position.y, transform.position.z);
             }
             if (transform.position.x >= 3f)
             {
                 transform.position = new Vector3(3f, transform.position.y, transform.position.z);
             }

             if (transform.position.y <= -4.5f)
             {
                 transform.position = new Vector3(transform.position.x, -4.5f, transform.position.z);
             }
             if (transform.position.y >= 3f)
             {
                 transform.position = new Vector3(transform.position.x, 3f, transform.position.z);
             }
         }
     }
 }

Any help would be greatly appreciated, thanks for your time!


texts: How can I position sprites in a Component-Entity engine?

texts:
I'm building my first component/entity engine and I'm not so sure about some of my choices. I'm here asking suggestions on my first doubt.

I draw objects with 2 different behaviours:

Position driven by Physics.
Position defined by other logics.

At the moment I've only built the first kind of object adding to some entities a Render component (which contains information about the sprite to draw) and a Physic component which contains body information.
The Rendering system just attaches Render components sprites to the main view and the Physic System takes each entity that owns a Physic component and defines the sprite position for each entity.

Question 1)

Is it a valid choice to access (and modify) Sprites positions directly through the Physic System?

Question 2)

For the second type of object, should I manage the sprite position using a third component which is responsible only for that?

Is it a valid solution or I'm totally wrong?

I'm a bit confused about how to manage logic and positions with this kind of system... It seems a bit overwhelming to create a component for every behaviour that I need to define.


texts: Transparency sorting in 3D world with different render types

texts:
I am rendering a world, object, and models from an older game format. The world is presented in a BSP tree so I can quickly iterate through. The opaque surfaces are rendered front to back. Then transparent surfaces are rendered back to front. For the world, that is all fine. I add the transparent pieces into a stack and pop them off one at a time and render.

Now I am realizing that characters that move in the world also support transparency and there is a possibility for error if I render them after the world and they happen to be overlapping with other semi transparent surfaces. Similarly, I have objects to handle.

The solution I have been kicking around in my head is to create a vector of containers that hold my current render structure and a distance from the camera. I would then sort these structures based on distance and then render them one by one.

As it stands now, my render call accepts a pretty generic object:

struct RenderCall
{
    GLuint textureID;
    int indexStart;
    int indexCount;
};

struct TransparentRenderCall
{
    float distanceToCamera;
    RenderCall call;
};

What do you think? Is there a more streamlined way to do this?


texts: Space Invaders-type game: Keeping the enemies aligned with each other as they turn around?

texts:
OK, so here's the lowdown of the problem I'm trying to solve.

I'm developing a game in PyGame that's a cross between Space Invaders and Columns.  I'm trying to make the motion of the enemies similar to that of the aliens in Space Invaders; that is, they're all clustered in a grid, and if even one hits the side of the screen, the entire formation moves down and turns around.  However, the motion of these aliens is continuous (as continuous as a monitor can be, anyway), not on a discrete grid like in the original.

The enemies are instances of an Enemy class, and in turn they're held by a 2D array in a enemysquadron module (which, if you don't use Python, is in this case essentially a singleton due to the way Python modules work).

Inside the Enemy class I have a class-scope velocity vector that is reversed every time an Enemy object touches the edge of the screen.  This won't do, though, because as time goes on the enemies just become disorganized and jumbled (i.e. not in a grid as planned).  I haven't implemented the Enemies going downward yet, so let's not worry about that right now.

Any tips?


texts: Is it possible to use 3G internet for a TCP/IP game server?

texts:
I'm working on a turned based multiplayer android game with a friend.
I started working on the game server and client using socket programming.
I found a few tutorials on how to implement a basic chat on android and I started extending that example to suit my needs.
Basically the game is really simple and the communication only include sending a few string from the client to the server every turn and sending the calculated scores back to all the clients after each turn.
the idea is that one of the players creates the game and thus initialize the server, and each player connects to this client using ip.
I tried this solution and it seems to work great when all the players are using the same wifi connection or by using router port forwarding.
The problem is when trying to use 3G internet for the server, I guess the problem is that 3G ip address isn't global and you can't use port forwarding there, correct me if I'm wrong here.

Is there a way to overcome this issue? or the only solution is to limit my game to wifi only or think of a different solution than the standard socket programming solution? I.E web server etc.

what do you think would be the best approach here?

Thanks.


texts: How to set the hair_mesh to follow the animation?

texts:
How to set the hair mesh to follow the animation?
I am trying this.
.cpp
Hair = CreateDefaultSubobject<USkeletalMeshComponent>("Hair");
    Hair->SetupAttachment(GetMesh());
    Hair->AttachToComponent(MyCharacter::GetMesh(), FAttachmentTransformRules::KeepWorldTransform, TEXT("head"));

.h
UPROPERTY(EditAnywhere, Category = "Components")
    class USkeletalMeshComponent* Hair;

I have attached the hair mesh to the Head socket but the hair mesh is not following the animation.
The hair mesh is called Hair_Mesh and has been attached in the editor while the Hair skeletal mesh component is already sets to UPROPERTY(EditAnywhere, Category = "Components")


texts: Best C# technique to pass variable from Instantiated object to GameObject

texts:
There are lots of instantiated prefabs.  Info from it is transmitted while it crosses a trigger zone.  Some of these are calculated custom variables.

I can print the custom variables from the instantiated prefabs.

I can get the trigger zone to report standard things like "...transform.position" or "...transform.localEulerAngles", but not stuff I make up. Intellisense seems to see everything I am trying to get, and everything compiles.

What's the best manner to perform this?  Here's what I've tried:

Prefabs' Script:

public float infoToSend;
 void Update(){
 float infoToSend = 10f //...actually, there's some math here, but it's a float.
}
print("Sender: " + infoToSend); //Works.

Receiver Script on Trigger Zone:

void OnTriggerStay2D(Collider2D other){

print("Receiver: " + other.transform.position);  //Works Fine.
print("Receiver: " + other.transform.localRotation);  //Works Fine.

float infoReceived = other.GetComponent<PrefabsScript>().infoToSend;
print("Receiver: " + infoReceived);  //Does not work!
}

Any help, either fixing this arrangement or directing me to a different method, would be appreciated.  Thanks.

Edit to display the solution:

Corrected Prefabs' Script (changed third line down):

public float infoToSend;
 void Update(){
 this.infoToSend = 10f //...actually, there's some math here, but it's a float.
}
print("Sender: " + infoToSend); //Works.

Correct Receiver Script on Trigger Zone:

void OnTriggerStay2D(Collider2D other){

print("Receiver: " + other.transform.position);  //Works Fine.
print("Receiver: " + other.transform.localRotation);  //Works Fine.

float infoReceived = other.GetComponent<PrefabsScript>().infoToSend;
print("Receiver: " + infoReceived);  //Does not work!
}

Many thanks, again!  There's so many places to begin with, it's tough to find a "Beginner course" to cover everything.


texts: How to do pixel perfect movement with Unity3D?

texts:
How would you be able to make sprites move pixel by pixel in Unity3D? I've tried the following things.

int x = (int) transform.position.x;
int x = Mathf.FloorToInt(transform.position.x);
int x = Mathf.RoundToInt(transform.position.x);

I don't know what else to try

Because I'm making an SNES looking game, and when things move, there is very bad pixel crawl in the sprites.


texts:
I am working on targeting system for 2D game. Two objects move in space.
Each one have Position and Velocity vector. Ship object shoots moving objects in space. Ship can shoot in any direction, but Ship Velocity is added to projectile Velocity.

I read some tutorials and I know the solution is quadratic equation. Moreover I implemented one solution and I achived 75% hits, but sometimes my projectiles fly behind or before object. Also I am not sure how it works underneath... I understend quadratic equation from math lessons but I don't see how it is related to that target calculation. Can some explain in on some drawing?
I totaly can't understand why a,b,c parameters looks like they look.

Here is my code:

        Ship.World.Query(boundingBox), objects);

        Vector3 shipToTarget = Vector3.Forward;

        WorldObject closestObject = GetClosestAsteroid(objects);

        Vector3 aimSpot = Vector3.Forward;
        Vector3 bulletPath = Vector3.Forward;
        float a, b, c;
        float p, q;

        float t1, t2, t;

        float timeToImpact = 0;

        if (closestObject != null)
        {
            shipToTarget = closestObject.Position - Ship.Position;
            a = closestObject.LinearVelocity.X * closestObject.LinearVelocity.X + closestObject.LinearVelocity.Z * closestObject.LinearVelocity.Z - (40 * 40) - (Ship.LinearVelocity * Ship.LinearVelocity).Length();
            b = 2 * (closestObject.LinearVelocity.X * (closestObject.Position.X - Ship.Position.X) + closestObject.LinearVelocity.Z * (closestObject.Position.Z - Ship.Position.Z));
            c = (closestObject.Position.X - Ship.Position.X) * (closestObject.Position.X - Ship.Position.X) + (closestObject.Position.Z - Ship.Position.Z) * (closestObject.Position.Z - Ship.Position.Z);

            p = -b / (2 * a);
            q = (float)Math.Sqrt((b * b) - 4 * a * c) / (2 * a);

            t1 = p - q;
            t2 = p + q;

            if (t1 > t2 && t2 > 0)
            {
                t = t2;
            }
            else
            {
                t = t1;
            }

            aimSpot = closestObject.Position + closestObject.LinearVelocity*t ;
            bulletPath = aimSpot - (Ship.Position + Ship.LinearVelocity * t);

            Ship.Shoot(Vector3.Normalize(bulletPath));

        }


texts: What is a good way to procedurally generate large tilemaps?

texts:
I'm sorry if this question was already asked before.
The game I'm aiming to make is a 2D-top down game in similar fashion to Zelda. I'm generating tilemaps, simple grids with 16x16 pixels per tile, and I'm using cellular automata combined with some other methods to generate these tilemaps. I can generate fairly large tilemaps, but It's problematic to go too big and it seems very ineffiecent. To be able to have a big world I decided it was probably smart to divide everything up in smaller seamlessly connected tilemaps, but I'm really unsure how to actually deal with such a large map. Since I'm planning on having maybe 40x40 tiles per area, and 100x100 areas for the whole world that will add up to a ridiculous amount of tiles in total.
What is the best way to generate such a huge area and still letting it all flow together nicely and naturally? I'm currently generating a mini map of a world to get the general layout of the world. (100x100 pixels) And I could generate all of the areas seperately based on this layout, but i'm not sure it would allow me to create larger open and natural environments.
I see 3 different options:

1) Generating the whole map at once as the game is started, everything in one go, this including all the different regions like forests, lakes, mountains etc.

2) Breaking the areas down by the type of region, for example, getting the bounds of a forest area (which spans over several tilemaps) and then generating it with more detail, and moving on to other regions after that

3) Generating the areas one by one as you enter them, meaning the world will only be fully generated once you explored it all.

I appreciate all replies a lot! It's more of a general question and I imagine there are a lot of ways to do these, so any suggestions are welcome! Maybe I have the wrong approach altogether? I'm very new to procedural map generation so I apologise if I come off as very inexperienced
Thank you!


texts: Handling latency in realtime music/rhythm-based games

texts:
Suppose I am making a co-operative multiplayer music-based rhythm game -- two players, side by side, move their cursor/avatar left and right with their mouse and attempt to hit or dodge obstacles that are coming towards them.

The problem here is that if there is latency in the connection, say 200ms from player B, then by the time  player A receives the movement from player B, it will have been too late -- the players' position on the track will be ahead of where it was when it was sent.

There is also a problem with running them in a sort of lockstep where the two players wait for each other to acknowledge their respective inputs -- the music must continue playing without delay on both players' clients, otherwise it will sound very choppy and the player actions might not line up well with the rhythm, which isn't what we want.

How can we deal with this latency?


texts: XNA - Drawing 2D Primitives (Boxes) and Understanding Matrices in Computer Graphics

texts:
I have two issues which I wish to solve by creating 2D primitives in XNA.

In my game, I wish to have a "debug mode" which will draw a red box around all hitboxes in the game (Red outline, transparent inside). This would allow us to see where the hitboxes are being drawn AND still have the sprite graphics being drawn.
I wish to further understand how matrices work within computer graphics. I have a basic theoretical grasp of how they work, but I really just want to apply some of my knowledge or find a good tutorial on it. To do this, I wish to draw my own 2D primitives (With Vertex3's) and apply different transormation matrices to them.

I was trying to find a tutorial on drawing primitives using Direct3D, but most tutorials are only for c++, and just tell me to use XNA's Spritebatch. I wish to have more control over my program than just with Spritebatch.

Any Help on using Direct3D or any other suggestions would greatly be appreciated.

Thank you.


texts:
We have a formula of f=g+h wherein g is the path cost and h is the distance left to the goal.

Given that I only want to move my unit in 4 direction (N,S,E,W), my question is:

Can we consider h as an input?  Because we will choose what heuristic to use?  Or not because it's value is given automatically?


texts:
Is anyone aware of any code to procedurally generate star fields?

Ideally I'd like it to be physics-based so I can have realistic planets and moons.
Best would be in C++, open source, and workable with Ogre3d.

I'm not afraid of coding something from a university paper if there's nothing available.


texts:
I'm trying to create rooms dynamically by creating them in random places and checking if they do overlap each other. The idea is that if the new room intersects with another one, it must be recreated so it doesn't intersect with anyone.

This is the room creating loop:

void GenerateBasicLevel(){
    roomsList = new List<Room> ();
    int initX = 0, initY = 0;
    for (int roomsCreated = 0; roomsCreated < 10; roomsCreated ++) {
        //Room size
        height = Random.Range (minSize, maxSize);
        width = Random.Range (minSize, maxSize);
        if(roomsCreated == 0){
            initX = 1;
            initY = 1;
        }else{
            bool loopBreaker = true;
            while(loopBreaker){
                initX = Random.Range(0,mapWidth);
                initY = Random.Range(0,mapHeight);
                foreach(Room r in roomsList){
                    loopBreaker = RoomIntersects(initX - 1, initX + width +1, initY - 1,initY + height + 1,r);
                    if(loopBreaker){
                        Debug.Log ("I do intersect");
                        break;
                    }
                }
            }
        }
        roomsList.Add(new Room(initX - 1,initX + width + 1,initY - 1,initY + height + 1,floorTiles,wallTile));

    }}

This is the Intersect checker function:

bool RoomIntersects(int x1, int x2, int y1, int y2, Room cR){
        if (x1 <= cR.x2 && x1 >= cR.x1 && y1 >= cR.y1 && y1 <= cR.y2)
            return true;
        else if (x2 <= cR.x2 && x2 >= cR.x1 && y1 >= cR.y1 && y1 <= cR.y2)
            return true;
        else if (x1 <= cR.x2 && x1 >= cR.x1 && y2 >= cR.y1 && y2 <= cR.y2)
            return true;
        else if (x2 <= cR.x2 && x2 >= cR.x1 && y2 >= cR.y1 && y2 <= cR.y2)
            return true;
        else
           return false;
    }

Rooms are objects with just 4 parameters: x1,x2,y1,y2.

This is my final result, overlaping rooms:


texts:
I have a crosshair image that will lock onto enemies that are visible in the camera and will stay on the edge of the screen when the enemy is offscreen. This works until you face more than 90º away from the enemy in either direction. If facing exactly 180º from the enemy, the indicator will appear as thought the enemy were directly in front of the camera but I would like it to stick to the closest edge of the screen instead. The red crosshair is drawn onto a 2d space and positioned within the camera view.
On screen:

Slightly offscreen:

Very offscreen:

        var enemy_pos:Vector3 = enemy.global_transform.origin
        var screen_pos:Vector2 = camera.unproject_position(enemy_pos)
        var lock:TextureRect = $TargetLock
        var lock_size:Vector2 = lock.texture.get_size()
        var crosshair_center:Vector2 = crosshair.rect_position + crosshair.rect_size * 0.5

        var direction_to_enemy := (enemy_pos - camera.global_transform.origin).normalized()
        var direction_facing := -camera.global_transform.basis.z

        # currently unused, > 0 = target within 90º rotation
        # var facing_target = direction_facing.dot(direction_to_enemy)

        var screen_width = ProjectSettings.get_setting("display/window/size/width")
        var screen_height = ProjectSettings.get_setting("display/window/size/height")

        screen_pos -= lock_size / 2
        screen_pos.x = clamp(screen_pos.x, 0, screen_width - lock_size.x)
        screen_pos.y = clamp(screen_pos.y, 0, screen_height - lock_size.y)

        lock.set_position(screen_pos)

I can understand the issue, but my vector math in 3d space is not good enough to solve this issue.


texts: How to load a text file from a server into iPhone game with AS3 in Adobe AIR?

texts:
Im creating an iPhone game with Adobe AIR, and I want to be able to load a simple text msg into an dynamic text box on the games front screen from my server (and then be able to update that text file on the server, so it updates automatically in the game after the game is on the app store) How would I go about acheiving that? is it as simple as using a getURL? are there any specifical issues with trying to do this on the iPhone via AIR that I should be aware of?

Thanks for any advice.


texts: Is it normal that "Game.Run" in XNA uses a lot of resources?

texts:
I have been using the visual studio profiler to optimize my game. I have noticed that the Game.Run method is eating through 93.6% of the overall game resources.

Is this because all of the other functions are called by it in the game? Or is there a problem? I am quite new to the VS profiler and have in the past not used such applications to assist in optimizing.


texts: offset texture attached to frameBuffer to render panorama

texts:
I would like to pre-render horizon of large landscape to texture and than paste it as cylindrical screen around the camera (to accelerate rendering of distant details)

Easiest would be make 8-gon screen uv-mapped to 4096x512 pixel frambuffer texture and render from 8 angles of camera with frustum 360/8=45 degrees wide (each angle mapped to different tile of framebuffer texture).

like this

But as far as I know output framebuffer texture is always mapped to whole framebuffer i.e. to whole camera frustrum. Is that right? Is there a way how to choose mapping for frambuffer output texture?


texts: How to manage changing Z-Index in an Entity-Component-System?

texts:
If got an Entity Component System based game-project (like classic zelda).

The Player as well as Enemys are Entities with sprite- and
tranform-components.
The Weapons are also Entities with sprite- and tranform-components.
The player and the Enemies can pickup weapons.
Weapons got an ParentComponent so they will be rendered realtive to
the Carrier-Entity.
There is a script/system for that.
No everytime an player/enemy walks upwards, the weapon must rendered BEHIND/under
the carrier for the illution, that the player walks to the top of the
screen.
I will do this by switching the Z-Index of the transform-component of the carrier with the one of the weapon.
Unfortunately, the rendering system is a Sorted-Iterating-System
which holds a sorted list of all entities with Sprite-Components so
everytime Im changing the Z-Index of an Entity, I have to force the
re-sortening of the list.
This works but sorting an entire list in
java almost every gamellop-update sounds very bad.

Is this really a good idea or should I try something else?
BTW: In practice, Im using libGdx with Ashley as the ECS.


texts: how to make cross platform 3d games using modern opengl?

texts:
How to create games that run on windows, Linux, mac os x, android, ios, wp8 etc....
using c/c++, opengl 3 or 4 and opengl es 2.0.
any tutorials or videos on how to create cross-platform 3d games.


texts: Is there any reason why there isn't a cross-platform implementation of DirectX?

texts:
Similar to how Mono can compile C# to various platforms, why isn't there an API that conforms to DirectX's specifications but can produce binaries for all platforms?

I understand that there is OpenGL but Microsoft is pushing DirectX with marketing and technologies such as XNA (which is now dead). Also, I understand that engines are supposed to support multiple backends (DirectX, OpenGL, Mantle, etc.) but that takes work..


texts:
When I build for Android or Windows, the icon is always whiteout. I've tried SVG, PNG and none of those works.

    <icon path="assets/images/default-icon.svg" />

or

    <icon path="assets/images/default-icon.png" />


texts: How to control a spaceship near a planet in Unity3D?

texts:
Right now I have spaceship orbiting a small planet. I'm trying to make an effective control system for that spaceship, but it always end up spinning out of control. After spinning the ship to change direction, the thrusters thrust the wrong way.

Normal airplane controls don't work, since the ship is able to leave the atmosphere and go to other planets, in the journey going "upside-down". Could someone please enlighten me on how to get thrusters to work the way they are supposed to?


texts: How is constant buffer allocation handled in DX11?

texts:
I'm starting with DX11 and I'm not sure if I'm doing the things right. I want to have both pixel and vertex shader program in one file. Both use some shared and some different constant buffers. So it looks like this:

Shader.fx

cbuffer ForVS : register(b0)
{
    float4x4 wvp;
};

cbuffer ForVSandPS : register(b1)
{
    float4 stuff;
    float4 stuff2;
};

cbuffer ForVS2 : register(b2)
{
    float4 stuff;
    float4 stuff2;
};

cbuffer ForPS : register(b3)
{
    float4 stuff;
    float4 stuff2;
};

....

And in code I use

mContext->VSSetConstantBuffers( 0, 1, bufferVS);
mContext->VSSetConstantBuffers( 1, 1, bufferVS_PS);
mContext->VSSetConstantBuffers( 2, 1, bufferVS2);

mContext->PSSetConstantBuffers( 1, 1, bufferVS_PS);
mContext->PSSetConstantBuffers( 3, 1, bufferPS);

The numbering of buffers in PS is what bugs me, is it alright to bind random slots to shaders (in this example 1 and 3)? Does that mean it still uses just two buffers or does it initialize 0 and 2 buffer pointers to empty?

Thank you.


texts: How to create a 2D ocean effect in cocos2dx and box2d for iphone, android, windows phones

texts: Currently my game needs a top ocean view. Can this ocean effect done using box2d? or should I dive into write my own physics (liquid/water simulation). Ideas and suggestions are welcome.


texts: Game designers need math as one of their tools for designing game, unfortunately I can't find one book concentrate on this topic. I know there's math book about game programmer, but designer need different math sub-branch knowledge like probability, game theory etc. And most important is examples tell us how to use these math knowledge as our powerful tools. Is there some books or articles available talk about this topic? Thanks in advance.


texts: Setting relative anchor point via matrix

texts:
The page at https://webglfundamentals.org/webgl/lessons/webgl-2d-matrices.html provides an example for rotating around the center of the image:

// make a matrix that will move the origin of the 'F' to its center.
var moveOriginMatrix = m3.translation(-50, -75);

Similarly, the library I'm using (gl-matrix), provides an ability to rotate around an origin vector:

  fromRotationTranslationScaleOrigin [...] Creates a matrix from a quaternion rotation, vector translation and vector scale, rotating and scaling around the given origin

However, I'd like to generically set a rotation vector based on the relative local transform - e.g. something like giving [0.5,0.5, 0] as the origin parameter to fromRotationTranslationScaleOrigin() and have it always rotate around the center.

Would this require handling it somewhere else in the pipeline? (e.g. after composing with the perspective matrix) - or are there some best-practices ways of handling this?

I'd also like a matrix to allow centering within another's world matrix but that's a different question I guess :)


texts: How do I get the mouse position relative to the window, not the whole screen?

texts:
I am developing an XNA game. I run it in window mode.

I need to handle mouse events, but when I use the Mouse class from Xna.Framework.Input.Mouse, I get the the mouse position on the whole screen.

I use this code:

MouseState state = Mouse.getState();
Point position   = new Point(state.X,state.Y);

Rectangle hitbox = new Rectangle(180, 410, 14, 14);

if (area.Contains(mousePosition))
{
    //fire event
}

How do I detect the mouse position within the current game window?


texts: Textures in Unity3D appear with lower quality than in Photoshop

texts: I made game assets that look great in Photoshop, but they look like crap when I import then into Unity and run the game.  Why?


texts: OpenGL Is High Efficiency For Large Number of Vertices Necessarily Highly Efficient For Low Numbers of Vertices

texts: To test my program, I rendered hundreds of times more vertices than the program will ever actually have (about 5000 vertices total for the exaggerated version). The exaggerated program lagged when using GL_FLOAT and did not when using GL_SHORT. What I'm wondering is if this optimization (and other optimizations) actually uses less energy than using GL_FLOAT for low numbers of vertices (since I read that some GPUs need to emulate integer functionality and I'm not sure if the increased speed is just because the float version passed some kind of memory limit (which it seems like it did, because lag immediately ended upon removing an exact number of vertices in the float version))). I'm using OpenGL es 1.1 right now, but advice for any version would be greatly appreciated.


texts:
I have a Fantasy F1 Website, currently users select their teams using dropdown menus.  It works OK but isn't as user friendly as I would like.

I would like to implement a drag and drop type of system, there's jQuery code out there that would go part of the way to allowing me to do this:

http://jqueryui.com/demos/draggable/

But I am not sure about how to integrate that into PHP and MySQL, my jQuery skills are limited!

I'd also need to stop them spending more than a certain amount of money, each driver has a value and the teams can only spend a certain amount of money.

There's also limits for example you can only pick a driver once, but you can have three different drivers.

Finally, how would you decide that the user had picked their team, I don't want a submit button as that kind of defeats the object of the exercise!

Thanks for any advice, I don't expect anyone to write the code for me but some pointers would be greatly appreciated.


texts:
I have this in my loop , it works but I get verry low fps and game is working in slow motion :

while (!done)
    {
        //Check for events
        done = processEvents(window, &player);
        updateLogic(&player);

        sprintf(buffer, "SCORE: %d", player.currentScore);

        textSurface = TTF_RenderText_Solid(font, buffer, color);
        text = SDL_CreateTextureFromSurface(renderer, textSurface);

        SDL_QueryTexture(text, NULL, NULL, &textW, &textH);
        SDL_FreeSurface(textSurface);

        doRender(renderer, &player);
        SDL_DestroyTexture(text);
    }

I think I need to update those 2 only when score is changing , not every frame..and I don't know how to do it.

textSurface = TTF_RenderText_Solid(font, buffer, color);
text = SDL_CreateTextureFromSurface(renderer, textSurface);