texts: Unity3D : Unity fails to detect null objects

texts:
im instantiating an object which is gonna play the background music for my game. On the Awake() function I check if there is a gameobject with the tag "MusicPlayer" on it, and if there isn't any I instantiate a prefab (the music player prefab with the tag "MusicPlayer" on it).

Now my issue is this :

It keeps instantiating the prefabs even if there is one or more music players(objects with the "MusicPlayer" tag on them). Why is this happening ?

Here is my code :

var musicPrefab : Transform;

function Awake()
{
    if(GameObject.FindWithTag("MusicPlayer") == null)
    {
        Instantiate(musicPrefab,transform.position,transform.rotation);
    }
}

I also have a script that makes the music player not be destroyed upon the level reload. This is the script :

function Start()
{
    DontDestroyOnLoad (gameObject);
}

Thank you for your time, I hope I was clear enough.


texts:
I am creating a card based game and I am stuck on an animation detail.
My question is I need an animation to shuffle the deck, a animation for dealing and  an animation for drawing.
My question is should I create the animations in Unreal Engine or would I create them in blender. I know traditionally with characters and other animations you would create them within blender. However I am unsure in this instance as we are talking about simply shuffling, dealing, and drawing cards.


texts: Structuring game world entities and their rendering objects

texts:
I'm putting together a simple 2d tile-based game.  I'm finding myself spinning circles on some design decisions, and I think I'm in danger of over-engineering.  After all, the game is simple enough that I had a working prototype inside of four hours with fewer than ten classes, it just wasn't scalable or flexible enough for a polished game.

My question is about how to structure flow of control between game entity objects and their rendering objects.  Should each renderer have a reference to their entity or vice-versa?  Or both?  Should the entity be in control of calling the render() method, or be completely oblivious?

I know there are several valid approaches here, but I'm kind of feeling decision paralysis.  What are the pros and cons of each approach?


texts: Problem in nested parent-entity relationship in ecs

texts:
In the given flow, the character is the parent entity, gun is child of character and bullet is child of gun. I've got a component called NodeComponent which has the storage of child entities and a NodeSystem that iterate the children then update its position relative to its parent. The problem is when the iteration reach to the bullet, it takes some time to update the bullet position. So when I move the parent the bullet is noticeable. How do I handle the parent-child relationship transformation without losing or slowing down the update from top to bottom?

Character >>
             Gun >>
                    Bullet


texts: Clipping speed when turning without using aggressive drag

texts:
I have a Unity project in which I want to control a player in a similar way to Source games, and so far I am clipping each input to the speed in the player's coordinates, by using
transform.InverseTransformDirection( GetComponent<Rigidbody>().velocity )

after which I pass each of the player's input vector direction through this function:
private float FLSMF ( float aInputVelocity, float aMaximumVelocityOnAxis, float aSpeedOnAxis ) {
    if ( Mod( aSpeedOnAxis ) >= aMaximumVelocityOnAxis ) {
        if( Sign( aSpeedOnAxis ) != Sign ( aInputVelocity ) ) {
            if ( Mod( aSpeedOnAxis + aInputVelocity ) > aMaximumVelocityOnAxis ) {
                return Sign ( aInputVelocity ) * ( aMaximumVelocityOnAxis + Mod( aSpeedOnAxis ) );
            }
            return aInputVelocity;
        }
        return 0;
    }
    if( Mod( aSpeedOnAxis + aInputVelocity ) > aMaximumVelocityOnAxis ) {
        return Sign( aInputVelocity ) * ( aMaximumVelocityOnAxis - Mod( aSpeedOnAxis ) );
    }
    return aInputVelocity;
}

There is only one problem: whenever I turn and strafe and walk forwards or backwards, the speed increases dramatically. I tried solving it by comparing each processed velocity axis to the velocity rotated by the difference in the rotations between the last 2 FixedUpdate's. So far nothing worked, aside from driving the drag factor through the roof.
My best guess is that when turning, the unclipped X axis of the vector bleeds into the Z axis when turning, which can't add anything, but cant stop the X axis from interfering because the forward key is pressed.
There is no issue when only one of the input axis are used, the speed remaining consistent when turning.
I tried to implement this function especially so I don't have to use any drag, to allow the player to be flung by other things, like grapples and explosions (this issue is present irrespective of said external factors).
If you want to, I will share the entire code, but it's messy and I don't think it would help.
Any ideas how to solve it?
Edit: yes, I have normalized the input vector. The speed increases to more than triple of the maximum, in as few as 2 turns.


texts: How can I easily model semi-realistically human movement and collision in a 2D game?

texts:
I am writing a sports simulation game in which the simulated players will interact physically with each other (i.e. tackle, push, bump...) as well as do individual actions such as changing direction of motion quickly in response to a changing game state.

At the moment all movement occurs with no inertia and infinite acceleration (so each step of the game loop the player can move at their top speed in whatever direction they want, regardless of their current motion). This has been sufficient to develop the main parts of the player AI, but it's time to get a little more realistic. The game has a cartoony look and feel so it doesn't need to be perfectly realistic, but player movement and interaction should give a semblance of reality.

So, how could human movement be summarized in a few key restrictions? I've toyed around with setting maximum acceleration and turning rates, as well as a momentum/inertia model for dealing with player collisions, but the game ends up looking like it's played by a bunch of bumper cars, rather than people (i.e. these restrictions and collision model describe cars on a slippery surface, not bipeds).


texts: How can I check if a player-drawn line follows a path?

texts:
I want to draw an invisible path that the user must follow.  I've stored that path as points.  When a player draws a line, how can I test if it follows the path I've stored?

Here's an example for tracing the letter A.

if((traitSprite.getX()<=Invisible.X  && traitSprite.getX()>=Invisible.X )){...}

(traitSprite is a sprite.)


texts: Seeking an C/C++ OBJ geometry read/write that does not modify the representation

texts:
I am seeking a means to read and write OBJ geometry files with logic that does not modify the geometry representation. i.e. read geometry, immediately write it, and a diff of the source OBJ and the one just written will be identical. Every OBJ writing utility I've been able to find online fails this test.

I am writing small command line tools to modify my OBJ geometries, and I need to write my results, not just read the geometry for rendering purposes.

Simply needing to write the geometry knocks out 95% of the OBJ libraries on the web.

Also, many of the popular libraries modify the geometry representation. For example, Nat Robbin's GLUT library includes the GLM library, which both converts quads to triangles, as well as reverses the topology (face ordering) of the geometry. It's still the same geometry, but if your tool chain expects a given topology, such as for rigging or morph targets, then GLM is useless.

I'm not rendering in these tools, so dependencies like OpenGL or GLUT make no sense.

And god forbid, do not "optimize" the geometry! Redundant vertices are on purpose for maintaining oneself on cache with our weird little low memory mobile devices.


texts:
In our game, we set the acceleration due to gravity to the appropriate value of 9.8 m/s^2. Although physically correct, it feels more like moving around on the moon.. It feels about right at a value of 16 m/s^2. Has anyone else experienced this? Is it only because we don't have motion blur, or sound to give the apparent feeling of speed?
Is it OK to just to set it to 16 m/s^2 if it feels right?


texts: How to know when graphics driver or card changes

texts:
I'm about to start work on implementing GLSL binary shader compilation and I was curious how to handle the cases when the shaders need to be recompiled, such as when the driver (or perhaps even the graphics card itself) changes. Are there any mechanisms out there to do these types of things, or is this just a "delete the shader cache folder if you update your driver" type of thing? I did a quick search on here and Google and didn't see anything that looked promising.

Edit: or am I just ignorant and GL will let me know when a recompile is necessary?


texts: When using Unity 5, is there a way to print/save/identify the last n lines of code that were executed at a specific point?

