texts: Should I Open/Close SpriteBatch with different settings?

texts:
I'm still new in game developpement, and I'm trying to complete my 1st game. Its a simple 2d game, but i'm trying to add lots of differents techniques in it.

It's all good when you take a single tutorial (I followed some tutorials for the screen managers, for diffuse lightning, for camera, HUD, particles, spritesheet animations, etc. )
It's all quite simple to get it to works and run in a simple game.cs file.

the problem I have is when its time to all mix it toghether. I cant find any good pointers on how I should handle the spritebatch orderings. Should I use different spritebatch, or reuse the same over and over ? I was told I need to utilise as little spritebatch as possible ...

** I KNOW i could test it and start to wonder about it only if I have a problem ... but instead I'd prefer to learn to do it right the 1st time I try it. If I get into a bigger project and this way of doing it only works on easy small 2d game ... its not much better than saying I've never done anything.

More specificly, I'm wondering if I keep my main Draw set up like this :

 graphicsDevice.Clear(Color.Black);

 spriteBat.Begin(paramteres set up for my camera);
   for each screen in screenmanager {
     screen.draw(spritebatch);
   }
 spriteBat.End();

  spriteBat.Begin(paramteres set up for my HUD);
     //draw hud stuff
  spriteBat.End();

....

and in my screens draw method ... i'll end up with :

void Draw(spritebat Spritebatch)
{
     //draw screen "normal" item affected by camera
  spriteBat.End();

  spriteBat.Begin(paramteres set up for particle);
    for each particlelist in particlemanager {
      for each particle in particleList
        particle.draw(spritebatch);
      }
    }
   spriteBat.End();

 spriteBat.Begin(paramteres set up for my light FX);
    //draw diffuse light and shadows stuff
 spriteBat.End();

 spriteBat.Begin(paramteres set up for my camera);
}

is this correct ?


texts: Screenshot always returning as a white image on iOS using robovm and libgdx

texts:
I am trying to take a screenshot for sharing on social media.  This code works on my Desktop project, but when I use it on iOS it always shows up as a white image, I am using the standard libgdx code for the screenshot factory, any suggestions?

public class ScreenShotFactory
{
public static void SaveScreenshot()
{
    try
    {
        Gdx.files.local("shot.png").delete();
        FileHandle fh;
        do
        {
            fh = new FileHandle(Gdx.files.getLocalStoragePath() + "shot.png");
        }
        while (fh.exists());

        Pixmap pixmap = getScreenshot(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight(), true);

        PixmapIO.writePNG(fh, pixmap);

        pixmap.dispose();
    }

    catch (Exception e)
    {
    }
}

private static Pixmap getScreenshot(int x, int y, int w, int h, boolean yDown)
{
    final Pixmap pixmap = ScreenUtils.getFrameBufferPixmap(x, y, w, h);

    if (yDown)
    {
        // Flip the pixmap upside downx
        ByteBuffer pixels = pixmap.getPixels();
        int numBytes = w * h * 4;
        byte[] lines = new byte[numBytes];
        int numBytesPerLine = w * 4;
        for (int i = 0; i < h; i++) {
            pixels.position((h - i - 1) * numBytesPerLine);
            pixels.get(lines, i * numBytesPerLine, numBytesPerLine);
        }
        pixels.clear();
        pixels.put(lines);
        pixels.clear();
    }
    Logger.Log("ScreenShot Taken!");
    return pixmap;
 }
}


texts:
I want to pull a sprite from point A(vector2) to point B(vector2) in my Windows Phone XNA game. GestureType.HorizontalDrag moves it horizontally and GestureType.VerticalDrag moves it vertically, how can I move the sprite diagonally?

The player should be able to pull the sprite in every direction if he touches the sprite with his finger. The sprite can't be moved if the player's finger isn't on the sprite.

How can I do that? How can I move an object diagonally on Windows Phone?


texts: Unity : how to Rotate GameObject back to Indentity position?

texts:
Hello i m trying to rotate my object smoothly over MouseButtonDown and rotate to identity position on MouseButtonUp and this code rotate my GameObject smoothly but it won't come back to identity position in time.

void Update ()
    {
        if (GameControls.Games.stateOfGame == GameControls.gameState.inStart || GameControls.Games.stateOfGame == GameControls.gameState.inPlay) {
            if (Input.GetMouseButtonDown (0) || Input.GetKeyDown (KeyCode.Space)) {
                StartCoroutine(FlyCat ());
            }
            if (Input.GetMouseButtonUp (0) || Input.GetKeyUp (KeyCode.Space)) {
                StartCoroutine (ResetCat ());
            }
        }
    }

    IEnumerator FlyCat()
    {
        animate.enabled = false;
        rigidbodyObject.bodyType = RigidbodyType2D.Dynamic;
        tempTimer = 0.0f;
        if (rigidbodyObject.position.y < maxUpperBorder) {
            rigidbodyObject.velocity = Vector2.zero;
            rigidbodyObject.AddForce (jumpForce);
            while (tempTimer < 0.5f) {
                tempTimer += Time.deltaTime;
                transform.rotation = Quaternion.Slerp (transform.rotation, Quaternion.Euler (rotationForce), Time.deltaTime * smooth);
            }
            rigidbodyObject.gravityScale = gravity;
            yield return null;
        }
        if (InstantiateOnce == true) {
            InstantiateOnce = false;
            GameControls.Games.GamePlay ();
        }
        yield return null;
    }

    IEnumerator ResetCat()
    {
        while (tempTimer > 0f) {
            Debug.Log (tempTimer);
            tempTimer -= Time.deltaTime;
            transform.rotation = Quaternion.Inverse (Quaternion.Euler(rotationForce));
        }
        transform.rotation = Quaternion.identity;
        yield return null;
    }


texts: What are the advantages of having a real time based physics?

texts:
Possible Duplicate:
  Fixed time step vs Variable time step

Now just let me clarify what I mean by "real time based physics", which I will call RTBP from now on. Well, basically, it implies taking, you guessed it, actual time into calculations.

For example:

timePassed = time - lastTime

positionx += vx*timePassed
positiony += vy*timePassed

lastTime = time

This would be a simple RTBP model. What's the alternative? I call it "step based physics" (SBP from now on), which would just be this:

positionx += vx //v in SBP is obviously smaller than in RTBP
positiony += vy

I currently use SBP, but I see that many people actually include time in their calculations. Why is that? I of course limit the update time to 1000/60ms.

Once the update interval is limited, both models would behave the same. The only difference is when the FPS drops. I believe that here is where PBS excels over RTBP. In PBS the game would, yes, run slower, but would always produce the same results! In RTBP, the position might increase so much that an object actually passes through a wall!

Anyway, there must be something that I'm missing.


texts: Why can't I use C routines to load files in Android NDK?

texts:
I have successfully rendered a triangle with a hard coded shader using NativeActivity of Android NDK. Now I have the requirement to load a shader file. I tried to use fopen but it is returning NULL.

I have researched a little bit and found out there's an AAssetManager which I can use.  I want to know why fopen didn't work and why should I use AAssetManager to load files?


texts: Unity runs custom AssetPostProcessor every time on save

texts:
I've written a AssetPostProcessor script that make some changes to prefabs and materials on import in some specific folders. I'm using this method to do that:

private static void OnPostprocessAllAssets(string[] importedAssets, string[] deletedAssets, string[] movedAssets, string[] movedFromPath)
{
   // if the importedAsset is a prefab
   GameObject obj = (GameObject)AssetDatabase.LoadAssetAtPath(objName, typeof(GameObject));
   if (obj) {
        if (AssetDatabase.GetAssetPath(obj).Contains("Assets/Tiled2Unity/Prefabs")) {
            // Here's some code that changes the asset
        }
    }
}

For some reason, every time I save this AssetPostProcessor is run which is something I don't want because this is lost time for something that isn't needed. What can I do to stop this?


texts: What should I set my managed stripping level to?

texts:
I know the higher the Managed Stripping Level the smaller binary size but I also know the higher the level more issues you can run into so I have some questions about all this.

If I set my managed stripping level to high will I see the effect of that and be able to properly test it when running my game in the editor or would I have to compile to make sure everything runs alright?
Can issues with a high managed stripping level be platform specific (Meaning a high level is good on one platform but causes issues on another)?
Does managed stripping level only effect binary size or can it also effect performance? If it can effect performance would a binary with a high managed stripping level run faster than a binary with a low managed stripping level or would it be the other way around?


texts: Accurately measure time between calls to onDrawFrame (Android OpelGL ES 2.0)

texts:
I'm trying to sort out some timing issues within my gameloop and I've seen something that I don't understand.