texts:
So, here is what I am after. Is there a way to identify which were the last n lines of code that were executed in Unity 5 (with C#) at a given point of the game?

I know I can use Debug.Break() to set break points to help identifying problematic parts of the code. However, when the codes escalate and multiple functions interact, it is sometimes difficult to identify what came immediately before the break point.

Therefore, my question. Is there a way to retrieve the lines of code that were executed for instance before a break point?


texts: FBX exported from C4D and imported into Unity creating new materials

texts: When importing a FBX model created in C4D, unity is creating new materials for certain meshes. For example, I have a material in C4D applied to my model called Metal. When imported into unity a new Material called Metal.1 is created and assigned to the mesh. I have no idea why this is happening.


texts: Handling commands or events that wait for an action to be completed afterwards

texts:
Say you have two events: Action1 and Action2. When you receive Action1, you want to store some arbitrary data to be used the next time Action2 rolls around. Optimally, Action1 is normally a command however it can also be other events. The idea is still the same.

The current way I am implementing this is by storing state and then simply checking when Action2 is called if that specific state is there. This is obviously a bit messy and leads to a lot of redundant code. Here is an example of how I am doing that, in pseudocode form (and broken down quite a bit, obviously):

void onAction1(event) {
    Player = event.getPlayer()
    Player.addState("my_action_to_do")
}

void onAction2(event) {
    Player = event.getPlayer()

    if not Player.hasState("my_action_to_do") {
        return
    }

    // Do something
}

When doing this for a lot of other actions it gets somewhat ugly and I wanted to know if there is something I can do to improve upon it.

I was thinking of something like this, which wouldn't require passing data around, but is this also not the right direction?

void onAction1(event) {
   Player = event.getPlayer()
   Player.onAction2(new Runnable() {

       public void run() {
           // Do something
       }

   })
}

If one wanted to take it even further, could you not simply do this?

void onPlayerEnter(event) { // When they join the server
    Player = event.getPlayer()
    Player.onAction1(new Runnable() {

       public void run() {

           // Now wait for action 2
           Player.onAction2(new Runnable() {
               // Do something
           })

       }

    }, true) // TRUE would be to repeat the event,
             // not remove it after it is called.
}

Any input would be wonderful.


texts:
The title might not be precise. Let's say I have one material consisting of vertex and pixel shader, another one consisting of vertex, geometry and pixel shader, and yet another one consisting of vertex, hull, domain and pixel shader. I use these 3 materials (shaders) for 3 different objects. If I want to render all 3 objects in one frame can I just apply the first material, render the first object, apply the second one, render the second object and the same with the third one? Is there any restriction to "mixing" shader types this way?

I think there isn't but I'm asking because I'm getting a strange bug in my application. I have 1 material using only vertex and pixel shader and another one using tessellation (vertex, hull, domain and pixel). When I render only 1st object everythings works fine. If I render only 2nd object everythings works fine, as well. But when I try to render both in one frame my application seems to freeze/crash and I get system notification that my graphics card driver crashed. Am I using shaders incorrectly or should I just look for some bug in my code?

Update:

When I assigned a tessellation shader to my first object as well and tried to render both objects... it worked. Or at least it didn't crash like before. And it's a different shader (material) but with the same stages (vertex, hull, domain, pixel) as the other object's material.

Again - is there any restriction to mixing tessellation shader with non-tessellation one?

Update:

Found the culprit - my tessellation shader (vertex, hull, domain and pixel) set 4 stages as active and my other shader (vertex and pixel) used only 2. But I never disabled the unused shader stages (hull and domain) which caused the crash. Still, the main question was "Is it ok to mix shader stages?" which Sean's just answered.


texts: Why isn't my world coordinate mapping back to the proper local coordinate?

texts:
I'm using XNA and am having a simple issue which I can't figure out. I'm just messing around and want to get a firm grasp of local/world space coordinates.

        Matrix rotateCharacter= Matrix.CreateRotationZ(MathHelper.ToRadians(45.0f));

        Matrix moveCharacter = Matrix.CreateTranslation(new Vector3(10,10,0));

        Matrix multMat =Matrix.Identity * rotateCharacter * moveCharacter ;

        Matrix WorldToB = Matrix.Invert(multMat);

        Vector2 worldCoord = new Vector2(10, 10);
        Vector2 worldToB = Vector2.Transform(worldCoord, WorldToB);

So all I'm doing here in my example is initially rotating my sprite's local axis around the world origin and then translating it out into world space. Thus, a world space coordinate of something like (10,10) would be 0,0 (my pixel's starting coordinate) in the local space (worldToB should be (0,0)). However, this is not occurring I guess as my inverted matrix is incorrect. Can anyone give me an answer of what I'm doing wrong exactly?


texts: Utility of submesh class in a 3d game engine?

texts:
I've read somewhere that we use sub mesh for being able to give different materials to one mesh. But why not simply do this with scenegraph ?

I mean you have a car mesh, and instead of using submeshes for windows, wheels etc... We could have one car node which would be composed of child nodes ( wheel, window ) with differents meshes and materials.

What's the utility of submeshes while there is scenegraph ? I've noticed that in Ogre3D there is both scenegraph ( SceneNode class ) and a mesh/submesh system, why ?


texts:
I'm changing to bilateral blur for my SSAO  implementation, just wondering how people usually combine the two passes - do you just add them together, or average, or something else?
I happen to be using Vulkan but don't think that should affect the answer too much.


texts: Can both High poly model go with a low poly scene?

texts: I'm in the process of developing a game, and I've found a model that would go perfectly for the character. However, the scentre I already have is low poly and I can't find a good enough high poly to go with it. So tell me whether or not I should I should carry on with the art I have or find a low poly model.


texts: How should an object that uses composition set its composed components?

texts:
After struggling with various problems and reading up on component-based systems and reading Bob Nystrom's excellent book "Game Programming Patterns" and in particular the chapter on Components

I determined that this is a horrible idea:

//Class intended to be inherited by all objects. Engine uses Objects exclusively.
class Object : public IUpdatable, public IDrawable {
public:
    Object();
    Object(const Object& other);
    Object& operator=(const Object& rhs);

    virtual ~Object() =0;

    virtual void SetBody(const RigidBodyDef& body);
    virtual const RigidBody* GetBody() const;
    virtual RigidBody* GetBody();

    //Inherited from IUpdatable
    virtual void Update(double deltaTime);

    //Inherited from IDrawable
    virtual void Draw(BITMAP* dest);

protected:
private:
};

I'm attempting to refactor it into a more manageable system. Mr. Nystrom uses the constructor to set the individual components; CHANGING these components at run-time is impossible. It's intended to be derived and be used in derivative classes or factory methods where their constructors do not change at run-time. i.e. his Bjorne object is just a call to a factory method with a specific call to the GameObject constructor.

Is this a good idea? Should the object have a default constructor and setters to facilitate run-time changes or no default constructor without setters and instead use a factory method?

Given:

class Object {
public:
    //...See below for constructor implementation concerns.
    Object(const Object& other);
    Object& operator=(const Object& rhs);

    virtual ~Object() =0;

    //See below for Setter concerns
    IUpdatable* GetUpdater();
    IDrawable* GetRenderer();

protected:
    IUpdatable* _updater;
    IDrawable* _renderer;
private:
};

Should the components be read-only and passed in to the constructor via:

class Object {
public:
    //No default constructor.
    Object(IUpdatable* updater, IDrawable* renderer);
//...remainder is same as above...
};

or Should a default constructor be provided and then the components can be set at run-time?

class Object {
public:
    Object();
//...
SetUpdater(IUpdater* updater);
SetRenderer(IDrawable* renderer);
//...remainder is same as above...
};

or both?

class Object {
public:
    Object();
    Object(IUpdater* updater, IDrawable* renderer);
//...
SetUpdater(IUpdater* updater);
SetRenderer(IDrawable* renderer);
//...remainder is same as above...
};


texts:
I have been struggling with this fairly basic issue: To make a game over menu appear upon death.

I am making a 3D game in Unity, where you, the player, must control a sphere with the basic controls: W, A, S, D and ↑, ↓, ←, →. It is a game where you must "drive" the ball and pass a broad variety of obstacles, where you must lead the ball to fall into a confined box where, if within it, you ultimately win the game.

I have already implemented the Main Menu, Pause Menu and the fundamental gameplay components. I just need to figure out how to make it so the player can actually lose the game. The most important aspect of a game.

I have not a clue on how I can make this.

The player is on a platform, as are the obstacles etc. I have made in my game 2 bridges you must cross over, on which below it is nothing. So, if you slide off a bridge, you will basically die, as there is nowhere else to go upon falling. I want to make it so that when you fall from the actual platform, or the map, falling into the "abyss", you will die, on which I would like a game over screen to appear, there being a play again button, and a button that will quit the game.

I basically have no clue how to make any of this a reality. If possible, I would be delighted if anyone could develop a script for this. Java Script or C#, doesn't matter. If you can assist me in anyway, please do.


texts:
On my screen I want to display two controllers, one to turn around the character (We'll call itLook) and one to move the character (We'll call it Move).
I have a line registering a ControllerListener Which implements InputProccessor.
My question is if I can use the ControllerListener to receive input from both Move and Look at the same time.
In case that wasn't clear, I mean I want the player to maneuver the map using both controllers, not just one.


texts:
I'm just starting to get into 3D programming with Direct3D. What version of D3D should I pick up?

11 looks pretty neat, but 9 and 10 still seems to be pretty present. Given the current state of the game development industry, which version does it make more sense to start using?


texts: Is quadrilinear texture sampling hardware supported?

texts:
If you have a volume texture with mipmaps, GL_LINEAR_MIPMAP_LINEAR texture sampling will perform quadrilinear texture sampling.

Is that implemented in hardware like bilinear texture sampling is? Or does the driver just do two trilinear texture samples and interpolate those results for you?

Is trilinear sampling even supported by hardware?


texts: Generating a grid (Array) of Tetris Pieces

texts:
What I want to do is quite self explanatory. Just like the title states. I want to code something that will generate a grid which contains is filled of Tetris pieces.
However some conditions must be met :

Having no empty holes for the final grid (all sections of the grid filled)
Having no blocks sticking out (e.g. a long tetris block sticking out of the square grid)

I have tried to approach the problem using my way since the methods used online are too complicated for me.
The first idea I had was to use a 2D array which each row will be gone through to have some generation algorithm. The next row will depend on the previous row. Such as making a 2x2 block. It will check if the current row position is empty, if it is then it will check if the previous row is empty. If it is then it will make keep note that this point is being used. But if the previous block is already been used. It will check what kind of block it is and depending on what information is on that position. It will either be a connecting piece of just a blank piece.

The second idea i have in mind is similar to the first idea.
That is, it will also go through each row but this way is dependent on maths.
Lets say we have a 10x10 grid. We can say each row is made of 10 blocks. And from that we can say each tetris shape is made of miniblocks. E.g the 2x2 block is made of 2x2 small blocks.
So from this we can, go through the first row and for the first 2 blocks of the 10 keep note in the array that we want to generate the a 2x2 tetris block. And we can go to the next row and we know that the previous row there was a 2x2 tetris block that is need to be finished creating in the second row. And so we repeat this to try and get a filled grid of tetris blocks.

Sorry I am not good at explaining/implementating/reading code. Sorry for the inconvenience.
I have been suggested by some people to look at Tetris AI. And maybe use the AI to solve my problem. But I'm not good with reading other people's code. Plus it isn't in the language i understand. And i dont have anyone to go through the code with me.
 So i prefer to use my own idea since i know what is going on. But i don't know how to implement the code.

If there is anyone who could help me in any way it would be my honor.
Thank you in advance.


texts: What kind of project management should a solo developer project use?

texts:
I’m working by myself on a game project whose development could be seperated into 3 independent parts (map generation, the “overworld” engine and the battle engine), but as the development progresses, I am not sure how I should be dealing with the management of this project, especially concerning these 3 points:

Is it worth it using a version control system, since I’m working solo?
Should I use a formal method to register planned features / bugs (I just remember what needs to be done for now)
The most important question: how can I know what to develop first? Now that the very basics are done, I know the list of features to code but I don’t know in which order I should do it.


texts:
I'm making a platform sidescrolling game. All I want to do is to detect if my character is on the floor:

function OnCollisionStay (col : Collision){
    if(col.gameObject.tag == "Floor"){
        onFloor = true;
    } else {onFloor = false;}
}
function OnCollisionExit (col : Collision){
    onFloor = false;
}

But I know this isn't the accurate way. If I hit a cube with a "floor" tag, in the air (no matter if with the character's feet or head) I would be able to jump.

Is there a way to use the same box collision to detect if I'm touching something from a specific side?


texts: Map handling - Indoors/Outdoors and loading large maps

texts:
I have two questions regarding the handling of maps.

Question 1. My map will consist of outdoor enviroments as well as dungeons, houses etc. How would I go on about connecting the outdoors with the indoors?

My simple solution to 1.
Put everything in the same map file and when you, for example, walk through a door the player will be "teleported" to the indoor location. Let's say the outdoor location of the door is at the coordinates (10,10) and the indoor enviroment of the given house is at (1000,1000) the player's coordinates will be set to (1000,1000) when he walks through the door.

Is this optimal or is there a better way of doing this?

Question 2. My map will consist of a bunch of larger cities and paths connecting these cities. Obviously the map will be pretty big and I'm not sure if I can keep the whole map in memory. How would I go on about creating an effective map management system?

My simple solution to 2.
Have the map consist of "chunks" with x*x tiles where x is the number of tiles that will fit in the screen. I would then load the chunk the placer is currently in and also the surrounding chunks but nothing else. When the player moves to a new chunk the map will load new surrounding chunks etc.

Would this be a more effective way of handling the map than loading the entire map into memory? Advantages of this way is that I don't have to keep the entire map in the memory but it will take time to dynamically load each "chunk" when it's needed thus creating loading time.

Any improvements to my rudimentary solutions is gladly appreciated.


texts: Unity generates changes in GitHub on saving scene

texts:
So, here is my problem.

First I have a look at the changes in the repository which I am working with.

Initially there are no changes:

Then I open up Unity, i don't make any changes and just save the scene:

I then go to GitHub Desktop and suddenly there are a lot of changes appearing which I did not make:

How can I avoid that?

The files which are getting changed are .prefab files.


texts: Access TrackAsset from PlayableAsset in unity

texts:
I have a PlayableAsset which samples a configuration randomly and then creates a Playable based on that configuration. Now, I want to include a gender configuration which is set inside a TrackAsset-Parameter (Serialized Field on the TrackAsset).
How can I access this parameter now?
[TrackClipType (typeof (OverlayAsset))]
[TrackClipType (typeof (RandomOverlayAsset))]
[TrackBindingType (typeof (MoveOverlayManager))]
public class OverlayTrackAsset : TrackAsset
    {
        [SerializeField]
        public IntParameter GenderParameter;
    }

public class RandomOverlayAsset : PlayableAsset
    {
        public static System.Random SYSRAND = new System.Random();

        //[ScriptableObjectDropdown (AppendNextDrawer = true)]
        [SerializeField]
        private MoveOverlay[] Overlays;

        [SerializeField]
        private float OverlayProbability = 1;

        public override Playable CreatePlayable (PlayableGraph graph, GameObject owner)
        {
            ScriptPlayable<OverlayPlayable> playable = ScriptPlayable<OverlayPlayable>.Create (graph);
            OverlayPlayable overlayPlayable = playable.GetBehaviour ();
            double rand = SYSRAND.NextDouble ();
            if (OverlayProbability >= rand)
            {
                for (int i = 0; i < 10; i++) //Monte Carlo
                {
                    int selected = SYSRAND.Next (0, Overlays.Length);
                    MoveOverlay selectedOverlay = Overlays[selected];
                    if ((selectedOverlay.GenderSpecific &  ????GenderParameter???.Value()) == 0){ // ??? How to define GenderParameter???
                        continue
                    }
                    overlayPlayable.Overlay = selectedOverlay;
                    break;
                }
            }
            else
            {
                overlayPlayable.Overlay = null;
            }

            return playable;
        }
    }


texts:
I am currently working with CAVE systems and I'm looking into hooking up a pre-exisiting game engine in one. I know this is possible through Unity and the Unreal Engine as there is already research out there showcasing that it has been done.

Right now, I have not decided upon one game engine to use and I'm currently looking around and researching if it is possible with the likes of CryEngine and Valve's Source Engine. The one issue that I am going to face, however, is getting the image to correctly render across all four of the monitors / screens.

Thusly, as a result I have two questions:

Does anyone know of any good research / books on distrubuted rendering? It doesn't need to be specificly for games, just the topic in general would be very useful
Does anyone know if other developers have managed to get Source and the CryEngine to run in a CAVE system? Through all my research I haven't been able to find anything on this, but then my google skills aren't the greatest.

If anyone could spare the time to answer these questions, I'd be extremely greatful.

Thanks.


texts: Should the camera's rotation value be clamped?

texts:
I noticed that when writing a camera for my 2D game that the camera rotational value of -6 and 6 is equivalent to 0.

That is, -6 = -12 = -18 = -24 = 6 = 12 = 18 = 24.

I was wondering if it was considered good practice to always keep the rotational value between -6 and 6, like so:

    public float Rotation
    {
        get
        {
            return rotation;
        }
        set
        {
            rotation = value;

            if (rotation <= -6 || rotation >= 6) rotation = 0;
        }
    }

Does it matter either way?


texts: Should I send the entries using a tickrate? Netcode Authoritative Server

texts:
I am developing a 2D platform and shooting video game in Unity 2D with authoritative logic / physics on the server (The physics server is also developed in Unity to be able to use the box2D library on both the client and the server).
Currently I am working on the basic communication functionality between the client and the server using socket to send the client's inputs to the server and executing the physics on it. And this is where I find myself with a question that I can't solve after searching a lot on google and forums.
When should you send the client's inputs to the server? Setting a delivery tickrate or each time the user clicks on the controls?
As I have analyzed on my own, what seems more efficient at first is to send the inputs to the server each time the client presses one of the game controls. And on the other hand that the server sends the clients the status of the game (player movements, changes in physics, etc.) using a tick rate.
This is a diagram of the communication and behavior that I am developing:

As you see this operation. Should I also set a tickrate on the client?
Thank you very much.


texts: How to calculate acceleration and deceleration

texts:
I have a car with speed x, and can accelerate at a rate of 0.5 m/s^2, and can decelerate at a rate of -0.1 m/s^2. Maximum speed is 20 m/s.
To accelerate the car speed, at each frame I need to do:
car.CurrentSpeed = car.CurrentSpeed + 0.5

To decelerate the car speed, at each frame I need to do:
car.CurrentSpeed = car.CurrentSpeed - 0.1

Is this correct?
I have found this answer which suggest the following speed formula:

Speed += ((MoveDirection * MaximumSpeed) - Speed) * AccelerationFactor
Where:

Speed is the current speed the entity is travelling at on the current
axis.
MoveDirection is the direction the entity is trying to travel in
on the current axis, 1 is forward, 0 is still and -1 is backwards. All
values in between are allowed.
MaximumSpeed is a constant determining
the fastest that the entity can travel on the current axis.
AccelerationFactor is a constant between 0 and 1 that represents the
rate of acceleration and deceleration. 1 is instant, and 0 will never
move.

Using the same formula then:
To accelerate:
car.CurrentSpeed += ((MoveDirection * 20) - car.CurrentSpeed) * 0.5

What would be the move direction? Can it be the heading?


texts: How to figure out if I'm on the right path

texts:
I'm a software developer from Israel, I've been programming professionally since 2011, my first job was in HP software and lasted 2 years after which I decided that I want to pursue my dream in working in game development and focusing on C++.
for a year an a half I worked for a mobile kids games company, doing small mobile games for kids using C++ and Cocos2d-x.
Unfortunately I was laid off last December and since then I've been focusing my free time on studying Unreal engine 4, studying openGL and computer graphics and working on my C++ skills while searching for a new job.

I'm very passionate about computer & console games and especially the rendering part and my dream job would be to work on AAA games and to be a graphics programming specialist.
The problem is that there aren't any AAA game companies in Israel so I started looking at positions in Europe and also in other jobs that involves computer graphics but aren't necessarily in games.

Last week I got a job offer for a small start up making a game in the "Clash of Clans" genre, the company seems nice, its not my type of games but I'm sure it presents all kinds of challenge but my biggest concern is the fact that the game is implemented in Unity and Python, which are two technologies I'm not so crazy about.

I wonder if I should take the job or keep looking for something that involves more C++,OpenGL,DirectX etc.
Do you think that taking a Unity\Python job will take me too far from the OpenGL\DirectX goal I'm trying to reach?

I know that good software developers aren't supposed to limit themselves to a certain programming language but I think its good to become really professional at something specific instead of changing language every 2 years.
I guess its being a specialist vs. a generalist question.

What do you guys think? should I take this job even though I have some concerns? should I keep searching? maybe doing some freelance work in the meantime?

any advice will be appreciated.


texts: How can I use one method and also switch between a coroutine and the main method?

texts:
Now I'm using two methods, one as StartCoroutine and one not.

What I want to do is to have just one method and when I set the StartCoroutine variable to true or false when the game is running I want it to switch between the coroutine and the main. Is there a simple way to do it with one method and not two, if not, how do I achieve this?

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

public class Grid : MonoBehaviour
{
    public GameObject gridBlock;

    public int worldWidth = 10;
    public int worldHeight = 10;
    public bool StartCoroutine = false;

    public float spawnSpeed = 0;

    void Start()
    {
        if (StartCoroutine)
        {
            StartCoroutine(GenerateGridSC());
        }
        else
        {
            GenerateGrid();
        }
    }

    private void GenerateGrid()
    {
        for (int x = 0; x < worldWidth; x++)
        {
            for (int z = 0; z < worldHeight; z++)
            {
                GameObject block = Instantiate(gridBlock, Vector3.zero, gridBlock.transform.rotation) as GameObject;
                block.transform.parent = transform;
                block.transform.name = "Block";
                block.transform.tag = "Block";
                block.transform.localPosition = new Vector3(x, 0, z);
            }
        }
    }

    IEnumerator GenerateGridSC()
    {
        for (int x = 0; x < worldWidth; x++)
        {
            yield return new WaitForSeconds(spawnSpeed);

            for (int z = 0; z < worldHeight; z++)
            {
                yield return new WaitForSeconds(spawnSpeed);

                GameObject block = Instantiate(gridBlock, Vector3.zero, gridBlock.transform.rotation) as GameObject;
                block.transform.parent = transform;
                block.transform.name = "Block";
                block.transform.tag = "Block";
                block.transform.localPosition = new Vector3(x, 0, z);
            }
        }
    }
}


texts:
I'm learning the basics of combat system by doing it myself, but there is a logical problem I can't figure out. It's on Unity2D, using C#.

Collider2D[] enemiesToDamage = Physics2D.OverlapCircleAll(attackPosition.position, attackRange, attackableLayer);
            for (int i = 0; i < enemiesToDamage.Length; i++)
            {
                enemiesToDamage[i].GetComponent<DamageEnemy>().TakeDamage(damage);
            }

This is what my attack function looks like, this script is assigned to every enemy in my game and functions properly. But the problem is I want to assign every enemy a unique function whenever they take damage, like jumping back or flying away, and I can't do it in one script. What do I do?


texts: Blur Shader: Can I use one Framebuffer for the horizontal and vertical pass?

texts:
I have set up my blur shader with the following header:

#version 400
in vec2 texCoord;

uniform sampler2D u_texture;
uniform vec2 resolution;
uniform float radius;
uniform vec2 dir;

layout (location = 0) out vec4 out_color;
void main() { *some code*; out_color = vec4(*some code*); }

The vertical pass is working well but I would like to use the same Framebuffer for both passes.

My idea was to create Color Attachment1 and Color Attachment2. In the first pass, Attachment1 is the target (out_color) attachment. Now I want the second pass to bind Attachment1 to the sampler2D (u_texture) and write the resulting pixels (out_color) into Attachment2.

If there is any possibility to read from one Attachment and write to another, please let me know.

Thanks in advance!


texts: Camera rotation around point, but without centering

texts:
Let's say i have the following:

Point somewhere in space
Camera with position and orientation (up, right, forward)

I want to rotate camera around the point, but also keep this point in same place on screen. So, if point was on (32, 32) on window, after rotation i want it to still be on (32, 32).

I've seen How can I orbit a camera about it's target point? , and it was somewhat helpful. I needed code to rotate point around arbitrary axis (camera's up and right), so i used this resource.

Problem is, i got something like numerical errors and my camera started to wander weirdly when rotating around camera's both up and right (it seems fine when i rotate only around one of them).

I tested my implementation with code:

Matrix m1=MatrixRotate(Vector(-1, -1, 1),  33);
Matrix m2=MatrixRotate(Vector(-1, -1, 1), -33);
Vector a=Vector(-1, -1, -1);
Vector c=a;

c=m1*c;
c=m2*c;
printf("%f %f %f %f\n", c.x, c.y, c.z, c.w);

And got:

-1.028036 -0.960396 -1.124331 0.000000

It worked fine when rotation axis was something 'normal' like (1, 0, 0) or (0, 0, -1).

So, how else can i rotate camera around point, while keeping said point in same point on screen?


texts:
this is what i do to blit FBO onto screen in ViewController:

[m_Context presentRenderbuffer:GL_RENDERBUFFER];

but i need something like glSwapBuffers, so that i can call it somewhere from the engine code ( which is cpp ) - to refresh the screen in special cases - is this available for iOS / how can i implement it - if i can at all..


texts: Instancing with empty data, or varying vertex counts?

texts:
I am new to game development, having only developed a few games before, in 2D space, but with 3D rendering.

I have implemented instancing before, but this is only my 2nd time doing it. I have a question regarding instancing.

To do instancing, I have a geometry buffer having a vertex declaration (for instance) 32 VertexPositionColor elements. This is because I have a few elements with 32 vertices in them.

I am rendering all elements as linelists. However, there are some elements in the list that doesn't have 32 vertices. I would like to include these in the instancing render process too.

So my final question is, what happens if I (for instance) fill out 8 of the vertices with their indexes, but then still send all the 32 vertices into the instancing shader? Is it possible?

Is there a better approach to be able to instance all kinds of elements, with various vertex counts?


texts: Still having problems using Json data in Unity

texts:
I have the following classes and json file, i thought id followed the documentation exactly but I am clearly wrong. Can anyone see why I get an error just saying : INVALID VALUE in my unity console:

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

[Serializable]
public class DataReader
{
public float[] x;
public float[] y;
public float[] z;
}

GameController:

public class GameController : MonoBehaviour {
    public static GameController instance;

DataReader dataReader;

private string gameDataFileName = "level1.json";

private void Awake()
{
    dataReader = JsonUtility.FromJson<DataReader>(gameDataFileName);
    instance = this;
}

void Start () {

    // create level:
    print("DATA: " + dataReader.x[0]);
}

}

and the json is stored in StreamingAssets folder (I also tried a copy in Resources folder):

{
"x": [{1},{1},{1},{1}],
"y": [{1},{1},{1},{1}],
"z": [{1},{2},{3},{4}]
}


texts: Difference between 'max distance' and 'radius' in Physics.SphereCastAll

texts:
I needed a way to check for all gameobjects within a set sphere of my player object.

I found Physics.SphereCastAll which will return a RaycastHit[], exactly what I wanted. But, I am having trouble understanding the method signature/docs.

Basically, it's the two things in the title I am confused on right now:

From Unity docs:

radius    - The radius of the sphere.
maxDistance - The max length of the sweep.

Is 'max length of the sweep' a measurement of time (or degrees?)? I would have thought the length would be the same as the radius (or at least you could calculate it from the radius) but it obviously isn't what I think length means.


texts: Calculating step length with dividing a number that returns digits after the decimal point

texts:
How can I get rounded numbers from calculations that returns digits after the decimal point? And all the numbers together will be the number that is divided from.

Explanation:

I am currently working on an JavaScript tilebased-game with sprite animations.

Some walk/run sprites are less or more.

Let's say I have 3 walk sprites for walking down.

1: Look down

2: walkanimation sprite

3: walkanimation sprite

The distance between each tile, let's say, is 16 pixels.

16 pixels divided by 3 sprites is 5.33333.

So if the player walks down, each animationsprite wil move 5.3333 pixels down. That will end up that the player is at 15.999 pixels when the walk animation is done.

That will become not nice if the player walks down many times.

So I want to dynamically get the steps length which end up at the number that is divided from.

In this example:

16 / 3

Will return:

1/3: 6

1/3: 5

1/3: 5

Total: 16 pixels walked


texts: (Unity) Shortest way to instantiate an object and obtain it script

texts:
Normally I use

ScriptName script = ((GameObject)Instantiate(
        Resources.Load("Prefab"),
        new Vector3(x, y, z),
        Quaternion.identity
    )).GetComponent<ScriptName>();

It is a little too long and too much of brackets, so I wondering if there is any other way to get instantiated object's script without break it in two statements.


texts: I have decided to make a simple engine for a new game I'm working on, and now, I'm wondering: what are the essential features of a 2D game engine? Or, a game engine in general?


texts: For PC game development with Visual Studio, how do AAA developers reconcile their dozens-of-GB games with VS's 4 GB memory limits?

texts:
As far as I understand it, Visual Studio is the de-facto standard for Windows development in C# and C++, but it is limited by the fact that it's a 32-bit application and thus only has access to 4 GB of RAM for loading projects (Microsoft wrote a blog post 10 years ago explaining(?) why there is no 64-bit version). AAA games, however, are dozens of GB large, and even after factoring out the assets (which VS doesn't load), still amount to quite a bit of executable code.

Are AAA developers able to work within those limits for PC development, or do they use other IDEs that have 64-bit versions?

(I am aware that Visual Studio often uses out-of-process facilities for actually building and running projects, but the IDE itself is 32-bit and a lot of its functions, such as CodeLens, run in process).


texts: Best place for learning how to write games in Unity3d

texts: What's the best place for tutorials & other learning resources for unity3d?


texts: Implementing The Command Pattern - Undo And Entity References

texts:
I am trying to implement a replay/undo system for a turn based strategy game I am currently working on. A sample move could go as follows:

1. A players select a pawn and gives it an attack command.
2. The attacked unit dies.
3. The dead unit is removed from the map and the controlling player.
4. The controlling player takes some damage.
5. The attacking unit gains a survivor strength power up for the remainder of the game.

The rest of the game plays similarly to a Fire Emblem type game, but the point is a single command like attacking yields multiple effects to various game entities.

Eventually I want to make the game networked, but for now everything is local play.

After doing some research, I came across several resources discussing the command pattern and feel it is the solution to my replay and undo system. I ended up using an interface similar to https://gamedev.stackexchange.com/a/37684/41499 but I am confused on some of the implementation details.

Do I make commands to update each component of my game separately (i.e. AtkUnitCmd, RmvUnitFromMapCmd, RmvUnitFromPlayerCmd, InflictPlayerDmgCmd, etc.) or should my AtkUnitCmd handle all updates of entity state internally?
How do I handle dead units? I can store a reference to the dead unit, but this would likely need to change when networking is implemented as the object itself would not be transmitted over the network correct?
Each command has some animation involved for example when a unit moves an animation needs to play. I may choose to skip the animations while other times leave them on. Do I bake the animations into the commands themselves or should I separate the animation code and call it somehow when the command is played?

Any thoughts?


texts:
I'm new to game dev,and I just trying to create my first game,a simple pong game.But i can't handle the keyboard input.

This is what i got :

const Uint8 * keystates = SDL_GetKeyboardState(NULL);
SDL_PumpEvents();

if (_keystates[SDLK_s])
    std::cout << "Down is pressed";

But if i run it and press 's',nothing ever happens.

if (_keystates[SDLK_RETURN])
    std::cout << "Return is pressed";

For this one is working just when i press 'j'... Yeah,right?

And more,if I add this line :

if (_keystates[SDLK_DOWN])
    std::cout << "Bla bla..";

My game crashes,what do you think is the problem?Thank you.


texts: Unity augmented reality app doesn't work on android

texts:
I am pretty new to unity and augmented reality applications. I use unity 2019.4.4f1 and my project is very simple as you can see in the screenshot below:

I am using Wikitude plugin for image tracking and the image i am using as the marker is the Jack of Clubs card as you can see in the assets. The project works fine when i press play and use my laptop's webcam , but when i build the project for android (unity 2019 automatically uses Gradle to build the project) and install the .apk file in my android phone, all i see on my phone screen when i open the application is:

As you can see the phone camera doesn't work and it gets stuck in this screen. How should i fix it? Does it have to do something with Gradle? I haven't tried using unity version 2018 to build it using the "Internal" build option. Anyways that's just my own thought and i might be wrong, but the final question remains which is how this problem can be fixed?
By the way i don't build the .apk file directly from the unity engine. I use the export option in unity to get a gradle project folder then i use that in Android Studio to build the final .apk file. The reason that i don't use unity to build .apk is that it gives errors and doesn't work for me so this is the solution i found for it.
Update: I debugged the application and it seems that the application needs camera permission to work, this is my debugging log:
07-22 17:47:16.908: E/Unity(32483): On Camera Error
07-22 17:47:16.908: E/Unity(32483):         Error Code: 1000
07-22 17:47:16.908: E/Unity(32483):         Error Domain: com.wikitude.camera.android
07-22 17:47:16.908: E/Unity(32483):         Error Message: Permission denied. Make sure to have camera permissions before trying to access the camera.
07-22 17:47:16.908: E/Unity(32483):
07-22 17:47:16.908: E/Unity(32483): (Filename: ./Runtime/Export/Debug/Debug.bindings.h Line: 35)

I'm pretty sure that it didn't ask for camera permission, how should i allow the permission if it's not asking?


texts: Calling update oct-function (only if changed)

texts:
Issue: How is the best way to update my units position on the oct-tree, I'm struggling with the logic, specifically when It changes oct, tree, I want it to pop itself of its previous oct-tree, and it it to its new oct tree, but only if it has changed since last frame-

update is called every frame, Is there a way to call it only when it knows the oct-tree of the current unit has changed,instead of doing comparison every second, as this throws exception error because can only pop it off the list once?

void EntityUnit::updateoct(worldspace &gameworldspace)
{
    int store = current_oct;
    for (auto a = gameworldspace.wspace.begin(); a<gameworldspace.wspace.end(); ++a)
    {
        if (checkwithinbounds(CVector3{unit_x,unit_y,unit_z}, (*a).w_origin, (*a).w_sideLen))
        {
            current_oct = (*a).num;
            //if oct-tree has changed since last call execute this
            // push this onto (a*).cObjs
            for (auto i = gameworldspace.wspace[current_oct].cObjs.begin(); i <  gameworldspace.wspace[current_oct].cObjs.end(); ++i)
            {
                if ((*i) == this)
                {
                    // Pop this off the last oct-tree object list
                }
            }
        }
    }
}

   void EntityUnit::update(float updateTime, worldspace &gameworldspace)
{
    int aliveswitch = unit_alive;
    if (this->UnitModel != nullptr)
    {
        (*UnitModel)->SetPosition(unit_x, unit_y, unit_z);
        (*UnitModel)->LookAt(0, 0, 0);
        (*UnitModel)->Scale(unit_model_scale);
        (*UnitModel)->ScaleZ(0.1);
        // << "current oct :" << current_oct << endl;
    }
    switch (aliveswitch)
    {
    case (0):

        break;
    case (1):

        move(updateTime);
        updateoct(gameworldspace);
        //cout << "Hit" << endl;
        break;

    default:;
    }

}


texts:
I appear to be awful at describing the question so I'll try and describe the problem.

I want to add a random amount of heads to my creatures but I want to be able to determine several things.
a) The minimum number of possible heads
b) The maximum number of possible heads
c) The probability of the number being high/low within the above values.

So i could add heads like so:
addHeads(5, 10, 0.5); // should produce creatures with "around" 7.5 heads but they could have anywhere from 5 to 10.

So random number generation isn't the problem, but controlling and actually using them in a game is. :D


texts: Why does my world generation code perform poorly on large inputs?

texts:
I'm writing some code to procedurally generate some islands in real time. The idea is to choose some points for each chunk, and for each tile calculate the distance from those points, then combine it with a Perlin Noise to decide  if it will be water or land. Anyway here's the code:

local function number()
    local n = math.random()
    if n < .4 then
        return 0
    elseif n < .8 then
        return 1
    end
    return 2
end

Just a custom weighted random function, used to choose how many points will be in each chunk.

chunks = setmetatable({}, {
    __index = function(tab, x)
        local xtab = setmetatable({}, {
            __index = function(xtab, y)
                local xs, ys = x * 32, y * 32
                local islands = {}
                for i = 1, number() do
                    islands[i] = {x = math.random(xs, xs + 31), y = math.random(ys, ys + 31), r = math.random(16, 32)}
                end
                xtab[y] = islands
                return islands
            end})
        tab[x] = xtab
        return xtab
    end})

This block just initializes the chunks table, setting its metatable so that if a non existing chunk is being called, that chunk gets initialized by choosing a number of points the chunk will contain, and for each point choose its position inside the chunk and its range.