The Nexus 10 is supposed to have (as far as I'm aware) a VSync on 60Hz.  So that would be mean would it not that onDrawFrame is called by the system every 16.66ms?

When I try to measure it I get different readings on every iteration like so:

public void onDrawFrame(GL10 gl) {

        Log.v("NewTag","Millis between this call and last: "+((System.nanoTime()-newTime)/1000000));

        newTime = System.nanoTime();
}

See my results:

As you can see, it varies between 11.53ms and 21.85ms

Why is it not a constant 16.66 or is it just that nanoTime isn't acurate enough to give a more exact reading?


texts: Giving points to users - how can I make it interesting?

texts:
I have a website where users can choose the winner of a sporting event. If they guess correctly they get 1 point, otherwise they receive zero points. At the end all users are ranked based on their score, which is computed like this:

score = points * (number_of_guesses / number_of_misses)

It's a rudimentary system but it works alright. However I am looking for a points system that's more interesting to the user, that makes the game more engaging. For example giving more points for picking the underdog in an event might make the game a bit more interesting.

Can you offer me some suggestions?


texts: Creating a gradient for a texture - Why is the color becoming dark on one side?

texts:
Updated
While debugging I looked at the lerp and it was calculating into a negative number at the start. So I added in checks for to low or high a value, and that seems to have fixed it. I'll answer the question myself unless someone can find a way to fix the formula that calculates the lerp, since that seems to be the culprit. My fix was this:

double lerp = (start - here) / (start - end);

if (lerp < 0d)
    lerp = 0d;
if (lerp > 1d)
    lerp = 1d;

Original Question
I'm applying a gradient to a texture per the answer in this topic: Code to generate a color gradient within a texture using a diagonal line

My code is referenced below. The code was seeming to work fine. I was using a two-color gradient: green to purple. However, when I changed it to two colors that blended well into a 3rd color, I could instantly see that something was wrong.

For example, blue to purple was producing a red element outside of the gradient area. If you also look closely, the blue itself is also enhanced on the outer edges. It's almost as if the two colors are mixing outside of the gradient area, when they should be the original colors.

Calling Code

This is applying to the center of an area 80x25.

Color[] colors = new Color[] { Color.Blue, Color.Purple };
float[] colorStops = new float[] { 0f, 1f };

Algorithms.GradientFill(new Point(40, 12), 3, 33, new Rectangle(0, 0, CellData.Width, CellData.Height), colors, colorStops);

Gradient Calculation Code

public static void GradientFill(Point position, int strength, int angle, Rectangle area, Color[] colors, float[] colorStops)
{
    double radians = angle * Math.PI / 180; // = Math.Atan2(x1 - x2, y1 - y2);

    Vector2 angleVector = new Vector2((float)(Math.Sin(radians) * strength), (float)(Math.Cos(radians) * strength)) / 2;
    Vector2 location = new Vector2(position.X, position.Y);

    Vector2 endingPoint = location + angleVector;
    Vector2 startingPoint = location - angleVector;

    double x1 = (startingPoint.X / (double)area.Width) * 2.0f - 1.0f;
    double y1 = (startingPoint.Y / (double)area.Height) * 2.0f - 1.0f;
    double x2 = (endingPoint.X / (double)area.Width) * 2.0f - 1.0f;
    double y2 = (endingPoint.Y / (double)area.Height) * 2.0f - 1.0f;

    double start = x1 * angleVector.X + y1 * angleVector.Y;
    double end = x2 * angleVector.X + y2 * angleVector.Y;

    for (int x = area.X; x < area.Width; x++)
    {
        for (int y = area.Y; y < area.Height; y++)
        {
            // but we need vectors from (-1, -1) to (1, 1)
            // instead of pixels from (0, 0) to (width, height)
            double u = (x / (double)area.Width) * 2.0f - 1.0f;
            double v = (y / (double)area.Height) * 2.0f - 1.0f;

            double here = u * angleVector.X + v * angleVector.Y;

            double lerp = (start - here) / (start - end);

            float newLerp;
            int counter;
            for (counter = 0; counter < colorStops.Length && colorStops[counter] < (float)lerp; counter++) ;

            counter--;
            counter = Math.Max(counter, 0);
            counter = Math.Min(counter, colorStops.Length - 2);

            newLerp = (colorStops[counter] - (float)lerp) / (colorStops[counter] - colorStops[counter + 1]);

            SetPixel(x, y, color);
        }
    }
}


texts: How were art assets created in the late 16-bit/early 32-bit era?

texts: How were 2d and 3d art assets typically created in the early-to-mid 1990's (16-bit and 32-bit eras?)


texts: Connecting varying tilemap layouts at possible connection points?

texts:
I'm building an isometric 3D ARPG in Unity3D, and

I have a tilemap, for example a dungeon.
I have tiles marked where a door could be placed.
I select a random "could-be-a-door" tile from the tilemap.
I "receive" an any shaped room, which could be a prefab, or a generated one as well. This room got tiles marked for door placement as well.

Without editing anything:

how could I easily determine whether this room could be connected to the existing dungeon via the selected connection point? (and of course find the solution if it could be)

by (valid) connecting I mean: only their doors and walls can overlap, but nothing else. (and removing the duplicates, creating the door itself, etc)

(Of course rooms can differ from rectangles)


texts: How to calculate area to fill in this Snake/Qix game variant?

texts:
I have a game which is a Snake/Qix variant.

The player controls a line which is moving on an island. Player has possibility to leave the island in order to connect that island to itself. Once the connection is made, the new area formed by the connection becomes part of the island (see picture: red line is the path the snake has made while outside the island, dark red pixels are the area/island).

I am trying to find a algorithm (even bruteforce) how to fill the new area (in other words how to do transition between first and second line on the picture).

What I have in mind is to run a path finding algorithm between the enter/exit points. If there is a path, it means the snake connect the island to itself. The path (in green) and red line together forms a closed polygon which can then be filled (how ?)

As it is now, the data is simply defined a 2D array of pixels (eg : 0 = empty, 1 = island, 2 = player snake)


texts: What is the specific name of this UI component?

texts: Is there a specific name for this kind of ui component? Sometimes it only renders a symbol (without text) so using name like TextComponent is imo not very fitting.


texts: Cocos2d-x: Differences between applying shader to child node and entire scene?

texts:
I'm beginning with shader.
I wonder what if i apply shader for single node, what'll happen?

The gl_FragCoord = (0.5,0.5) is the bottom left of the screen or the bottom left of the node?

I get some wrong caculations while wanting to draw something in the center of the node (not the screen).

Many shader tutorias with sample code to draw at center using gl_FragCoord.xy / resolution.xy, if it's 0.5, it's center. In this case, it might be wrong because i want to draw in center of the node.

Finally, how's about texture2D i use texture2D instead of texture, are they the same?

I've applied this code on the node and it prints out the whole screen with stretch version (resolution = device resolution)

vec2 xy = gl_FragCoord.xy / resolution.xy;
vec4 texColor = texture2D(CC_Texture0,xy);
gl_FragColor = texColor;


texts: How important is music to mobile phone (smart PDA) games?

texts: Specifically iPhone/iTouch, Droids, and the new Windows Phone 7? I don't know how to quantify this, or if any research has been done. I am wondering how important the music is to the gaming and what % of games come with music at all, if good music at that.


texts: Question about BoundingSpheres and Ray intersections

texts:
I'm working on a XNA project (not really a game) and I'm having some trouble with picking algorithm. I have a few types of 3D models that I draw to the screen, and one of them is a switch. So I'm trying to make a picking algorithm that would enable the user to click on the switch and that would trigger some other function. The problem is that the BoundingSphere.Intersect() method always returns null as result. This is the code I'm using:

In the declaration section:
`

//Basic matrices
private Matrix world = Matrix.CreateTranslation(new Vector3(0, 0, 0));
private Matrix view = Matrix.CreateLookAt(new Vector3(10, 10, 10), new Vector3(0, 0, 0), Vector3.UnitY);
private Matrix projection = Matrix.CreatePerspectiveFieldOfView(MathHelper.ToRadians(45), 800f / 600f, 0.01f, 100f);

//Collision detection variables
Viewport mainViewport;
List<BoundingSphere> spheres = new List<BoundingSphere>();
Ray ControlRay;
Vector3 nearPoint, farPoint, nearPlane, farPlane, direction;

`

And then in the Update method:
`

nearPlane = new Vector3((float)Mouse.GetState().X, (float)Mouse.GetState().Y, 0.0f);
farPlane = new Vector3((float)Mouse.GetState().X, (float)Mouse.GetState().Y, 10.0f);

nearPoint = GraphicsDevice.Viewport.Unproject(nearPlane, projection, view, world);
farPoint = GraphicsDevice.Viewport.Unproject(farPlane, projection, view, world);

direction = farPoint - nearPoint;
            direction.Normalize();
            ControlRay = new Ray(nearPoint, direction);
            if (spheres.Count != 0)
            {
                for (int i = 0; i < spheres.Count; i++)
                {
                    if (spheres[i].Intersects(ControlRay) != null)
                    {
                        Window.Title = spheres[i].Center.ToString();
                    }
                    else
                    {
                        Window.Title = "Empty";
                    }
                }

`

The "spheres" list gets filled when the 3D object data gets loaded (I read it from a .txt file). For every object marked as switch (I use simple numbers to determine which object is to be drawn), a BoundingSphere is created (center is on the coordinates of the 3D object, and the diameter is always the same), and added to the list. The objects are drawn normally (and spheres.Count is not 0), I can see them on the screen, but the Window title always says "Empty" (of course this is just for testing purposes, I will add the real function when I get positive results) meaning that there is no intersection between the ControlRay and any of the bounding spheres. I think that my basic matrices (world, view and projection) are making some problems, but I cant figure out what. Please help.


texts:
I'm learning a tutorial from Rastertek about diffuse light with DX 11, here's the shader code:

float4 LightPixelShader(PixelInputType input) : SV_TARGET
{
    float4 textureColor;
    float3 lightDir;
    float lightIntensity;
    float4 color;

    // Sample the pixel color from the texture using the sampler at this texture coordinate location.
    textureColor = shaderTexture.Sample(SampleType, input.tex);

    // Invert the light direction for calculations.
    lightDir = -lightDirection;

    // Calculate the amount of light on this pixel.
    lightIntensity = saturate(dot(input.normal, lightDir));

    // Determine the final amount of diffuse color based on the diffuse color combined with the light intensity.
    color = saturate(diffuseColor * lightIntensity);

    // Multiply the texture pixel and the final diffuse color to get the final pixel color result.
    color = color * textureColor;

    return color;
}

And I don't understand why to invert the direction, it says in a comment line "invert the light direction for calculations", why is it necesary?

Thanks.


texts: Displaying and updating score in Android (OpenGL ES 2)

texts:
I'm using a FrameLayout where I have a GLSurfaceView at the bottom and a few Views on top of it. One of those Views is a TextView that displays the current score.

Here's how I'm updating the score TextView based on what happens in my game loop: whenever an event happens that increases the score, I call activity.runOnUiThread(updater), where activity is the activity that has the above FrameLayout (my main game activity) and updater is just a Runnable that increments the score. From my understanding, using runOnUiThread() from the OpenGL thread is standard practice - otherwise you'll get an exception, I can't remember its name.

The problem is that there's a very noticeable lag between the event and the score update. For example the character gets a coin, but the coin count is not updated quickly. I tried summing all the score events from my game loop and calling runOnUiThread() only once per loop, but it doesn't seem to make much of a difference - the lag is still noticeable.

How can I improve my design to avoid this lag?


texts:
Apart from using b2Body::setTransform(), are there other ways to move a body around while keeping its dynamics ?

I want to move several bodies at the same time into one direction, pretty much like the movement of a crowd like the units in starcraft 2.

Does box2d already provide such features, if yes what is this called ? If not what precautions should I take while using setTransform ?


texts: How to create a container with thin borders?

texts: I want to make a container with a thin border, for this I created a 32x32 pixel image, but by adjusting the Canvas Scaler and also setting the Anchors I noticed that at some screen resolutions the sides of the container disappear or change color, how can I fix this?


texts: Client should send one big packet or multiple smaller ones per frame?

texts:
The client can do several actions per frame, for instance, requesting a movement, shooting etc. Should i send a packet to the server for each action the client performed during the frame, or should i stack them in an unique packet and send it at the end of the frame?

EDIT: i'm using Jmonkeyengine and the provided network API SpiderMonkey.


texts: I'm wondering if there's anyway of automatically testing the performance of my game on multiple configurations because I know a game runs well on my computer but how do I know how well my game performs over a variety of hardware? Do I just simply have to rely on player feedback?


texts: How can I "stick" objects to tables in Skyrim and still allow those objects to be player-interactable?

texts:
I'm trying to place a non-static pot (RuinsPot01) on a table (RuinsAltar) with the Havok simulation.

I place the pot a little bit above the table and turn on Havok. The pot falls down but is left floating slightly above the table.

If I turn of Havok and press F it is aligned correctly to the table, but as soon I turn on Havok Simulation, it jumps up slightly and floats as before.

Does any one have a fix for this? Making the pot static isn't an option, it has to be movable.


texts: How can I move my player on exact x and y coordinates, like on a grid?

texts:
I'd like to implement movement exactly like it is done in this game. (You can see it in action on YouTube.)

I need my Player to always stay in the center of X and Y similar to grid movement, but with free movement/line like. Only move on x and y lines. And I need smooth changes at intersections.

 var x = Input.getAxis("Horizontal");
 var y = -Input.getAxis("Vertical");
 var deltaPos = Vector2.zero;

 if (Mathf.Abs(inputY) > Mathf.Abs(inputX)) {
     deltaPos.Y = speed * inputY * Time.deltaTime;
 }
 else {
     deltaPos.X = speed * inputX * Time.deltaTime;
 }

 transform.position += deltaPos;


texts: Independent Column sizes in Scene2D Table in LibGDX

texts:
For my game's (mostly GUI based) UI i am using table from Scene2D in libGDX. I want independent column sizes in my table but first cell width is the width for all other rows in column. Is it possible to have a table in Scene2D with independent cell width in each row? For example, first cell in first row should have 10% width and first cell in second row should have 15% width.
I tried using Horizontal Groups, Containers but they make my code too shabby and cluttered.


texts: How can I determine if the player holds the top leaderboard spot in Game Center?

texts:
I have integrated Game Center into my game and I want to make an achievement that is earned if the user holds the #1 spot on Game Center.

How do I access that information with code?


texts: Collectible card game, cards and effects

texts:
Based on Design of a turn-based game where actions have side-effects

I am building a card-game where cards can have side-effects be triggered under different circumstances.

I was given a good idea on how to handle different phases by having hooks (events) that different cards can be triggered to do something, like when a card is played, draw an additional card, etc.

I am not sure how I should compose all these things to work together, I have a GameState object which handles the state of the game (who's turn, player objects, timers) checking if a move is legal etc.

I am having a Card class that currently just has a type and a name getter/setters and properties. I believe the best way to store cards would be to use .JSON files, because that would let you simply write a new card.

To achieve side-effects I am thinking of having "components" that is configured through a cards JSON-file.

{
    "name": "Ocean Humans",
    "type": "Creature",
    "components": {
    }
}

However, I am not sure how I should compose these JSON-files to some actually working object. How do I call these components when I invoke a hook_event (draw a card, phase begin). And make sure right components are run?


texts: Animation imported from Blender into Unity via FBX doesn't play?

texts:
I started building this model in Blender and gave it a simple animation that rotates the board about the axel.

...I exported it as FBX and imported it into Unity. I can see the animation is stored in the file when I import, but I can't find an animation file after I drop it in the scene, and there is no controller for the Animator controller it generated, either. I can watch the animation play in the FBX preview thumbnail but nowhere else.

How can I get my animation working?


texts: Establish a person's genuine interest in game programming

texts:
I teach on a 3rd level, 4 year games programming degree (B.Sc. in Computer Games Development). We find that new and prospective students often conflate interests and abilities in game-playing, game-design and game-programming. (I know the title could be a a lot more specific or descriptive, but there are internal reason why we can't change it). We do have an open day when prospective students can come and talk to faculty and current students.

This results in a lot of students signing up for our programme who find themselves with interests and/or abilities mis-aligned with their chosen degree. We have options for them to change major, but the are almost just as programming intensive. We don't have any options for students who really wanted to to game related art or design. So some students just stick at it for 4 difficult/unhappy years, as it is the closest degree available to them in gaming.

We outline the content of the programme in our prospectus, but most incoming students have little programming experience, so topics titles like data-structures, software engineering or 3D Graphics don't really mean much to them.

  "I didn't expect so much math in 3D Graphics, I assumed it would be,
  like, drawing..."

Is there any way to help establish a person's genuine interest in game programming, so that they can make a more informed decision about their education?


texts:
How is a game cinematic made? I can't find a decent article anywhere to give at least starting point into understanding what it takes to create a cinematic.

I don't mean typical scripted game play, rather, the really nice cut scenes games have, like the ones Blizzard has for almost every game they develop.

http://www.youtube.com/watch?v=OGwCU_qA22U

Note: I'm not sure what to tag this under.


texts: Which is the best approach to make a 2D character to be able to use tons of different equipments when in action?

texts:
I want to create a 2D game but I'd like to have the character to wear tons of different equipments on different combinations, like a RPG or something.

So let's say the user changes his/her shoulders and pants, this must be shown to the player and all these different equipments must follow the different characters action (hitting, being hit, spelling magic, etc.).

I see a few problems that I'd like to know the best approach/algorithm/architecture to solve.

1 - Sprites or Animations

Should I create different sprites for each equipment in each action animation?

Is it better to just have the equipment sprite and animate it directly on code like rotating and translating (using something like tween on Flash)?

Is there any other better option? (I really don't like the ideas above)

2 - Positions

Let's say during one of the character's move he starts looking directly in front to the player's view but ends his movement showing his right side to the player (like if he swings his sword from one side to the other).

If we consider one part of the user, like his head for example, it starts in front and then turns left.

It means at least 3 different positions for each head equipment (helmet, cap, whatever).

This surely influence the answer of #1 question. How is the best way to achieve that?

3 - Layers

Let's consider a character move where he spins 360 degrees with his arms open. At the beginning of the animation, his right hand is close to the user's view and then, at the middle of the movement, this is probably behind the character's body on the animation.

Whatever is the option on #1 question, you surely needs to use some kind of layer model to make this sprite or animation to starts closer to the player's view and later change to far away from player's view.

Is there any good way to do that?

I know the question is quite long and difficult to understand. Let me know if you think it's better to have some drawings to try to explain which one and I'll try to do that.


texts: Took one major now want to be in different industryssT

texts:
How different is Programmer Analyst from Game Programmer?
I took the first one as my major but want to go with game development industry.
Is it possible to transition from one to another?

EDIT: There is a single class about game development in this major


texts: Loading tilemaps, entering buildings, chopping big maps

texts:
I´ve got some questions regarding the loading of tile maps.
I´ve got a world with several buildings in it that guide the user to a new map. This map can be a small room, but also a big area.
To change the map it seems straight forward to change the current tilegrid to the tilegrid of the new map.
But this seems pretty inefficient in some cases;

User enters building from world map

Small building map is loaded

User exists building, enter world again
This scenario causes the entire world map to be loaded again.
I could just hold the previous map in a variable to prevent it from needing to be loaded again. But what if the new map has several other passages, or is a big map itself. Then I would need to hold a big amount of data.

I was thinking of loading only tiles that are in a certain radius of the players viewport. But entering new maps would still cause the entire viewport area to be loaded again.
Is there a way how this type of thing is generally done?


texts:
I've been running into walls for the past week or so on my toy project in UE4. My goal is to draw procedural roads on a procedural landscape (eventually getting to intersections and buildings). The landscape is generated with libnoise and the roads are generated with a slightly modified version of the algorithm found here.

But I'm having issues draping the roads on the landscape and I can't find any straightforward algorithmic way of doing it. You can see my problem below: the geometry of the road intersects the geometry of the landscape.

In short, given:

The landscape index buffer
The landscape vertex buffer
Every road segment's X,Y,Z coordinate

How do I modify the underlying vertex/index buffer so that the landscape "wraps around" the roads?


texts: How do I get my team NPC to follow the player? | Game Maker Studio

texts:
I would like to have 4 teammate NPC's that would follow behind the Player. First off, I know how to get the movement and collisions working properly but getting the NPC's to follow the player is where I'm struggling.

This code checks if the player's x is greater than the x of the NPC so it can move right.

if obj_testPlayer.x > x - 34 { // want it to stop 34 pixels away from the players left
   xspd += 3
} else {
   xspd = 0;
}

Once the NPC is 34 pixels away from the Player it will stop, but when the player moves again, the NPC is stationary. Also, when I change this code to check if the player is on the left of NPC; The NPC won't move.

All I'm trying to do is get the NPC moving Horizontally when the player is on the right or the left side of the NPC but it's not working.


texts: OpenGL camera movement with mouse buttons

texts:
I am using modern OpenGL with glfw. I made a FPS camera with mouse and it works very well. But I want to move my mouse like Blender's model view mode. When I press the middle mouse button and move the mouse, it should move the camera. I tried it but I couldn't succeed it. I just want it like Blender.

That is my camera class (sorry for indentation):

#pragma once
#include <vector>
#include <GL/glew.h>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>

enum Camera_Movement {
    FORWARD,
    BACKWARD,
    LEFT,
    RIGHT
};

const GLfloat YAW        = -90.0f;
const GLfloat PITCH      =  0.0f;
const GLfloat SPEED      =  3.0f;
const GLfloat SENSITIVTY =  0.05f;
const GLfloat ZOOM       =  45.0f;

class Camera
{
public:

glm::vec3 Position;
glm::vec3 Front;
glm::vec3 Up;
glm::vec3 Right;
glm::vec3 WorldUp;

GLfloat Yaw;
GLfloat Pitch;

GLfloat MovementSpeed;
GLfloat MouseSensitivity;
GLfloat Zoom;

Camera(glm::vec3 position = glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3 up =            glm::vec3(0.0f, 1.0f, 0.0f), GLfloat yaw = YAW, GLfloat pitch = PITCH) : Front(glm::vec3(0.0f, 0.0f, -1.0f)), MovementSpeed(SPEED), MouseSensitivity(SENSITIVTY), Zoom(ZOOM)
{
    this->Position = position;
    this->WorldUp = up;
    this->Yaw = yaw;
    this->Pitch = pitch;
    this->updateCameraVectors();
}
Camera(GLfloat posX, GLfloat posY, GLfloat posZ, GLfloat upX, GLfloat  upY, GLfloat upZ, GLfloat yaw, GLfloat pitch) : Front(glm::vec3(0.0f, 0.0f, -1.0f)), MovementSpeed(SPEED), MouseSensitivity(SENSITIVTY), Zoom(ZOOM)
{
    this->Position = glm::vec3(posX, posY, posZ);
    this->WorldUp = glm::vec3(upX, upY, upZ);
    this->Yaw = yaw;
    this->Pitch = pitch;
    this->updateCameraVectors();
}

glm::mat4 GetViewMatrix()
{
    return glm::lookAt(this->Position, this->Position + this->Front,  this->Up);
}

void ProcessKeyboard(Camera_Movement direction, GLfloat deltaTime)
{
    GLfloat velocity = this->MovementSpeed * deltaTime;
    if (direction == FORWARD)
        this->Position += this->Front * velocity;
    if (direction == BACKWARD)
        this->Position -= this->Front * velocity;
    if (direction == LEFT)
        this->Position -= this->Right * velocity;
    if (direction == RIGHT)
        this->Position += this->Right * velocity;
}

void ProcessMouseMovement(GLfloat xoffset, GLfloat yoffset, GLboolean  constrainPitch = true)
{
    xoffset *= this->MouseSensitivity;
    yoffset *= this->MouseSensitivity;

    this->Yaw   += xoffset;
    this->Pitch += yoffset;

    if (constrainPitch)
    {
        if (this->Pitch > 89.0f)
            this->Pitch = 89.0f;
        if (this->Pitch < -89.0f)
            this->Pitch = -89.0f;
    }

    this->updateCameraVectors();
}

void ProcessMouseScroll(GLfloat yoffset)
{
    if (this->Zoom >= 1.0f && this->Zoom <= 45.0f)
        this->Zoom -= yoffset;
    if (this->Zoom <= 1.0f)
        this->Zoom = 1.0f;
    if (this->Zoom >= 45.0f)
        this->Zoom = 45.0f;
}

private:
void updateCameraVectors()
{
    glm::vec3 front;
    front.x = cos(glm::radians(this->Yaw)) * cos(glm::radians(this-  >Pitch));
    front.y = sin(glm::radians(this->Pitch));
    front.z = sin(glm::radians(this->Yaw)) * cos(glm::radians(this->Pitch));
    this->Front = glm::normalize(front);
    this->Right = glm::normalize(glm::cross(this->Front, this->WorldUp));
    this->Up    = glm::normalize(glm::cross(this->Right, this->Front));
}
};

Thank you.


texts: Do game engines put all interpolation onto the GPU?

texts:
Is it considered standard to push all the vertices and an interpolation of the next position onto the GPU?

Suppose a sector is moving up every game tick at 50 units per second. You could put on the shader something like (good old parametric equation-like formulas):

pos.x = a*x1 + (1 - a)*x0;

Where you'd calculate a as a uniform and only send this value to the GPU in an uncapped fashion, like so:

while (true) {
    a = percentage of the way between frames [in range from 0.0 to 1.0]
    updateGLUniform(..., a);
    render();

    // Rest of stuff

    delay();
}

The other way of doing it was to manually set each entity and sector every single time you loop, but then you might have to update the position of a lot of things every game cycle. Just setting one value seems way more efficient.

However, I don't know if there's any downsides to this. Are there any negatives to shoving interpolation off to the GPU to save computation time in the game? Or is there something that I'm missing? What do major games do?


texts:
I'm new to game development and am looking for some help on improving my jump handling for a simple side scrolling game I've made.  I would like to make the jump last longer if the key is held down for the full length of the jump, otherwise if the key is tapped, make the jump not as long.  Currently, how I'm handling the jumping is the following:

Player.prototype.jump = function () {
    // Player pressed jump key
    if (this.isJumping === true)
    {
        // Set sprite to jump state
        this.settings.slice = 250;

        if (this.isFalling === true)
        {
            // Player let go of jump key, increase rate of fall
            this.settings.y -= this.velocity;
            this.velocity -= this.settings.gravity * 2;
        }
        else
        {
            // Player is holding down jump key
            this.settings.y -= this.velocity;
            this.velocity -= this.settings.gravity;
        }

    }

    if (this.settings.y >= 240)
    {
        // Player is on the ground
        this.isJumping = false;
        this.isFalling = false;
        this.velocity = this.settings.maxVelocity;
        this.settings.y = 240;
    }
}

I'm setting isJumping on keydown and isFalling on keyup.  While it works okay for simple use, I'm looking for a better way handle jumping and gravity.  It's a bit buggy if the gravity is increased (which is why I had to put the last y setting in the last if condition in there) on keyup, so I'd like to know a better way to do it.  Where are some resources I could look at that would help me better understand how to handle jumping and gravity?  What's a better approach to handling this?  Like I said, I'm new to game development so I could be doing it completely wrong.  Any help would be appreciated.


texts: Universal App: Exception from HRESULT: 0x8000FFFF (E_UNEXPECTED)

texts:
I have problem with creating xaml control. I write new project in VS 2015 in universal app.
this is my code:

<ItemsControl Grid.Row="1" ItemsSource="{Binding Path=TechnologyList}">
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <Grid>
                <Grid.RowDefinitions>
                    <RowDefinition Height="10*"/>
                    <RowDefinition Height="10*"/>
                    <RowDefinition Height="10*"/>
                    <RowDefinition Height="10*"/>
                    <RowDefinition Height="10*"/>
                    <RowDefinition Height="10*"/>
                    <RowDefinition Height="10*"/>
                    <RowDefinition Height="10*"/>
                    <RowDefinition Height="10*"/>
                    <RowDefinition Height="10*"/>
                </Grid.RowDefinitions>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="14*"/>
                    <ColumnDefinition Width="14*"/>
                    <ColumnDefinition Width="14*"/>
                    <ColumnDefinition Width="14*"/>
                    <ColumnDefinition Width="14*"/>
                    <ColumnDefinition Width="14*"/>
                    <ColumnDefinition Width="14*"/>
                </Grid.ColumnDefinitions>
            </Grid>
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
    <ItemsControl.ItemContainerStyle>
        <Style TargetType="Control">
            <Setter Property="Grid.Column" Value="{Binding Level}" />
            <Setter Property="Grid.Row" Value="{Binding Row}" />
        </Style>
    </ItemsControl.ItemContainerStyle>
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <Button Content="{Binding Name}"/>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

in line
I get error: Exception from HRESULT: 0x8000FFFF (E_UNEXPECTED)

Can anyone help me ?


texts: Collisions reflecting ball velocities incorrectly

texts:
Ok so this is for a small uni project. My lecturer provided me with a framework for a simple brickbreaker game. I am currently trying to overcome to problem of detecting a collision between the two game objects. One object is always the ball and the other objects can either be the bricks or the bat.

public Collision hitBy( GameObject obj )
{
    //obj is the bat or the bricks
    //the current object is the ball

    // if ball hits top of object
    if(topX + width >= obj.topX && topX <= obj.topX + obj.width &&
       topY + height >= obj.topY - 2 && topY + height <= obj.topY){
        return Collision.HITY;
    }

    //if ball hits left hand side
    else if(topY + height >= obj.topY && topY <= obj.topY + obj.height &&
            topX + width >= obj.topX -2 && topX + width <= obj.topX){
        return Collision.HITX;
    }

    else return Collision.NO_HIT;
}

So far I have a method that is used to detect this collision. The the current obj is a ball and the obj passed into the method is the the bricks. At the moment I have only added statement to check for left and top collisions but do not want to continue as I have a few problems.

The ball reacts perfectly if it hits the top of the bricks or bat but when it hits the ball often does not change directing. It seems that it is happening toward the top of the left hand edge but I cannot figure out why.

I would like to know if there is another way of approaching this or if people know where I'm going wrong.

Lastly the collision.HITX calls another method later on the changes the x direction likewise with y.


texts:
Please note that this is purely an architectural/design question. And sorry for the long post, there are a lot of "thinking out loud" here.

I'm working on a simple graphics engine (as a universtiy research project) and I'm stuck with a decision. I'm trying to abstract every low level API call (so there is no direct gl/d3d call in the high level of code) making the "engine" basically graphics-API-independent.

Let's say I have a class that can represent the source of any geometry (eg. positions, normals, texcoords, etc). The attributes provided can vary from geometry to geometry, there is no guarantee that every geometry contains all of the possible attributes.

I also have the traditional Scene/GameObject/Component/etc classes: a GameObject can be added to the Scene and a GameObject can contain any number of Components.

Lastly, there are multiple Renderers that iterate over a certain set of "things" and use the RenderDevice to issue graphics commands (like setting states, creating resources, executing draw calls, etc).

I'm wondering where I should create/store the actual vertex buffer(s), etc. As far as I know, it is the best to have the least amount of different vertex layouts. Also, the vertex layout is tightly coupled to the shader (especially in DX11+) so it seems logical that the renderer specifies a vertex struct with a layout descriptor. And this was my initial idea.

However, this means that only the renderer knows how to align/store data interleaved from the individual components of the geometry source. And this means that the renderer should create the actual vertex buffers. (This would also help with static batching, since the batching logic depends on the actual rendering task).

However with this approach a "GeometrySource" might be stored in multiple vertex buffers. For example the ShadowMapRenderer requires only the position component of the geometry. Also it can batch every static geometry into a single vertex buffer since there will be no state/uniform/etc changes between the draw calls.

My very first approach (years ago) was that the GeometrySource self-contained a vertex buffer with a vertex layout descriptor. However there are multiple problems with this approach:

every (even the smallest one) geometry would be stored in separate buffers which would cause a big driver overhead
in the modern graphics APIs (eg. DX11+) the vertex layout is tightly coupled to the shader that will be used to render that geometry (see)
the vertex layout should be checked before rendering (does the buffer provide every necessary attribute with the right format?)

So I don't think that this approach would be beneficial. What is a sensible alternative?

Also, there are multiple stack*** posts, but unfortunately, I couldn't find my answer in these:

https://stackoverflow.com/questions/21347636/dx11-inputlayout-cannot-be-set-to-multiple-shaders
Creating Input layouts for different vertex types
How do commercial games engines organise the index/vertex buffers?


texts: What is the term that describes the "user" of a status ailment

texts:
Suppose a Snake performs a skill that inflicts a "poison" status on the Hero, and every minute the Hero receives damage equal to the Snake's skill level.

What is a term that would describe the snake as the object that inflicted the status ailment, that players would recognize or be able to figure out based on context? I imagine there are some standard terminology used in the industry.

Some things I have thought of include "applier" or "inflicter".


texts:
What are the pros and cons of using a 'square' or 'space' based character movement mechanic vs using a free movement mechanic?

Square/Space - Movement on a ridged grid using 'squares', 'hexagons' and 'triangles'
Free - Character can move to any valid position on the game board

Some examples of 'Square'

Final Fantasy Tactics
Zoids Assault

Some examples of 'Free'

Star Craft
Age of Empires
Baldur's Gate

I am designing a game that is a Tactical RPG my current idea is to use a square grid with a standard character size of 3x3 or 5x5 so that the maps tiles are more granular.


texts:
So, I'm making a platformer game from scratch in Java and I am trying to make the camera movement smoother. Here is what it currently is

public class Camera {
    private int x, y;

    public Camera(int x, int y) {
        super();
        this.x = x;
        this.y = y;
    }

    public int getX() {
        return x;
    }

    public void setX(int x) {
        this.x = x;
    }

    public int getY() {
        return y;
    }

    public void setY(int y) {
        this.y = y;
    }

    public void tick (GameObject player) {
        setX((int) (-player.getX() + Reference.WIDTH / 2 + 16));
        setY((int) (-player.getY() + Reference.HEIGHT / 2 + 64));
    }
}

It moves too strictly and it always centres the player to the screen, I don't like it.

I tried watching this video, but it's in GameMaker. Any way to translate this to Java?
https://youtu.be/6cIN6iW5ois

Any help would be appreciated,  thanks! :)


texts:
Eventually this problem will be 3D, so I would like a solution that works in 3D.

My player is looking forwards. There is an axis-aligned box on the screen (FOV is guaranteed to be 90, so boxes behind the player aren't considered.)

I want to get the coordinates of the point on box that is closest to the player's looking direction.

I.e., if the player turned towards the box, which point of the box would intersect with their line of vision first?


texts:
The steps I have gone through:

Added an FBX in UnityProject.
FBX added to scene hierarchy.
Made Prefab by dragging the FBX into my assets.

Note that now the model became a prefab in my hierarchy.
Then I added a script to the prefab and assigned some objects and methods to such script.
My problem is that when I import the new FBX in the project my scene object doesn't update as it's linked to the prefab which doesn't see the updated FBX.
Is it possible to update my prefab with the latest FBX so I don't have to rebuild the prefab and reassign all scripts every time?


texts: Unity2D - Save everything in a scene before loading another and come back to it?

texts:
So I have am into this endless runner thing where everything is generated randomly from prefabs. Okay cool! But I am currently working on a bonus collectible which takes the player to another scene. After certain time, the player must reach at exactly the same position it left from.

But that's not the problem. I have figured out a way to save and load player's and camera's position using temporary prefabs.

My problem is : When the player collects the bonus thing in main scene and goes to the bonus scene and comes back, there's a sort of gltichiness or distortion in the game view. As if, the bonus scene is frozen and other scene is overlapping and everything is being stretched.
But in inspector, everything including camera is in place.

In game view, on returning, the camera seems to be starting from beginning while in inspector its exactly where its supposed to be. Not only that, there's a lot of distortion, which I am 70% sure is because the level had to load all over again and there's no possible way of game knowing which prefabs were instantiated as they all are random.

Compiling up, my question is, how can I save everything in a scene before leaving and load it all again at once so it doesn't have to go through all of it again. Is there any less-complex way? I hope I have made my ques clear. Thank you.


texts: How to disable gravity for a RigidBody moving on a slope?

texts:
I created a script that handles movement for my player (moving around, going down and up slopes). However, since I'm using a RigidBody not a CharacterController when I go up slope and stop on the middle of it the gravity pulls me backward, which is fine, but the problem is when I move forward, the gravity force pulls me backward when I'm trying to go forward. This problem wouldn't have appeared if my character wasn't a sphere but my character is a sphere so it always roll down when gravity is applied to it.

What I want is to somehow stop the gravity for a second or reset it to zero when I move my character, and when I'm going up a slope so it won't hold me back. I tried:

if(grounded) rb.velocity = Vector3.zero;

but I don't think it's the right approach.


texts: Why is the camera tilting around the z axis when I only specified x and y?

texts:
My goal is to program a camera to point towards the mouse cursor. I attached the following script to the Main Camera.

using UnityEngine;
using System.Collections;

public class CameraController : MonoBehaviour {

    public float sensitivity;

    // Update is called once per frame
    void Update () {
        transform.Rotate (Input.GetAxis ("Mouse Y") * -1 * sensitivity, Input.GetAxis ("Mouse X") * sensitivity, 0);
    }
}

I "told" the camera to rotate around the x and y axes. Whenever it does this, the camera tilts sideways. When I checked the rotation of Main Camera, I saw that the z rotation had changed. Why is it rotating around the z axis when I left it at 0?


texts:
I have went over and over in my head for the past month trying to get a simple platformer together. My problem is collision. So far from every tutorial I've found this tilemap based collision needs to be done this way:
Check for for tile in x+xVel / tilesize if so xVel=0
same for x axis just subtracting for when the player goes left.
Check for tile in y+yVel/tilesize. if so yVel=0. No matter how many different ways I end up programming this concept. The player always ends up clipping walls, falling through, or just hanging out 2 pixels before the collision. Can anyone tell me what's up?

By the way my collision check is a two point method. eg. Check top two points of the rectangle box if going up, bottom two for down ect.

Thanks!


texts:
I have recently started to work with DirectX 11 and 12, I am using Microsoft Visual Studio Community Edition. I am under a 64-bit machine. I am currently rendering a frame with background and a window using Windows C++ API and DirectX 11.1.
I was thinking about drawing text, but I thought about using custom Fonts, so I will have original Font file, not some graphic file e.g. *bmp or some other format. I have read about: SpriteBatch[1] and SpriteFont[2], which can be used via DirectX Tool Kit (https://github.com/microsoft/DirectXTK).
I tried:
std::unique_ptr< SpriteFont> font(new SpriteFont(device, L"text.spritefont"));
std::unique_ptr<SpriteBatch> spriteBatch(new SpriteBatch(context));
spriteBatch->Begin();
font->DrawString(spriteBatch.get(), L"Hello, ", XMFLOAT2(200,200));
spriteBatch->End();

But, I am running into some issues with the Begin() function, that seems to have mandatory parameters. I did try: Begin(SpriteSortMode:: SpriteSortMode_Deferred, nullptr, nullptr, nullptr); But, I keep experiencing the same errors in Visual Studio regarding overloading and params.
I know that DirectX 9 had D3DXFont, https://drunkenhyena.com/cgi-bin/view_cpp_article.pl?chapter=3;article=17 , I also found this: http://download.nvidia.com/developer/GPU_Gems/CD_Image/Natural_Effects/Water_Simulation/d3dfont.cpp
I also found the DXUT for Direct3D 11, https://github.com/walbourn/directx-sdk-samples/tree/master/DXUT -- but seems this is no longer active.
[1] https://github.com/microsoft/DirectXTK/wiki/SpriteBatch
[2] https://github.com/microsoft/DirectXTK/wiki/SpriteFont
EDIT #1:
With DirectX 9, I can do the following:
 HRESULT hr=D3DXCreateFont(
                     device,           //D3D Device
                     22,               //Font height
                     0,                //Font width
                     FW_NORMAL,        //Font Weight
                     1,                //MipLevels
                     false,            //Italic
                     DEFAULT_CHARSET,  //CharSet
                     OUT_DEFAULT_PRECIS, //OutputPrecision
                     ANTIALIASED_QUALITY, //Quality
                     DEFAULT_PITCH|FF_DONTCARE,//PitchAndFamily
                     "Arial",          //pFacename,
                     &font);           //ppFont

But, unfortunately this does not exist in DirectX 10, 11, or 12.

Questions:

Is using these new recommendations (SpriteBatch, SpriteFont & DirectXDTK) by Microsoft, in any way, linking the stuff I build with XNA?
Is it possible to use Font file, custom one? Or, do I have to create graphic font? (What is more recommended generally speaking)?

A book recommended writing your own Font drawer class, it uses:

ID3D11VertexShader
ID3D11PixelShader
ID3D11InputLayout
ID3D11Buffer
ID3D11ShaderResourceView
ID3DX11CreateShaderResourceViewFromFile
ID3D11SamplerState
D311_MAPPED_SUBRESOURCE
D311_MAP_WRITE_DISCARD

EDIT #2: WHY DO I HAVE TO CAST,
Microsoft::WRL::ComPtr


texts: Translating a world position to an array position

texts:
Lets keep this simple, so, assuming I have an array like this ...

var array = new bool[10,10,10];

.. and then I have a start and end vector3 ...

var start = new Vector3(-21,-21,-21);
var end = new Vector3(-10,-10,-10);

... these booleans represent some data for a part of my virtual world, but they are a small chunk of that data between the start and end points in the world.

How do I, given a point in the virtual world translate that position to a point in the array ...

var pos = new Vector3(-20,-20,-20);

var result = GetValueAt(pos);

bool GetValueAt(Vector3 pos)
{
    // my question is:
    //what goes in here to translate from pos to array pos [1,1,1] ?
   return array[1,1,1];
}


texts:
Ok, I'm having a lot of trouble understanding using Matrices for Movement in a 2D game. I currently have a Tank object that has a Matrix3 globalTransform managing the direction Scale and Rotation. That Object is the Parent to a gun Object that rotates around the centre of the Tank.

That uses a localTransform that is multiplied by its parents globalTransform to get its own globalTransform. The Update Method is:

localTransform = localTransform * rotation;
globalTransform = tank->globalTransform * localTransform;

How would I go about implementing a bullet being shot from the Gun? Should I create a Bullet Object? What would be the math be to fire in a linear direction the way the gun is facing?


texts: How does a 4x4 matrix represent an object in space and matrix lore?

texts:
I have been following some tutorials on how Matrix maths works, with adding, dividing, scaling, etc, but I am struggling to understand how the 4x4 matrix represents an object's position in space.

There are 16 elements in the array but to my knowledge you only need to use 7 of them? (I am most likely, horribly wrong but please correct me) and they are:

x, y, z
scale
pitch, roll and yaw.

Furthermore, what is the significance of a column major matrix over a row major one or vice versa? Is it just down to the framework you are using that determines which one you use? (i.e OpenGL or DirectX) What is the difference between them? Is it just the order the elements appear in?


texts: How do I draw a portion of a texture onscreen in OpenGL?

texts: I have a sprite sheet loaded as an OpenGL texture, and I'd like to draw a portion of that texture sequentially for animation. Is there an actual OpenGL command to draw part of a texture? I can get it done by modifying the U and V components when drawing the texture, but I'm not sure if there's a more elegant/correct method of doing this.


texts: Do physics engines take shape into account or they operate solely on predefined variables?

texts:
I have never given it much of a thought about how physics engines operate behind the scenes.

Though, I am currently working on a game that would greatly benefit from as precise as possible physics model, hence the question.

To apply the counter forces, do physics engines, such as Havoc, Bullet and PhysX, take into account the actual shape of the mesh (probably only it's collider) or they operate solely as math functions working with only the predefined physical variables (mass, drag, friction etc.)?

I know that collisions operate on colliders and their shapes, but I am thinking about aerodynamics, gravity and other forces that are counter-applied while objects are in motion.


texts: How do I use transparent textures in panda3d?

texts:
I need to map a partially transparent texture on a flat quad with panda3d. With the quad as a canvas I'd like to create something like sprites positioned in the 3d coordinate system.

I wanted to render a tree. As you can see the color values of the trees border have been stretched over the texture. How can I change the texture mode to include the alpha channel ?

I just don't know how to get hold of the right settings. A link to the right manpage would be perfect. If you need more information about the setup you might want to look at my other question: How do I use setFilmSize in panda3d to achieve the correct view?


texts: How can I create a Texture2D out of an array of color data?

texts:
I'm trying to make a simple engine with DirectX where you can draw to the screen with a function Draw(x, y, r, g, b). The function sets the pixel at x,y to the color r,g,b. The engine has a parameter for the size of a pixel, making the engine capable of looking somewhat retro or low resolution.
My question is in the title. I would like to take an array of color data and paste it into a Texture2D which will then be rendered to the screen, and I would be greatful if someone could point me in the right direction of how I could go about doing that in DirectX.


texts: How do I support animation with frames of different sizes?

texts:
I'm trying to create a simple top-view 2D rpg, in the style of Zelda and Secret of Mana, using PyGame. I've managed to make the beginnings of a game, with an animated character walking around. However, when I start animating attacks, I'm running into problems because the sprite with the sword slash is bigger than the walking sprite. This makes the character appear to be jumping around when attacking.

I managed to handle the problem by defining a center of gravity, so to speak, for each image, and apply a suitable offset at each frame in the animation to make the center of the character stay at the same place throughout the animation. I defined a dictionary of lists of images (instances of pygame.Surface), where I pick out the correct list by the state of the character, so for example there is one list for walking left, and then I loop over the list to get the animation. To handle the offset, I similarly created a dictionary of lists of offsets, looping over those in the same way.

However, I'm not entirely pleased with this implementation, so I'm looking for a more elegant solution.

I tried to add an attribute called offset to each instance of the pygame.Surface class, to hold the offset for each image, but the Surface class doesn't allow new attributes to be set. I then thought about subclassing pygame.Surface, which would allow me to set any attribute I wanted, but then I couldn't load my images with pygame.image.load without a lot of extra code.

I imagine everyone who makes a game with animations where the size of the sprite changes between frames would have to deal with this problem, so if anyone could suggest an elegant implementation, that would be great. If example code with PyGame is available, that would be even greater.


texts: Compute "up" and "right" from a direction

texts:
I have a camera class that is missing some functionality.

I need to give it the ability to, given a direction, or a point to look at, will rotate the camera left/right and up/down to look at this point or along this direction, without causing gimbal lock.

lets, say I move the camera to (10,10,10).

I want the camera to point at (0,0,0).

By normalizing the vector , I find that the direction I want to look along is (-0.577,-0.577,-0.577). We'll call this "Forward".

What I want to be able to do, is compute the local "Up" and "Right" vectors which are perpendicular to Forward.

How do I do this?


texts: How can I automatically pause my timeline at a specific time code?

texts:
I want to setup a way that the timeline will pause at a particular time/frame. I have tried this, and it doesn't work:

public PlayableDirector playableDirector;
void Update() {
    if (playableDirector.time == 4f)
        playableDirector.pause();
}

Also, is it alright to leave this in the update method?


texts: Will my game engine be compatible with physics engines?

texts:
My engine supports scene handling, cameras, and has a renderer. Also, it has a class called Drawable, which has the position, the shape and the picture of an object. The picture property has width, height, rotation and a draw method. All game objects are supposed to inherit from this Drawable class, and are added to the scene, along with a map (a collection of Tiles, that also inherit from Drawable), lights, and so on and so forth.

The shape property of a Drawable is a Polygon, a collection of user defined vertices around the position of a Drawable. This is a relative coordinate system, so [0, 0] is the position of the Drawable.

With this setup, will the users of my engine (which will probably only be me) still be able to integrate physics engines such as Box2DJS into their games?


texts:
I hope its not too early to be asking OUYA dev questions, but I just got my dev kit and I want to get my game running ASAP! I am using LibGDX as my framework for my game and launching the Android backend on the OUYA. Everything seems fine except that none of my graphics are being displayed! I can only tell what's going on because of Box2D's DebugDraw showing my physics. I am using LibGdx's Spritebatch and OpenGL ES 2.0. Everything is working pefectly on my desktop and Android (phone) backends.

Am I doing something wrong with handling my resources for OUYA? What could be the problem? Could this be because I store my graphics in the assets folder instead of /res?

Edit: Here's a logcat output: http://pastebin.com/BbPyPCcR


texts: Raycast drawing and hitting limited to inside cylinder

texts:
I'm trying to get a very basic "radar" system to work. Right now, I'm not even scanning, just looking at a known target location.

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

public class RadarScript : MonoBehaviour {

    public GameObject radar;
    public GameObject target;

    private bool found = false;

    void Update () {

        Vector3 lookLocation = target.transform.position - radar.transform.position;

        RaycastHit hitInfo;

        if (found == false) {

            Ray ray = new Ray (radar.transform.position, lookLocation);

            Debug.DrawRay (ray.origin, ray.direction, Color.red);

            if (Physics.Raycast (ray, out hitInfo, 10000.0f, 0)) {
                if (hitInfo.collider.tag == "Target") {

                    printHitInfo (hitInfo);

                    found = true;
                }
            }
        }
    }

    private void printHitInfo(RaycastHit hit) {
        Debug.Log ("TARGET FOUND!");
        Debug.Log ("Distance: " + hit.distance);
    }
}

So, here's the result can be seen here: https://gfycat.com/FloweryBraveCockroach

There's 2 problems here.

The Debug.DrawRay call is only drawing the ray inside the cylinder (radar).
The target is never being hit.

What's going wrong here ?


texts: Is it NOT feasible to create a web-based game which provides cash prizes due to bots?

texts:
Say you want to build an online web-based game of (say) Hangman where the person who continues to win eventually wins a cash prize. The more players that enter the game the more the eventual winner wins.

However, it is clear these days, that any game which has cash prizes will attract the bot-writers. I would assume that even a game like Hangman would be a trivial matter for an experienced bot-writer to create a bot which would provide a significant edge over a human player.

Based on this fact; that any online game could provide a bot-writer with a advantage over human players, my question is: is it possible to create a online game which provides cash prizes which a bot-writer would have no significant advantage over human players? Or is it simply that bots are too powerful and pervasive now in gaming and a real-money-transaction game is not feasible?


texts:
The Admob plugin for Unity - Android does not supply an EEA permission request form like the standard Android plugin does.
So, I have created my own and it works great.

My only problem is how do I check if I am in the EEA and need to request permission? Again, this feature is supplied for a standard Android app.

I know I can make a simple Android plug-in and call it but that seems a bit over the top.


texts: What's the recommended way of doing a HUD for an android game?

texts:
Basically the question is in the title.

I'm creating a RTS game and I will need buttons like attack move / attack ground, etc. I am not using any engine.

When people do games in OpenGL for android (my case), do they ever use android components to control the game or do they create their components in the game? What are the general recommended approach, if there's any?
How about more complex components like scrolling lists of items , etc?
I would also appreciate you to pair your answer with a brief comment about how was your experience using the approach(es) you describe.

Thanks :)


texts: What is the name of the perspective style of games like Final Fantasy 6, Chrono Trigger or Alundra?

texts:
What is the actual term for the 'top-down' style of the Super Nintendo games such as Final Fantasy 6, Chrono Trigger, et cetera. I'm looking for the equivalent term of:

'isometric' - (Jaggered Alliance, Final Fantasy Tactics, Fallout),
'first person' - (Half Life, Doom, Quake),
'birds eye' - (Grand Theft Auto)
? insert term here ? - (Final Fantasy 6, Chrono Trigger)


texts: Jumping higher when the player touches a trigger collider in Unity

texts:
Im using Unity engine to create a 2D platformer. My character can single/double jump, this works fine everywhere except when i am in range of a collider with a IsTrigger set to TRUE, then my character can triple jump if jump is pressed repeatedly. This can used as an exploit in my game when collecting pickups :( How can i stop this from happening? Please assist

void FixedUpdate()
    {
        // This is the Jump code
        grounded = Physics2D.OverlapCircle (groundCheck.position, groundRadius, whatIsGround);
        anim.SetBool ("Ground", grounded);
        anim.SetFloat ("vSpeed", rigidbody2D.velocity.y);

        if (grounded)
        {
            doubleJump = false;
        }

void Update()
    { //This is pressed to get the player to jump
        if((grounded || !doubleJump) && (Input.GetKeyDown (KeyCode.Space) || didPlayerJump || wasEnemyStomped == true))
        {
            JumpAction(); // rigidbody2D.AddForce(new Vector2(0,jumpForce)) triggered in this function
            if(!grounded && !doubleJump)
            {
                doubleJump = true;
            }


texts: Google Web Toolkit: Ever used for making games?

texts: I've recently come across GWT (Google Web Toolkit) and have been amazed by it. I was wondering if anyone has ever put it to use making a video game? And if they did, what their experience was, whether it was worth it and whether the game was any good.


texts: How To Destroy/Deactivate one enemy without affecting other enemies of the same type?

texts:
In my game, you jump on zombies'heads to squash them.

Currently I'm only able to have one zombie in my game. When I add another (duplicate or drag from prefab), then run the game, I can squash one enemy but when I try to jump on the second zombie's head it says "Coroutine couldn't be started because the game object "Zombie (1)" is inactive".

Here's the player's stompbox script code & below that the ZombieController script code:

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

public class StompEnemy : MonoBehaviour {

    private Rigidbody2D playerRigidbody;
    public ZombieController zombieController;

    public float bounceForce;
    // a bounce force of 12 is wonderful (set in unity's inspector)

    // Use this for initialization
    void Start () {
        playerRigidbody = transform.parent.GetComponent<Rigidbody2D>();
        zombieController = FindObjectOfType<ZombieController>();
    }

    // Update is called once per frame
    void Update () {

    }

    private void OnTriggerEnter2D(Collider2D other)
    {
        if(other.tag == "Zombie")
        {
            zombieController.Stomped();
            playerRigidbody.velocity = new Vector2(playerRigidbody.velocity.x, bounceForce);
        }
    }

}

Now here's the ZombieController script code:

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

public class ZombieController : MonoBehaviour {

    Animator zombieAnimator;
    Rigidbody2D myRigidBody;
    [SerializeField] float moveSpeed = 1f;

    public bool isAlive = true;

    // Use this for initialization
    void Start () {
        zombieAnimator = GetComponent<Animator>();
        myRigidBody = GetComponent<Rigidbody2D>();
    }

    // Update is called once per frame
    void Update () {
        if (!isAlive) { return; }
        if (isFacingRight())
        {
            myRigidBody.velocity = new Vector2(moveSpeed, 0f);
        }
        else
        {
            myRigidBody.velocity = new Vector2(-moveSpeed, 0f);
        }
    }

    bool isFacingRight()
    {
        return transform.localScale.x > 0;
        // if it's positive he's facing right, and if negative, facing left.
    }

    private void OnTriggerExit2D(Collider2D collision)
    {
        transform.localScale = new Vector2(-(Mathf.Sign(myRigidBody.velocity.x)), 1f);
    }

    public void Stomped()
    {
        isAlive = false;
        transform.localScale = new Vector2(-(Mathf.Sign(myRigidBody.velocity.x)), 1f);
        zombieAnimator.SetBool("Squash", true);
        if (isFacingRight())
        {
            myRigidBody.velocity = new Vector2(Mathf.Epsilon, 0f);
        }
        else if (!isFacingRight())
        {
            myRigidBody.velocity = new Vector2(-Mathf.Epsilon, 0f);
        }
        gameObject.layer = 11;
        StartCoroutine(WaitXSecond());
    }

    public IEnumerator WaitXSecond()
    {
        yield return new WaitForSeconds(2f);
        gameObject.SetActive(false);
        zombieAnimator.SetBool("Squash", false);
    }

}

How do I implement multiple zombies using the same script attached to each one?

When I've tried having three zombies I'd jump on the first one's head and another zombie would die (show the squashed animation, then disappear after two seconds) and the remaining zombies would no longer be jump-on-head-able, displaying the coroutine error above.


texts: Trying to understand exactly how the server sends data to the client to prevent malicious actions

texts:
I recently started coding a game with one of my friends and he is taking care of the front end and I am doing the back end.

I read many blogs/articles/tutorials on how the back end communicates with the client side and they all show different ways of doing this.

In our game the player can move his character by right clicking where they want to go. Does this mean the movement happens on the client side or should the client send a coordinate to the server and the server checks if its valid and responds with 'move_verified' which then allows the client side to carry out the action?

If this is the case how does collision take place because it will have many calculations and can cause major stress on the server. but doing it client side will make it vulnerable to malicious scripts.

The game needs to be in real time and 10 people will be playing simultaneously in a single match.I know the coords of all players have to be constantly sent to the client from the server so each player can see all players.

We are using Unity and socket.io. We successfully got communication with one another. But I just want to make sure I am on the right track before I start going deeper into the code.

I can show my code if its needed but its bare bones connections.

Thanks in advance!


texts: Node.js/V8 as a Platform for High End Local PC Game Development?

texts:
As a Web/UI dev rapidly expanding into more wide-open generalist territory, the more I learn about how its done in other languages, the more I love JS for architectural and basic messaging/event-driven concerns. For the record I am most certainly not a full-blown game-dev (although I did once write for a major gaming mag which is like saying I pretended to be friends with game devs on TV, although you guys were always my favorite folks to talk to).

Anyway, since it's fairly easy to bind C and C++ to JavaScript via Node (or perhaps more specifically V8), how reasonable would it be to assume you could write a decent 3D engine that exposed outcomes of things like collision calculations as events to the JS with the intention of getting the dynamic first-class-function party language benefits (assuming you see such things as benefits - I do) to higher level architecture and AI logic concerns without a crippling loss in performance?

Node, as I understand it, basically exposes a C event loop to JavaScript handled by V8. The JS is single-threaded, meaning any attempt to do anything calculation/IO-intensive with the JS would be foolish, but you get the advantage of not really having to sweat threads, queuing etc... since you're ideally never trying to muck with the same data at the same time. Most code would of course be heavily event/callback driven. All the file I/O concerns and other processor intensive stuff is basically C or C++ under the hood telling you when its done. Not to mention handling UI concerns directly out of the JavaScript via a webkit layer slapped on top of everything.

I'd be delighted to hear why you love/hate the idea but the core question is: is it feasible and why/not? And no, I seriously doubt my own ability to do this all by myself, although plugging an existing 3D engine in might not be outside of the realm of possibility but I'd still be learning a lot of new stuff to make that happen I'm sure.


texts:
I'm trying to understand the maths of moving points in a 3d space by making a game written in C#.

I'm looking at this wolfire blog series which explains some basic 3d maths. I've read the first two parts but am stuck on the 3rd. I know it's all really rudimentary stuff but I find Googling for help with equations really hard.

The one I'm struggling with is:

0*(0.66,0.75) + 2*(-0.75, 0.66) = (-1.5, 1.3)

How can anything multiplied by 0 not be 0?

So my question is how does this look in code:

x(a,b) + y(c,d)

I know it's basic stuff but I just can't see it.


texts: How to connect Unity with Arduino using Bluetooth module?

texts:
I will be getting data in real-time from an Arduino. I want to display that data (such as rpm of a bike) in my Unity game and use it to control the subjects in the game.

I have Bluetooth module HC-05 which I want to use to send the data from the Arduino to Unity.  I found a plugin for this on Unity store but it costs $20.

Could you guide me on how to include Bluetooth access in Unity as well as Arduino?


texts:
Problem

I have a spawn manager written in c# which spawns my game object, i use screen.width, to set the maximum screen with and -screen.width to set the minimum screen width for the spawning, but my game object spawns way off the screen.

I am using a portrait camera 2:3 instead of free aspect as my camera view, as i want my game to be in portrait mode

how do i make my game object spawn within the camera widths(max and min)?

my code

public class SpawnManager : MonoBehaviour {

    public int maxBalloons = 100;
    public GameObject balloon;
    public float horizontalMin = -Screen.width;
    public float horizontalMax = Screen.width;
    public float verticalMin = -5.0f;
    public float verticalMax = 1.0f;

    private Vector2 originPosition;

    void Start () {

        originPosition = transform.position;
        Spawn ();

    }

    void Spawn()
    {
        for (int i = 0; i < maxBalloons; i++)
        {
            Vector2 randomPosition = originPosition + new Vector2 (Random.Range(horizontalMin, horizontalMax), Random.Range (verticalMin, verticalMax));

            Instantiate(balloon, randomPosition, Quaternion.identity);
            originPosition = randomPosition;
        }
    }

}


texts: How does an FPS like Overwatch have client time run ahead of the server?

texts:
In watching the GDC talk about Overwatch netcode, it mentions that the client is always ahead of the server, that the "current tick" on the server is behind that of the client.
From their explanation this makes sense. If the client is ahead of the server, then by the time the client messages arrive at the server, the server will have caught up and can handle them when it wants them.
But how does this get setup to begin with? The client connects to the server, the server starts a game... does the client jump ahead of it's own accord? (Server says "game is starting, I'm at tick 0", and the client is like "okay, well, based on my ping I'm going to be tick 20 then")

If the server is in charge of what's going on in the game, how does the client even know what's going on in that future tick? I would assume constant extrapolation of game events from the last server update would be bad. Having the client in the past to allow it to interpolate between server updates would make a lot more sense to me.

Or am I wrong in assuming that client and server tick times need to remain in sync, and it is instead more loosely based on server updates and the number of client events that happened since that update was received, rather than the client actually caring about what tick they're on compared to the server?

It's the time/tick synchronization, despite one or the other having to be in the past, that I can't wrap my head around...


texts:
I'm making a 3D camera scene in Flash, draw using drawTriangles() and rotated and translated using a Matrix3D. I've got the camera to look after a specific point, but only on the Y-axis, using the x and z coordinates, here is my code so far:

var dx:Number = camera.x - lookAt.x;
var dy:Number = camera.y - lookAt.y;
var dz:Number = camera.z - lookAt.z;

camera.rotationY = Math.atan2(dz, dx) * (180 / Math.PI) + 270;

so no matter the x or z position, the point is always on the mid of the screen, IF and only if y matches with the camera. So what I need is to calculate the rotationX (which are measured in degrees not radians), and I was wondering how I would do this?


texts: LibGDX - Rotating sprites and still keep the positioning between them

texts:
I've been struggling with a problem regarding rotations and relative positions between sprites (in this case, the sprites are just lines) - a bit off-topic, but should i be using the ShapeRenderer class to do this, though?

Anyway, it might be quite simple but i can't seem to figure it out properly. Heres a picture of the situation: https://gyazo.com/78988e07991fedc778eaeb70f8a04d8e

Now, after trying a bunch of different approaches, this piece of code is the one i'm testing right now:

`   public class TestState extends AbstractGameState {

private static final String LINE = "lineEffect.png";

private Sprite[] sprites;

public TestState(GameStateManager gsm) {
    super(gsm);

    sprites = new Sprite[2];
    for (int i = 0; i < 2; i++) {
        sprites[i] = new Sprite(new Texture(LINE));
        // both lines starting at the same X and Y
        sprites[i].setPosition(20, 50);
        // both lines have the same size
        sprites[i].setSize(100, 2);
        // guess i might be messing up here
        sprites[i].setOrigin(sprites[i].getX(), sprites[i].getY());
    }

    // for testing purposes
    sprites[0].setRotation(-20);
    sprites[1].setRotation(45);
}

@Override
public void render(SpriteBatch batch) {
    batch.setProjectionMatrix(camera.combined);
    batch.begin();
    for (Sprite sprite : sprites)
        sprite.draw(batch);
    batch.end();
}`

Any help on this would be appreciated, thanks in advance.


texts: Getting the material name or index from a Blender FBX model in MonoGame


texts: x coordinates resets after changing speed?

texts:
I wanted to change the speed of a soldier when he enters a barbed wire texture.
Since I have multiple soldiers and multiple barbed wires I just iterate with two for-loops through all of them.

for(int j = entityWalkingRightArray.size() - 1; j >= 0; j--) {
  final entity_walking_right entity_walking_right = entityWalkingRightArray.get(j);
  for(int i = barbedWireArray.size() - 1; i >= 0; i--){
    final barbedWire wire = barbedWireArray.get(i);
    //Checks if the entity is inside the barbed wire
    if(  entity_walking_right.getX() >= wire.getX()
      && entity_walking_right.getX() <= wire.getX() + wire.getWidth()
      && entity_walking_right.getY() >= wire.getY()
      && entity_walking_right.getY() <= wire.getY() + wire.getHeight()) {

      entity_walking_right.changeSpeed();
    } else {
      //entity_walking_right.changeSpeed2();
    }
  }
}

In the class of the soldier the speed is set to 500 and the positionX is set to 200 when he is first created. I also have these two functions:

public void changeSpeed(){
    speed = 50;
}

public void changeSpeed2(){
    speed = 500;
}

In the render() function of the soldier's class the position is determined.

runningTime += Gdx.graphics.getDeltaTime();
positionX = speed * runningTime;

When he now enters the barbed wire and the speed is set to 50 then the positionX changes to 200 and he runs with a speed of 50. When I activate entity_walking_right.changeSpeed2(); then he runs with normal speed (500) through the barbed wire and starts blinking rapidly while another version which also blinks rapidly on positionX 200 with a speed of 50. I looked at the positionX value and he just "teleports" again and again between those two positions. When the "500 speed version" of him reaches the end of the barbed wire everything is normal again. I have absolutely no idea why this is happening.


texts:
I am new to game development and I have a game where the car moves and picks the monster.But now I want to automate the game so it looks like it is played automatically.
The control keys are given by the update function which is as below:

update(){
        if (keys.ArrowUp) { // Player holding up
            this.y -= this.speed * frameTime;
            this.dir = Math.PI * 0; // set direction
        }
        if (keys.ArrowDown) { // Player holding down
            this.y += this.speed * frameTime;
            this.dir = Math.PI * 1; // set direction
          }
          if (keys.ArrowLeft) { // Player holding left
            this.x -= this.speed * frameTime;
            this.dir = Math.PI * 1.5; // set direction
        }
        if (keys.ArrowRight) { // Player holding right
            this.x += this.speed * frameTime;
            this.dir = Math.PI * 0.5; // set direction
        }
        if(Math.sign(this.speed) === -1){ // filp directio of second car
            this.dir += Math.PI; // set direction
        }

So Eventually I need this update function to be automated.Automated in the sense you can think of the one car moves 3 seconds straight and 3 seconds right and so on.But the other car follows a different movement.
Incase my code is not sufficient
the working pen is here and I just want to automate the process so that the cars move in different directions and the game is automated.

Any help is appreciated


texts:
I am making a top down Pacman game. I have two sprites: one for facing up and one for facing left.

When I press W, the sprite showing is still the one for when Pacman is moving left, but I want to see the up sprite instead.

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

public class pacman : MonoBehaviour
{
    public int speed;
    Vector2 dest;
    public Transform[] points;
    // Start is called before the first frame update
    void Start()
    {
        dest = transform.position;
        speed = 25;

    }

    // Update is called once per frame
    void FixedUpdate()
    {
        //Vector2 p = Vector2.MoveTowards(transform.position, dest, speed);
       // GetComponent<Rigidbody2D>().MovePosition(p);

        // Check for Input if not moving
        if (Input.GetKey("w"))
            transform.position = Vector3.MoveTowards(transform.position, points[0].position, speed * Time.deltaTime);

        gameObject.GetComponent<SpriteRenderer>().sprite = GameObject.Find("up").GetComponent<SpriteRenderer>().sprite;

        if (Input.GetKey("d"))
            transform.position = Vector3.MoveTowards(transform.position, points[2].position, speed * Time.deltaTime);

        if (Input.GetKey("s"))
            transform.position = Vector3.MoveTowards(transform.position, points[1].position, speed * Time.deltaTime);

        if (Input.GetKey("a"))
            transform.position = Vector3.MoveTowards(transform.position, points[3].position, speed * Time.deltaTime);

        gameObject.GetComponent<SpriteRenderer>().sprite = GameObject.Find("left").GetComponent<SpriteRenderer>().sprite;
    }
}


texts: Looking for collision detection algorithms for broad and narrow phases between non-convex polyhedrons

texts:
I have some experiences on particle system simulation (namely DEM - Discrete element method), in which an individual particle with realistic shape (convex and non-convex) is approximated by gluing 3D spheres together (non-overlapping or overlapping), and act like rigid body. The collision detection is performed by the simplest sphere-sphere contact.

Nevertheless, for particle shape representing by polyhedrons, almost all the collision detection algorithms for broad and narrow phases are based on convex polyhedron (e.g. GJK). For non-convex/concave shapes, convex decomposition is required to divide the concave object into many convex components (e.g. V-HACD).

At this point, I really want to know the details on:

  1) how to store the concave objects via many convex components into memory (like BSP tree?);

  2) collision detection and contact forces calculation between
  convex-concave, concave-concave objects.

I have searched quite a few relevant books like "Real-time collision detection" and "3D game engine design", etc,  unfortunately I haven't find any details on this topic yet. Could some veteran game developers give some advice or insight on how to implement collision between concave objects?

Cheers,

David

Update 1:

Seems the physics engines likes Bullet3 and reactPhysics3D are able to simulate collision of non-convex objects. Can someone give some rough idea on how to do this? before I dig into the source codes, since i have only some academic experiences on molecular dynamics / DEM simulations mainly based on 3D spheres.


texts: How can I move bodies in Farseer, using touch input?

texts:
The player should be able to move a Farseer body with it's fingers. How can I do that? What is the best way to create a Farseer body for the player's finger so that the player can move other Farseer bodies with it? I don't know how to do that.

If the player pushes a body(for example windmill sail) hard with it's finger, then the body should move/rotate faster.

UPDATE:

I want to move the body RectangleA1 with my finger/cursor. But something isn't working.
If I press somewhere on the screen and move the cursor/finger a little bit around, then I get very often an error message in this line:

world.Step(Math.Min(elapsed, (1f / 60f)));

An exception of type 'System.NullReferenceException' occurred in FarseerForWindowsPhone.DLL but was not handled in user code

Additional information: Object reference not set to an instance of an object.

What is wrong? Why am I getting this error message?

My code:

    World world;
    Body RectangleA1, RectangleA2;
    Texture2D RectangleA1Sprite, RectangleA2Sprite;
    Body body;
    Fixture fixture;
    bool MouseJointAktiv = false;
    FarseerPhysics.Dynamics.Joints.FixedMouseJoint MouseJoint;
    private static float _displayUnitsToSimUnitsRatio = 100f;

    public static Vector2 ToDisplayUnits(Vector2 simUnits)
    {
        return simUnits * _displayUnitsToSimUnitsRatio;
    }

    RectangleA1 = BodyFactory.CreateRectangle(world, 1.50f, 0.50f, 1.0f);
    RectangleA1.BodyType = BodyType.Dynamic;
    RectangleA1.Mass = 20;
    RectangleA1.Position = new Vector2(4f, 1f);
    RectangleA1.Rotation = 0f;
    RectangleA1.CollisionCategories = Category.Cat5;

    RectangleA2 = BodyFactory.CreateRectangle(world, 3.50f, 0.50f, 1.0f);
    RectangleA2.BodyType = BodyType.Static;
    RectangleA2.Mass = 40;
    RectangleA2.Position = new Vector2(4f, 3f);
    RectangleA2.Rotation = 0f;
    RectangleA2.CollisionCategories = Category.Cat10;

    protected override void Update(GameTime gameTime)
    {
      float elapsed = (float)gameTime.ElapsedGameTime.TotalSeconds;
      world.Step(Math.Min(elapsed, (1f / 60f)));

      TouchCollection touchCollection = TouchPanel.GetState();
      foreach (TouchLocation tl in touchCollection)
      {
        if ((tl.State == TouchLocationState.Pressed))
        {
          fixture = world.TestPoint(ConvertUnits.ToSimUnits(new Vector2(tl.Position.X, tl.Position.Y)));
          if (fixture != null)
          {
            body = fixture.Body;
            MouseJoint = new FarseerPhysics.Dynamics.Joints.FixedMouseJoint(body, new Vector2(tl.Position.X, tl.Position.Y));
            MouseJoint.MaxForce = 1000 * body.Mass;
            world.AddJoint(MouseJoint);
            body.Awake = true;
            }
          }

          if ((tl.State == TouchLocationState.Moved))
          {
            if (MouseJointAktiv == true)
              MouseJoint.WorldAnchorB = ConvertUnits.ToSimUnits(new Vector2(tl.Position.X, tl.Position.Y));
          }

          if ((tl.State == TouchLocationState.Released))
          {
            world.RemoveJoint(MouseJoint);
            MouseJoint = null;
            MouseJointAktiv = false;
          }
        }

        base.Update(gameTime);
    }


texts: How to add constant force to player with sperical gravity planet.?

texts:
I have a planet and character. My player move perfect around planet with pressing key like 'w','s','a and 'D'. I want to move my player on every frame with same force around sphere. I try plane surface constant force code  like this this.rigidbody.AddForce ( 3f,3f,3f);, when start playing game this code work fine but after some movement it stop my player on specific position of planet. I want to use this code for 3D sphere.

Any one can help me how can add constant force to my player on 3d sphere.?

I want add constant force to player when game start. I don't want any kind of planet's orbits, because my player is moving on all over the planet.

I try below link but it did not working for me.
 How can i accurately simulate orbits in unity.?

Here is my Sctipts

PlayerController.cs

using UnityEngine;
using System.Collections;

public class PlayerController : MonoBehaviour {

public float moveSpeed = 10;
public Vector3 moveDir;
Rigidbody rigidbody;
// Update is called once per frame3

void Start(){
    rigidbody = GetComponent<Rigidbody> ();
}
void Update () {

    moveDir = new Vector3 (Input.GetAxisRaw("Horizontal")  ,0,Input.GetAxisRaw("Vertical"));
}
void FixedUpdate(){

    rigidbody.MovePosition (rigidbody.position + transform.TransformDirection(moveDir) * moveSpeed * Time.deltaTime);

 }
}

FauxGravityBody.cs

using UnityEngine;
using System.Collections;

[RequireComponent (typeof (Rigidbody))]
public class FauxGravityBody : MonoBehaviour {

public FauxGravityAttractor attractor;
public Transform myTransform;
Rigidbody rigidbody;

// Use this for initialization++
void Awake(){

    this.rigidbody = GetComponent<Rigidbody> ();

}
void Start () {
    myTransform = transform;
    rigidbody.useGravity = false;
    rigidbody.constraints = RigidbodyConstraints.FreezeRotation;
}

// Update is called once per frame
void Update () {

    attractor.Attract (myTransform);
  }
}

FauxGravityAttractor.cs

using UnityEngine;
using System.Collections;

public class FauxGravityAttractor : MonoBehaviour {

public float gravity = -10;
public void Attract(Transform body){

    Vector3 gravityUp = (body.position - transform.position).normalized;
    Vector3 bodyUp = body.up;

    body.GetComponent<Rigidbody>().AddForce (gravityUp * gravity);
    Quaternion targetRotation = Quaternion.FromToRotation (bodyUp, gravityUp) * body.rotation;
    body.rotation = Quaternion.Slerp (body.rotation, targetRotation, 50 * Time.deltaTime);
  }
}

I am working with this scripts, If any one help me? then please.


texts: How to calculate acceleration distance(frictionless, massless)

texts:
Object A is moving via. 2D rigidbody by velocity V and in script is defined breaking power P. Every frame of breaking (P * Time.deltaTime) is subtracted from velocity V (in other words, ignoring mass). How i can calculate distance D required to slow down to target velocity tV ?

I'm not actually using force/power but i setting velocity directly with this line of code :

Vector3 dir = transform.TransformDirection(Vector3.up);
ship.rb.velocity = Vector2.MoveTowards(ship.rb.velocity, (dir * maximalSpeed) * ship.massModifier, speedGain / ship.massModifier);

(Don't worry about ship.massModifier, Basically heavier ship hulls are slower)

I'm self-learning Indie developer and i need this for AI to my game. Enemy in space ship have nothing like space-breaks so only way how to slow down is to turn ship by 180 degrees and thrust forward in counter-direction.I need to know this to calculate distance from target required to slow down and prevent possible collision with target.


texts: I wanted to add some lighting effects to my game. The only way I know t achieve this is through a shader who calculates the lighting. But for multiple lightsources it's a bit complex at the moment. Is there an easier way to just create an overlay lighting effect?