However here's the buggy code:

function generatechunk(x, y)
    local xs, ys = x * 32, y * 32
    for xm = xs, xs + 31 do
        for ym = ys, ys * 31 do
            for xc = x - 1, x + 1 do
                for yc = y - 1, y + 1 do
                    local points = chunks[xc][yc]
                    for p = 1, #points do
                        local po = points[p]
                        local d = math.max(0, math.min(math.sqrt((po.x - xm) ^ 2 + (po.y - ym) ^ 2) / po.r, 1))
                    end
                end
            end
        end
    end
end

It isn't even completed yet. Basically what it should do is choosing for each tile if it will be sea or land by combining the Perlin Noise value and the influences of the points of the chunks around its chunk.

But here's the bug: if I call (for testing) generatechunk(n, n) for n <= 0, it executes in little to no time. But as n increases I get results of about n seconds of execution. Why is it?


texts: How can I get game objects and prefabs to recognize modifications in enum values from scripts in the scene window

texts: I have made a script with several properties and enums that I attached to an empty game object. I am making changes to the values within the inspector, since they a public. How can I get the scene window to recognize these changes as they occur?


texts:
I'm trying to write a game where player picks where they are going by just mouse-clicking on that position and it goes there (just like RuneScape's point-and-click mouse interface).

I'm trying to get it working on the jme3test.bullet.TestWalkingChar example.

I've tried:

character.setLocalTranslation(
    cam.getWorldCoordinates(inputManager.getCursorPosition(), 0.0f));

Also tried:

Vector3f worldCoordinates = cam.getWorldCoordinates(inputManager.getCursorPosition(), 0.0f);
Vector3f localCoordinates = null;

character.worldToLocal(worldCoordinates, localCoordinates);
character.setLocalTranslation(localCoordinates);

and:

Vector3f worldCoordinates = cam.getWorldCoordinates(inputManager.getCursorPosition(), 0.0f);
Vector3f localCoordinates = null;

character.setLocalTranslation(character.worldToLocal(worldCoordinates, localCoordinates));

But it's just teleporting the player to some unrelated coordinates.

Any ideas?

BTW: If there's a complete example on how to do that, it'd be great. I don't care about game engine - I prefer jME3 but it doesn't really matter for me.


texts: Need help understanding ms to fps for a Unity animation

texts:
I'm trying to create an animation in Unity (2018.1.1f1) and can't understand how to proceed.

I have a 3 sprites which I need to order like so : 1 2 3 2 (then repeat).
The first and third sprites should have a 640ms delay and the second sprite should be 80ms.

In the animation window, I don't understand how to translate that into fps on the animation timeline.

What sample should I choose and where I need to put each sprites on the timeline to get the 640 and 80ms specified?


texts: How do I portray characters with a bum leg properly in an action game like Devil May Cry, without making him a liability?

texts:
Right now, I'm designing a character for a 2D action platformer game. The problem is that said character has a bum leg due to an accident a few years prior to the game's setting, but was the first one to be dragged into a dungeon formed by the newly developing incident, and had to escape on his own.

What I've thought about until now about this:

The character will move slower than the normal movement speed, cannot double jump, and have a lower jump height than the normal jump height.
However, he would use a sword that doubles as a retractable whip, allowing his melee attacks to have a wide coverage. Said sword-whip has low damage by default, however.
There's also that his melee attacks are less focused on launching enemies upwards and more focused on knocking them back - and maybe apply bleeding (non-elemental damage over time).
He would also have a shotgun that can be 'charged' to maximize the damage output, very much like the Gunslinger Style Shotgun in DMC3 and 4.

My problem is that this character will be one from around eight (for now), and the other seven characters don't have such a disability - two of them I intend to have the ability to glide mid-air.

The game will have a feature of switching between three characters chosen to engage the other dungeons, so he can be switched out for sections that require double jumping, but I'm not sure that's an optimal solution, especially considering the lower damage his weapon deals (making him a non-optimal pick for boss battles).

Should I just make each character fulfill a specific niche in terms of mobility options, melee attack options, and ranged attack options? How does one design the map and bosses for these cases, without making it seem like giving him too much of a break?

P.S. Can a grappling hook be involved, without ending up making him the best option to navigate the map (like refreshing it only after landing)?

EDIT: I also have a thought of integrating this grappling hook into the sword-whip, being able to pull enemies towards him, or him towards them. Is it possible to use this as a melee charge attack? Because I still think that it doesn't feel right.


texts:
How do I render Hindi text in Libgdx using any font? For example, I want to render the word "प्रकार".

Here is what I have, so far:

import com.badlogic.gdx.Game;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.freetype.FreeTypeFontGenerator;

public class MyGdxGame extends Game
{
    SpriteBatch spriteBatch;
    BitmapFont font;
    OrthographicCamera camera;
    String text, text1;
    private byte[] myBytes = { (byte) 0xe0, (byte) 0xa4, (byte) 0xa8,
            (byte) 0xe0, (byte) 0xa4, (byte) 0xbf, (byte) 0xe0, (byte) 0xa4,
            (byte) 0xb6, (byte) 0xe0, (byte) 0xa5, (byte) 0x89, (byte) 0xe0,
            (byte) 0xa4, (byte) 0xa4 };
    private String myName = new String(myBytes, Charset.forName("UTF-8"));
    private String hindiStr = "ँंःअआइईउऊऋऎएऐऍऒओऔऑकखगघङचछजझञटठडढणतथदधनऩप"
            + "फबभमयय़रऱलळऴवशषसहािीुूृॆेैॅॊोौॉ़्।०१२३४५६७८९INV";

    @Override
    public void create()
    {
        camera = new OrthographicCamera();
        camera.setToOrtho(false, 400, 640);
        spriteBatch = new SpriteBatch();

        FreeTypeFontGenerator generator
                = new FreeTypeFontGenerator(Gdx.files.internal("font/mangal.ttf"));
        FreeTypeFontGenerator.FreeTypeFontParameter parameter
                = new FreeTypeFontGenerator.FreeTypeFontParameter();

        // +FreeTypeFontGenerator.DEFAULT_CHARS; The characters the font should contain
        parameter.characters = hindiStr;
        parameter.size = 15;

        font = generator.generateFont(parameter);
        font.setColor(1.0f, 0.0f, 0.0f, 1.0f);

        generator.dispose();

        text = "शुभ प्रभात";
        text1 = "आप का स्वागत है";
    }

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

        spriteBatch.setProjectionMatrix(camera.combined);

        spriteBatch.begin();
        font.draw(spriteBatch, "सूक्ष्मजीवों के विभिन्न प्रकार ", 10, 30);
        font.draw(spriteBatch, myName, 10, 100);
        spriteBatch.end();
    }

    @Override
    public void resize(int width, int height)
    {
        camera.setToOrtho(false, width, height);
    }

    @Override
    public void dispose()
    {
        font.dispose();
        spriteBatch.dispose();
    }
}


texts: Will SDL_DestroyRenderer() destroy every texture created with it?

texts:
The documentation on the SDL wiki states:

  Use this function to destroy the rendering context for a window and free associated textures

So does this mean that every texture I create will be freed (even those still used) or only the ones that were destroyed manually (by using SDL_DestroyTexture())?


texts:
I am trying to make Basic Touch behaviors for my game where i want to

Pan Camera by Single finger touch.
Zoom Camera by pinch With two fingers ofCourse.
Rotate Camera by two fingers rotation.
Rotate camera around an object and move only in x axis using Two fingers y position.

i am having problem in making camera to rotate on X axis but i am not able to do it correctly plz help and it also conflicts with my pan behaviour when input is given

   public float comfortZoneVerticalSwipe_A = 10;
    public float comfortZoneHorizontalSwipe = 50;
    public float minSwipeDistance = 100;

    public float startTime;
    public Vector2 startPos;
    public float maxSwipeTime = 0.5f;

    if (Input.touchCount > 0 && Input.touchCount < 2)
            {
                Touch touch = Input.touches[0];
                switch (touch.phase)
                { //following are 2 cases

                    case TouchPhase.Began: //here begins the 1st case
                        startPos = touch.position;
                        startTime = Time.time;

                        break; //here ends the 1st case

                    case TouchPhase.Moved:

           Vector3 offset = transform.right * (-Input.touches[0].deltaPosition.x * 0.9f) * panSpeed + transform.up * (-Input.touches[0].deltaPosition.y * 0.9f) * panSpeed;
                                Vector3 newTargetOffset = Vector3.ClampMagnitude(offset, maxOffsetDistance);

                                transform.position += newTargetOffset - targetOffset;

                        break;

                    case TouchPhase.Ended: //here begins the 2nd case

                         float swipeTime = Time.time - startTime;
                        float swipeDist = (touch.position - startPos).magnitude;

                              Debug.Log("Mathf.Abs(touch.position.x - startPos.x) " + Mathf.Abs(touch.position.x - startPos.x));

                            Debug.Log("swipe Time " + swipeTime);

                            Debug.Log("swipe Dist " + swipeDist);

                            if (Mathf.Abs(touch.position.x - startPos.x) < comfortZoneVerticalSwipe_A && swipeTime < maxSwipeTime && swipeDist > minSwipeDistance && Mathf.Sign(touch.position.y - startPos.y) > 0)
                        {

                            Debug.LogWarning(transform.rotation.x);
                            transform.rotation = new Quaternion(transform.rotation.x - 5 , transform.rotation.y , transform.rotation.z , transform.rotation.w);
                           if (transform.rotation.x > 0.2)
                           {
                                transform.Rotate(Vector3.right, -2);
                            }
                                Debug.LogError(transform.rotation.x);
                            Debug.LogWarning("Up");

                        }
                            else if (Mathf.Abs(touch.position.x - startPos.x) > comfortZoneVerticalSwipe_A && swipeTime > maxSwipeTime && swipeDist > minSwipeDistance && Mathf.Sign(touch.position.y - startPos.y) < 0)
                            {

                                 transform.rotation = new Quaternion(transform.rotation.x - 5 , transform.rotation.y , transform.rotation.z , transform.rotation.w);
                                if (transform.rotation.x < 0.9)
                                {
                                    transform.Rotate(Vector3.right, 2);
                                }
                                print("down");

                            }

                        break; //here ends the 2nd case
                }
            }


texts: Open GL Android frame-by-frame animation tutorial/example code

texts:
My first question was asked wrong, so I need to ask again :)

I found out, that I will have to do an OpenGL animation for my Android game. The closest (known) example is Talking Tom (but I don't know how they did the animations).

I have large PNGs which I would like to put into a animation. For example - 30 PNGs 427×240px at 8 FPS.

I know some things already about Open GL, but I am used to learn from example code. And it is quicker that way (so I don't need to invent hot water all over again :)). Does anybody has any points to direct me?


texts: Unity Physics Simulation - Limitations / Inaccuracies? Bounciness of a ball (pool/snooker balls etc)

texts:
I am playing with Unity physics engine. I have a pool table and a cue ball. Both have Physic Materials. If I start the game, with the ball floating about 1m above the table, it falls and bounces (bounce depends and happens only if Physic Material, bounciness property is set to something above 0.5 ish.). But I have to have it between 0.8-0.9 bounciness for it to look anything like realistic. And even so after a bounce or two it stops and it doesnt look at all real.

The mass of the ball is set to 0.17.

I've tried playing about with the two Friction properties, but these seem to have no effect on this test. (currently I have these all set to 0.1)

Like I say, it will bounce two or even three times but then seems to come to an abrupt stop.

Also if you set the bounciness of both materials to about 0.9+ the bounces sometimes get larger after a smaller bounce before it.

Does anyone have experience playing with similar physics in Unity? And if so, what else should i change to tweak the behaviour.

The table itself doesn't have a rigidbody, only the balls do.

As an added complication to the question, wouldnt the ball roll slightly in some direction after it had bounced, rather than just bouncing directly up and down?

thanks


texts: What revenue models exist for online games?


texts:
I also use Farseer Physics and Artemis ECS. Here is RenderingSystem Process method:

    public override void Process(Entity entity, TransformComponent transformComponent, RenderingComponent renderingComponent)
    {
        Vector2 dimension = transformComponent.Dimension * camera.ScalingFactor;

        Vector2 rotationOrigin = new Vector2(dimension.X,dimension.Y)/2;

        Vector2 renderingPosition = new Vector2(1, -1) * transformComponent.RenderingPosition * camera.ScalingFactor + camera.BitmapPosition;

        Rectangle rectangle = new Rectangle((int)(renderingPosition.X), (int)(renderingPosition.Y), (int)dimension.X, (int)dimension.Y);

        spriteBatch.Draw(renderingComponent.Texture, rectangle,
            null, Color.Wheat, -transformComponent.Rotation,rotationOrigin, SpriteEffects.None, 0f);
    }

That's what i get:

And that's what I get if

Vector2 rotationOrigin = new Vector2.Zero;

What's the reason for such a weird behavoir of rotationOrigin parameter and how to correctly rotate the sprite around its center?


texts: Handling different aspect ratios on a 2D dodging game

texts:
I've been making a game where the player is on the ground and has to dodge objects falling to the ground. Since I'm using libGDX (But the question still applies to any other language/framework), The game will have to handle both desktop and mobile apps.

I'm trying to make the game fit vertically into any aspect ratio while making it fair, but this is my first time trying to deal with this, and I'm looking for a good way to do this. My game has 3 main regions: The game, the data (Health/coins), and the GUI (Pause button). Here are my ideas so far:

Horizontal: Game in the center with everything else on the sides

Vertical: Game on the bottom with data on top

Everything else: No room for GUI on sides/bottom, GUI on top of game

I've seen other questions similar to this, but none of them cover a game similar to this type.


texts: How to enable Unity related syntax highlighting with VSCode?

texts:
I'm using VSCode, not VisualStudio for Unity scripting. VSCode has syntax highlighting for C#, which works fine, but all the Unity related stuff like Vector3 doesn't get any highlights. I know, that you can change somehow the files, but I can't even find the C# folder in my extensions folder (There is everything else like cpp, css etc. just no c#). Would be great if someone could lead me to the folder location and how to add keywords for the highlighting.

Here is a screenshot, where you can see that float is highlighted, but Transform not.


texts: Why is spacebar causing Unity to fire last OnClick() event

texts:
I have a turn based roguelike with input issues that are driving me nuts.

I use the Unity Input/GetAxis() for keyboard input. I recently added a skill bar with clickable buttons that pass an int parameter to a simple class when clicked.

The problem I am having is that the OnClick() event, on the last button that was clicked, fires whenever the SPACE bar is pressed.

What could cause this? I do not have space set on any of the input Axes (I did originally and both the axes attached to SPACE and the OnClick() would fire)

Edit: The code is below. It is called by the OnClick() handler on the button in the inspector. If you run the project and press SPACE nothing happens. Then if you click a button the Debug.Log fires. Then press SPACE again and the debug fires again with the same button number as was last clicked.

public class SkillClickNotifier : MonoBehaviour
{
    [HideInInspector]
    public int SkillClicked;

    public void ButtonClicked(int skill)
    {
        Debug.Log("Button Clicked: "+ skill);
        // SkillClicked = skill;
        // GameManager.Notifications.PostNotification(this, "SkillClicked");
    }
}


texts: Actor in Stage Does Not Update the MoveTo XY Location

texts:
I am creating a game wherein an apple is being shot with an arrow. The apple's location is the XY location of the user input and the arrow actor has to move to that location using the code actor.moveto. The problem is the arrow only moves only once to the user input's direction. I know that the moveTo action of the actor is updated many times per second when I called stageArrow.act in the update method so I am wondering why the arrow only moves once. Here's my code:

appleclass.java

public class AppleClass implements Screen {

Arrow arrow;
private final MainApp app;
public Image ShotImage;

public AppleClass(final MainApp app){
        this.app = app;
        this.stageApple = new Stage(new StretchViewport(app.screenWidth,app.screenHeight , app.camera));
        this.stageArrow =new Stage(new StretchViewport(app.screenWidth,app.screenHeight , app.camera));

        arrow = new ArrowClass(app);

    }

@Override
    public void show() {

        InputMultiplexer inputMultiplexer = new InputMultiplexer();
        inputMultiplexer.addProcessor(stageApple);
        inputMultiplexer.addProcessor(stageArrow);
        Gdx.input.setInputProcessor(inputMultiplexer);

        arrow();

    }

    public void arrow(){
        arrow.isTouchable();
        stageArrow.addActor(arrow);
        arrow.addAction((moveTo(Gdx.input.getX(),Gdx.input.getY(),0.3f)));   //===> only executes once.
        arrow.addListener(new InputListener(){
            public void enter(InputEvent event, float x, float y, int pointer, Actor fromActor){

            if (Gdx.input.isTouched()){
                        ShotImage.setVisible(true);

                          }
                        }
                    });}

}

@Override
    public void render(float delta) {

        Gdx.gl.glClearColor(0, 0, 0, 1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
        update(delta);
}

public void update(float deltaTime){

        stageApple.draw();
        stageArrow.draw();

        stageApple.act(deltaTime);
        stageArrow.act(deltaTime);

    }

ArrowClass.java

public class ArrowClass extends Actor {
    MainApp app;
    AppleClass appleClass;
    public Texture arrowTexture;

    public ArrowClass(final MainApp app){
        this.app = app;
        arrowTexture = new Texture("medievalarrow.png");
        this.setSize(arrowWidth, arrowHeight);
        this.setTouchable(Touchable.enabled);
        this.setBounds(app.screenWidth*0.45f,0,arrowWidth,arrowHeight);
        this.setOrigin(0,0);

}
@Override
    public void draw(Batch batch, float parentAlpha) {
        super.draw(batch, parentAlpha);

        final float delta = Gdx.graphics.getDeltaTime();
        this.act(delta);

        app.batch.begin();
        app.batch.draw(arrowTexture, getX(),getY(),getWidth(),getHeight());
        app.batch.end();

    }
}

Any help will be highly appreciated. Thanks.


texts: How to compensate for moving objects with client side prediction?

texts:
I'm implementing a game server that supports Star Control-like melee. So you have ships flying and shooting, with super simple velocity/acceleration/dampening physics to drive movement.

I've read Valve, Gafferon and Gambetta and implemented Gambetta's algorithm for client prediction:

Client prediction works on the player ship by updating its position from the server as it comes and then reapplying the yet-unprocessed-by-the-server input to the player ship.

Unfortunately, it doesn't work well for my game. I believe it has to do with the fact that Gambetta's example doesn't take into account objects that are already moving, or commands that are updated on a step by step basis. (by "step" I mean frame). So in my game the player presses up to accelerate the (already moving) ship, which continues moving on the client, sends the command to the server and usually receives the world snapshot from the server on the next step. I get something more like:

The player command runs at client step 3, but on the server its only run at server step 5. By the time the world snapshot is received by the client at client step 6, the prediction is way off, especially in faster velocities.

The crux of the problem is that the client runs the command at step 5, but the server runs it at step 6. I thought about maybe sending the client step with the command, and have the server roll back and re-run the command with the client time step. That might lead to a slew of other problems though - like what happens to commands received since the rollback, or how cheating clients can exploit by changing the sent step.

Reading and watching videos like this one from Google mentions a different approach, where you gradually change player position to match that of of the snapshot over a few steps.

My questions:

Can you make Gambetta's algorithm work with constant step movement? Or is it conceptually incompatible with my game?
Is gradual interpolation over steps the correct way to go then? If so, how do you interpolate an already moving object from the client position to match that which was just received from the server?
Can these methods, gradual interpolation and Gambetta's algorithm work in tandem, or are they mutually exclusive?


texts:
I'm coding a 3D game for a project using OpenGL and I'm trying to do tile collision on a surface.

The surface plane is split into a grid of 64x64 pixels and I can simply check if the (x,y) tile is empty or not.

Besides having a grid for collision, there's still free movement inside a tile.

For each entity, in the end of the update function I simply increase the position by the velocity:

pos.x += v.x;
pos.y += v.y;

I already have a collision grid created but my collide function is not great, i'm not sure how to handle it. I can check if the collision occurs but the way I handle is terrible.

int leftTile = repelBox.x / grid->cellSize;
int topTile = repelBox.y / grid->cellSize;
int rightTile = (repelBox.x + repelBox.w) / grid->cellSize;
int bottomTile = (repelBox.y + repelBox.h) / grid->cellSize;

for (int y = topTile; y <= bottomTile; ++y)
{
    for (int x = leftTile; x <= rightTile; ++x)
    {

        if (grid->getCell(x, y) == BLOCKED){
            Rect colBox = grid->getCellRectXY(x, y);
            Rect xAxis = Rect(pos.x - 20 / 2.0f, pos.y - 20 / 4.0f, 20, 10);
            Rect yAxis = Rect(pos.x - 20 / 4.0f, pos.y - 20 / 2.0f, 10, 20);

            if (colBox.Intersects(xAxis))
                v.x *= -1;

            if (colBox.Intersects(yAxis))
                v.y *= -1;

        }
    }
}

If instead of reversing the direction I set it to false then when the entity tries to get away from the wall it's still intersecting the tile and gets stuck on that position.

EDIT: I've worked with Flashpunk and it has a great function for movement and collision called moveBy. Are there any simplified implementations out there so I can check them out?

EDIT2: I've figured out a solution, you can check the answer below


texts: convert view space normal to world normal

texts:
Im writing a shader that uses Unity's _CameraDepthNormalsTexture to get both the view normal and depth values. I return a color from my fragment shader equal to the normal values sampled.

I am having problems converting the view normal into a world normal so that when my camera tilts around, the fragment colors shouldnt change.

How can turn my view normal-> world normal in my fragment shader? Relevant code is marked with TODO below:

Shader "Custom/DepthNormal"{
    Properties {
       _MainTex ("", 2D) = "white" {}
       _HighlightDirection ("Highlight Direction", Vector) = (1, 0,0)
    }

    SubShader {
        Tags { "RenderType"="Opaque" }
        Pass{
            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag
            #include "UnityCG.cginc"

            sampler2D _CameraDepthNormalsTexture;
            sampler2D _CameraDepthTexture;

            struct vertexOutput {
                float4 position_in_clip_space : SV_POSITION;
                float2 depth : TEXCOORD0;
                float4 scrPos : TEXCOORD1;
                float4 position_in_world_space : TEXCOORD2;
            };

            vertexOutput vert(appdata_full v){
                vertexOutput output;
                output.position_in_clip_space = UnityObjectToClipPos(v.vertex);
                //use the helper function instead of MATRIX_MVP as per documentation
                //mul(UNITY_MATRIX_MVP,float4(v.vertex,1.0));

                output.position_in_world_space = mul(unity_ObjectToWorld,v.vertex);
                //recall computeScreenPos does not divide by w, but because this is not an image effect,
                //diving by w here will WARP things unless we are completely parallel to viewing camera

                output.scrPos = ComputeScreenPos(output.position_in_clip_space);

                return output;
            }

            float4 frag(vertexOutput input) : COLOR
            {
                float3 normalValues;
                float depthValue;
                //extract depth value and normal values

                //recall computeScreenPos does not divide by w, so if you want proper screenUV for use in tex2D divide
                //xy by w
                //https://forum.unity3d.com/threads/what-does-the-function-computescreenpos-in-unitycg-cginc-do.294470/

                float2 screenUV = input.scrPos.xy / input.scrPos.w;
                //DecodeDepthNormal(tex2Dproj(_CameraDepthNormalsTexture, input.scrPos), depthValue, normalValues);
                //Alternatively:
                    DecodeDepthNormal(tex2D(_CameraDepthNormalsTexture,screenUV), depthValue, normalValues);

                 //TODO: CONVERT TO WORLD NORMAL?
                 float4 worldNormalValues  = mul(unity_ObjectToWorld,mul(UNITY_MATRIX_IT_MV, float4(normalValues,1.))); //THIS ISNT RIGHT :(

                float d = pow(depthValue,2);
                return float4(normalValues.x,normalValues.y,normalValues.z,d);
            }

         ENDCG
        }

    }
fallback "Diffuse"
}


texts:
I have a single lane road and I want cars to drive along it. I want variables such as car speed and gap lengths between cars to be changeable.

I have already implemented this simply using a Waypoint circuit along the road and spawning cars at one end of the road every few seconds, destroying them once they get to the end of the road. I am also able to change the speed of the cars.

However for choosing a gap length between cars, this implementation isn't great. I thought I could use the spawn time (e.g. 3 seconds between cars means a certain gap length) but this isn't accurate when you factor in realistic acceleration time and the speed. For instance, if the speed is 100mph and cars are spawned every 3 seconds, the first car spawned is going accelerate quickly and be a lot farther than the second car when it spawns. If the speed was 30mph with a 3 second spawn time, the cars are going to have a much smaller gap. I want to be able to predetermine what this gap is going to be regardless of the speed limit.

Any ideas how I can go about this? An idea of mine was that I could populate the road with cars, making sure that the length between the cars are the predetermined gap length and begin the simulation from there. But how do I make these cars follow the same Waypoint system? And how do I properly spawn new cars to keep a constant flow of traffic as the cars at the end of the road are destroyed?


texts: Making organic 2D tilemaps for tile based games

texts: So I have always wondered how one makes a nice (not so squarish) 2d tile map, is it possible?  all games now days I think use textured polygons...but my game engine (and engine) doesn't support that to my knowledge.  But it does support nice TMX files generated by mapeditor.org's Tiled Map Editor.  Though in my game I want nice twisting and turning caverns to traverse ... I was wondering some ideas on such a process... is it in the art style? The type of tile engine? both? So what are some common techniques?


texts:
I'm currently trying to make the fire object (created by the fireball) stick to the enemy, by specifying the enemy type and its id. I'm getting the following error:

"Unable to find any instance for object index '-4' name undefined".
Here's my fireball [collision with enemy] code:

var sp=other.speed
var dir=other.direction
var oi=other.id
var on=object_get_name(other)
with (instance_create(other.x-lengthdir_x(new_push_amount, pd),other.y-lengthdir_y(new_push_amount, pd),fire))
{
speed = sp
direction = dir
enemyid = oi
enemyname=on
}

And here is the Create,

enemyname = ""
enemyid = 0

and the Step events of fireball:

speed = instance_find(enemyname,enemyid).speed
direction = instance_find(enemyname,enemyid).direction

Maybe I'm using the wrong functional to get the instance... In any case, help would be really appreciated!


texts: What is an OO way for my input layer to act upon objects?

texts:
I'm building a top-down RPG specifically to practice Object Oriented thinking and design. I am keeping in mind coupling, single-responsibility, and so forth. One design issue that's been bugging me is how to ultimately have objects talk while maintaining the loosest coupling possible. As an example, I'm designing the input class now, which will be made up of two layers, like so:

The conundrum is that I don't know how to bridge that gap between Input and HeroActor, which is initialized from the PlayState class, which is also where the hero.update() method is called. Let's say Keyboard has just executed

public void keyPressed(KeyEvent e) {
    switch(e.getKeyCode()) {
        //Some cases

        case KeyEvent.VK_UP:
            //Assume InputEvent.INPUT1 is a defined enumeration in InputEvent
            inputHandler.passInput(InputEvent.INPUT1);
            break;

        //Some more cases
    }
}

I've basically landed here:

public class Input {

    public void passInput(InputEvent e) {
        switch(e) {
            //Some cases

            case InputEvent.INPUT1:
                ????????????????????

            //Some more cases
        }
    }

}

My ideas have been:

Pass a reference to the instance of HeroActor to the Input object, then have Input directly call the moveUp() method on the HeroActor instance.

case InputEvent.INPUT1:
    actor.moveUp();

My instinct tells me this is bad OO design as it tightly couples the two classes.
Make the instance of HeroActor global and basically do the same as above. Even worse OO design.
Write a registerInput(Input inputHandler) function in the Actor class, like so:

public class HeroActor extends Actor {

    //Existing fields and methods

    private Input inputHandler;

    public void registerInput(Input inputHandler) {
        this.inputHandler = inputHandler;
    }

Still, then the HeroActor would have to poll the inputHandler every frame to find out if any actions have applied to it.

I'm in the same situation trying to figure out how to write the collision engine without passing it specific references to the player's HeroActor instance or the dozens of EnemyActor instances in the PlayState constructor.

Any help would be greatly appreciated. My request is not for specific code, but rather common techniques for handling the many objects in a game without ending up with a god object. I've seen some material suggesting an Observer pattern being applied for things like the input layer above, but before I go too far, I'd like some feedback from the community since I've got so many different answers among all of my Googling today.


texts: Procedurally generated paths with intersections

texts:
The Problem
I've been attempting to create some procedurally generated paths for a while now, but I've reached a problem when it comes to generating the intersections of the paths.
The paths are currently "extruded" along a catmull-rom spline, I used a bezier curve before but catmull made the whole process of placing the points easier.
My plan is to have all of the path nodes as part of one big graph, so that each node has edges to other nodes. This way it will be easier to do pathfinding on the paths later on.
public class PathNode
{
    public Vector3 Position;
    public float Width;
    public List<PathNode> Edges;
}

Here's an illustration that kinda shows what i want, think of existing games like the roads in Cities skylines:

I know how generate the mesh along a curve, my biggest problem here is that i don't know how to generate the mesh at the intersections.
I've read something about creating a polygon from all of the closest vertices of an intersection, and the triangulating that polygon. but i fail to see how i would get the right vertices from the mesh, without having to calculate the distances for each of them to the intersection node.


texts: How to trigger poison effects efficiently

texts:
I'm trying to trigger poison effects at the end of each turn in a turn based game. Each Actor in battle has a list of active effects, each of which could be a poison. I simply want to Execute() all of those Poisons.

See my code below; is there a way I can combine my two queries or make them more efficient so that the moment a Poison is found, that Poison executes?

var poisonedActors =
            from Actor actor in ins.BattleParticipants
            where actor.ActiveEffects.Any(activeEffect => activeEffect is Poison)
            select actor;
var poisons =
            from ActiveEffect activeEffect in poisonedActors
            where activeEffect is Poison
            select activeEffect;
foreach (Poison poison in poisons)
            poison.Execute();

EDIT: Is this more efficient? Is there a better way to do things?

    foreach (Actor actor in ins.BattleParticipants)
        foreach (ActiveEffect activeEffect in actor.ActiveEffects)
            if (activeEffect is Poison)
                activeEffect.Execute();


texts: When I open an image from Unity in preview it's blank?

texts:
Ok, I need to know why this is and don't have the .png anywhere else. I have a texture in Unity that I need to edit in Photoshop, yet when I Reveal the image in Finder then open it in preview or photoshop, the whole thing is blank.

It is clearly not a blank image, and other images are not doing this:

What is wrong here?


texts: XNA HLSL Shader Color Swapping based on lightness

texts:
I'm trying to achieve a similar effect to the image below in HLSL.

[Ignore the inbetween state, currently I'm only trying to achieve the final phase, which is black and red]

What I tried so far is to sample based on which colors we perceive as brighter, ore more intense and separate the sampled colors to red and black based on that.

Code for what I've tried below:

    float4 PixelShaderFunction5(PixelShaderInput input) : COLOR0
{
    float4 src = tex2D(ColorMapSampler, input.TexCoord);
    float4 final = float4(0.6F,0,0,1);
    float4 final2 = float4(0,0,0,1);
    double a = 1 - ( 0.299 * src.r + 0.587 * src.g + 0.114 * src.b)/1;
    if(src.a >0)
    {
    if(a>0.5)
    {
    return lerp(src,final,limit);
    }
    else return lerp(src,final2,limit);
    }
    else return src;
}

But this doesn't seem to result in the same effect.

Could anyone suggest me possible ways to have a similar color swapping shader?

Thanks in advance.


texts:
My player sprite won't move if I use the A/D keys or the arrow keys. If I try to use them then the sprite will stretch and won't move at all. But if I try to jump before I press the A/D or left/right arrow keys then it will jump. If I press the A/D or left/right arrow keys then it will stretch again and I have to reload the game to jump again.
This is my code.
Create Event:
hsp = 1;
vsp = 0;
grv = 0.5;
walksp = 4;

Step Event:
// get player input
key_left = keyboard_check(vk_left) || keyboard_check(ord("A"));
key_right = keyboard_check(vk_right) || keyboard_check(ord("D"));
key_jump = keyboard_check_pressed(vk_up) || keyboard_check(ord("W"));

//calculate movement
var move = key_right - key_left;

hsp = move * walksp;

vsp = vsp + grv;

if (place_meeting(x,y+1,oWall)) && (key_jump)
{
    vsp = -7;
}

//horizontal collision
if (place_meeting (x+hsp,y,oWall))
{
    while (!place_meeting(x+sign(hsp),y,oWall))
    {
        x = x + sign(hsp);
    }
    hsp = 0;
}
x = x + hsp;

//vertical collision
if (place_meeting (x,y+vsp,oWall))
{
    while (!place_meeting(x,y+sign(vsp),oWall))
    {
        y = y + sign(vsp);
    }
    vsp = 0;
}
y = y + vsp;

//animation

if (!place_meeting(x,y+1,oWall))
{
    sprite_index = sPlayerA;
    image_speed = 1.5;
}
else
{
    image_speed = 1;
    if (hsp == 0)
    {
        sprite_index = sPlayer;
    }
    else
    {
        sprite_index = sPlayerR;
    }
}

if (hsp != 0) image_xscale = sign(hsp);

I don't know why this is happening.


texts: Sending a shot left/right/up/down based on directional key press

texts:
I am trying to make a top-down shooter game with similar combat to the Binding of Isaac:

when I press the up key the shot goes up
when I press the right key the shot goes to the right

I have all the rest of the code such as the point where the projectile is instantiating and the if statement to check for the button press I just want to know where I should put the vector 2 to allow me to set the direction and what to write into the vector 2

private void Update()
{

    if (Input.GetKeyDown("up"))
    {
        if (Time.time >= shotTime)

        {
            Instantiate(projectile, shotPoint);
            shotTime = Time.time + timeBetweenShots;

        }
    }

}

This is my Projectile script (at least the parts that I think would be useful)

void Update()
{
    transform.Translate(Vector2.up * speed * Time.deltaTime);
}

I realized that if I change the Vector2.up to make it say Vector2.down it would now shoot down But I need that to be able to change depending on which direction I am shooting.


texts:
I am trying to implement a simple camera mouse look.

if (Input.GetInstance().GetMouseKey(MouseButton.Middle))
{
    Vector2 d = Input.GetInstance().getMouseDelta() * 0.001f;
    camera.transform.AddRotation(new Vector3(-d.Y, d.X, 0));
}

Here is the camera matrix:

cameraMatrix = Matrix4.LookAt(myEntity.transform.Position, myEntity.transform.Position + myEntity.transform.GetForward(), myEntity.transform.GetUp());

I also tried to create camera matrix like this, but the results were the same:

Matrix4 t = Matrix4.CreateTranslation(myEntity.transform.Position);
Matrix4 r = myEntity.transform.RotationMatrix;
cameraMatrix = t * r;

Here is the rotation matrix of transform:

var x = Matrix4.CreateRotationX(rotation.X);
var y = Matrix4.CreateRotationY(rotation.Y);
var z = Matrix4.CreateRotationZ(rotation.Z);
rotationMatrix = x * y * z;

Add rotation of transform:

public void AddRotation(Vector3 rotation)
{
    if (rotation == Vector3.Zero) return;
    this.rotation += rotation;
    myEntity.ObserverOnRotationChanged();
}

Get forward method of transform:

public Vector3 GetForward()
{
    return new Vector3(RotationMatrix * new Vector4(0.0f,0.0f,1.0f,0.0f));
    //or just extract third column from matrix
}

Vertex shader:

#version 330

uniform mat4 transformMat;
uniform mat4 cameraMat;
uniform mat4 projectionMat;

layout (location = 0) in vec3 position;
layout (location = 1) in vec3 normal;
layout (location = 2) in vec2 uv;

void main(){
    gl_Position = projectionMat * cameraMat * transformMat * vec4(position, 1.0);
}

It rotates the camera around global x axis instead of local x when i look at triangle from the side.
Thanks.


texts: Does Monogame on Windows Desktop use OpenGL or DirectX by default?

texts:
if i use monogame 3.0 beta on windows desktop, does it use the directx renderer (sharpdx) or the opengl renderer by default?

if it uses directx is there away to make sharpdx call directly? thanks!


texts: Is the source code of the Source Engine available?

texts:
Is the full C++ source code of the Source Engine available?

I know the SDK is available with the purchase of a Source-based game, but my goal is to find a open-sourced game engine that includes its full implementation details for learning purposes.


texts: Performance cost of using character collider?

texts:
I am attempting to get an update to this question: https://answers.unity.com/questions/57680/should-a-character-controller-attach-with-rigidbod.html
There are conflicting answers. From my understanding since the character controller uses a collider with no rigidbody attached there will be a performance penalty.

"You should never move a Static Collider on a frame by frame basis.
Moving Static Colliders will cause an internal recomputation in PhysX
that is quite expensive and which will result in a big drop in
performance. On top of that the behaviour of waking up other
Rigidbodies based on a Static Collider is undefined, and moving Static
Colliders will not apply friction to Rigidbodies that touch it.
Instead, Colliders that move should always be Kinematic Rigidbodies."

On the other hand there is another answer that says:

"The character controller (CC) - at least as implemented in PhysX,
that is a kinematic CC - is a very specific piece of code working
alongside (but outside of) the main physics simulation (rigid body
dynamics). Although the CC do use a capsule collider, the collision is
typically performed "by hand" in the CC code rather than automatically
through the physics simulation like other colliders."

Does anyone have more insight into this?


texts: Dragging a Rigidbody2D without passing through obstacles

texts:
I have this body of code written for an object that needs to be an obstacle and another object that is draggable.  I have colliders on both and a kinematic rigidbody on the draggable object, but the obstacle is still allowing the dragged object to be dragged through it.  This is all 2d.  I'm not sure what I'm doing wrong.

The part that I'm confused on is this - when you just add a collider to the obstacle sprite and a collider and rigidbody (all 2d) to the draggable sprite, if I don't add the script above, then the draggable sprite falls due to gravity on top of the obstacle and stop there, it doesn't fall through the obstacle sprite.  However when I add the above script which has the OnMouseDrag function, and I move the draggable sprite around because now I can, it falls through the sprite.

With no script the obstacle acts like an obstacle.  With this script the it does not.

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

public class Block : MonoBehaviour
{
    public GameObject Four_Object1;
    //public GameObject clone_Four_Object1;
    //private Vector3 screenPoint;
    //private Vector3 offset;
    private Rigidbody2D rb2d;
    private Vector3 screenPoint;
    private Vector3 offset;
    private Vector3 cursorPosition;

    public void Start()
    {
        rb2d = GetComponent<Rigidbody2D>();
        GetComponent<Rigidbody2D>().isKinematic = true;
    }

    public void OnMouseDown()
    {
        screenPoint = Camera.main.WorldToScreenPoint(Four_Object1.transform.position);

        offset = Four_Object1.transform.position - Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z));
    }

    public void OnMouseDrag()
    {

        Vector3 cursorScreenPoint = new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z);
        cursorPosition = Camera.main.ScreenToWorldPoint(cursorScreenPoint) + offset;
        transform.position = cursorPosition;
    }

    public void FixedUpdate()
    {
        rb2d.MovePosition(cursorPosition);
        Debug.Log("Update!");
    }

}