texts: How can I structure my ASCII terrain object?

texts:
So I have this object which represents a simple ASCII "overworld". Note the code is broken, but it's for demonstration purposes...

var TerrainObj = {
    w: { name: 'water', glyph: 'w' },
    g: { name: 'ground', glyph: 'g' },

    terrain: [[w, w, w, w],
              [w, g, g, w],
              [w, g, w, w],
              [g, g, w, w]],

    generate_display: function(terrain) {
        ...
        Code that returns an array the same as terrain but containing
        the glyphs from the objects in terrain
        ...
    }
}

So as you can see, the object contains the data for different types of terrain cell, the overworld itself, and a method to covert the terrain info into an array of glyphs for printing to the screen. But of course the problem with this code is that in the terrain array, there will be an reference error to each object.

I want to be able to write out the terrain array without using more than a one-letter name, because presumably to get this to work I'd have to do something like

terrain: function() {
    var map = [[this.w, this.w, this.w, ...],
               ...
               ...
               ];
}

So is there a nicer way I can produce my "semantic" terrain layer that references objects but without me having to write lengthy references to them in my array declaration?


texts:
I do a RayCast to the terrain and then use the RaycastHit.normal to plant flags.

I would like to have the flags to point up with the normal, but have them all face the same direction. As seen in the image flag 1 points to left of the screen and flag 5 to the right. I understand why, but do not know how to rotate it.
I saw LookRotation (Unity) has an override that takes a forward direction too. I thought it would work with say Vector3.Forward, but if a flag is placed on a wall it points into the wall.
The direction or angle they face can be set by the player.
I have a hard time understanding quaternions, every time I think I do, I get stuck.
Any tips ?


texts: What programming language were PS1 games written in?

texts: Is there any common language that is used to create Play Station 1 Games? Or how can I find out what programming language is used for one of those games?


texts: UV texture mapping with perspective correct interpolation

texts:
I am working on a software rasterizer for educational purposes and I am having issues with the texturing.

The problem is, only one face of the cube gets correctly textured. The rest are stretched edges:

You can see the running program online here.

I have used cartesian coordinates, and all I do is interpolate the uv values along the scanlines.
The general formula I use for interpolating the uv coordinates is pretty much the one I use for the z-buffering interpolation and looks like this (in this case for horizontal scanlines):

    u_Slope = (right.u - left.u) / (triangleRight_x - triangleLeft_x);
    v_Slope = (right.v - left.v) / (triangleRight_x - triangleLeft_x);
    //[...]
    new_u = left.u + ((currentX_onScanLine - triangleLeft_x) * u_Slope);
    new_v = left.v + ((currentX_onScanLine - triangleLeft_x) * v_Slope);

Then, when I add each point to the pixel buffer, I restore z and uv:

                z =  (1/z);
                uv.u = Math.round(uv.u * z *100);//*100 because my texture is 100x100px
                uv.v = Math.round(uv.v * z *100);

Then I turn the u v indexes into one index in order to fetch the correct pixel from the image data (which is a 1 dimensional px array):

        var index = texture.width * uv.u + uv.v;
        //and the rest is unimportant imagedata[index].RGBA bla bla

The interpolation formula is correct considering the consistency of the texture (including the straight stripes).

I must get some sleep now, but before I get into further dissecting of every single value to see what goes wrong, Can someone more experienced guess why might this be happening, just by looking at the cube?

"I have no idea what I'm doing" (it's my first time implementing a rasterizer). Did I miss an important stage?

Thanks for any insight.

PS: My UV values are as follows:

    { u:0,   v:0 },
    { u:0,   v:0.5 },
    { u:0.5, v:0.5 },
    { u:0.5, v:0 },
    { u:0,   v:0 },
    { u:0,   v:0.5 },
    { u:0.5, v:0.5 },
    { u:0.5, v:0 }

[EDIT]

The uv values were to blame, and pixel 50 being in the second zone, as Victor pointed out.

My new uv values:

                    {u:0, v:0},
                    {u:0, v:1},
                    {u:1, v:1},
                    {u:1, v:0},
                    {u:1, v:0},
                    {u:1, v:1},
                    {u:0, v:1},
                    {u:0, v:0}

To some extent this was "a bug in my code", but also I had overlooked an important part of the process: the uv values should not just be assigned to the 8 corners of the cube.


texts: Efficient way to implement fog of war on a 2D grid with multiple actors

texts:
Lets say you have a 2D grid of tiles 100x100 and each tile can toggle fog on/off. To initialize the map you draw the tiles and toggle fog ON for each tile.

Now drop a single actor on the grid and use the actor's vision to determine which tiles need to toggle the fog OFF. As long at the actor stands still there is no further action required. When the actor moves you look ahead and toggle fog OFF on tiles near the destination and toggle the fog back ON for tiles in the area the actor is leaving. This implementation works well when there is a single actor but starts getting tricky when you add multiple actors.

Imagine the same scenario but now you have two actors standing on adjacent tiles. Initialization is the same, the initial vision is just based on each actor's starting point and vision distance. Now lets say one actor moves away while the second actor remains stationary. You can't use the original logic since, as the first actor leaves he will begin toggling the fog ON around the tiles where the second actor is standing (and still has vision).

I can think of two possible solutions and I'm wondering if there is something better that Im missing:

You could have the tile search the surrounding area for an actor with vision before toggling fog back ON but since an actor can have an arbitrary vision distance the tile won't know how far out to search unless the tile is aware of the maximum vision distance.
Each time an actor moves you could loop through every actor and redraw all vision but that seems inefficient if you have a large number of actors, especially if there is not a lot of simultaneous movement.


texts: How to stop camera rotation after reaching a specific angle?

texts:
I have a camera in my scene that I want to rotate around the player. The rotation is done when the camera rotation state is at CameraRotation.Left or CameraRotation.Right and CameraRotation.None indicates that the camera should stop rotating and just follow the player.

I want the camera to rotate around the player and stop after it reaches a specific angle (180 degrees) in the y axis in the CameraRotation.Left or CameraRotation.Right from the position the camera was at the start of the rotation. It would also be helpful if some direction is given on how to edit the SmoothFollow() method so that it follows the player with the camera still rotated.

The problem is I'm not familiar with rotations and not sure whether to use Euler angles or quaternions so any tips would help.

private void LateUpdate()
{
    if (GameManager._RotateCamera == CameraRotation.None)
    {
        SmoothFollow();
    }
    else if (GameManager._RotateCamera == CameraRotation.Left)
    {
        transform.RotateAround(player.transform.position, Vector3.up, rotationSpeed * Time.deltaTime);
    }
    else if (GameManager._RotateCamera == CameraRotation.Right)
    {
        transform.RotateAround(player.transform.position, Vector3.down, rotationSpeed * Time.deltaTime);
    }
}

// Make the Camera follow the player smoothly
private void SmoothFollow()
{
    Vector3 desiredPoistion = player.position + offset;
    Vector3 smoothedPosition = Vector3.SmoothDamp(transform.position, desiredPoistion, ref velocity, smoothSpeed);

    transform.position = smoothedPosition;

    transform.LookAt(player.transform);
}


texts: How do I instantiate a prefab to a specific coordinate?

texts: I have a prefab called ‘road’.  How can I instantiate it (using C#) such that it appears initially at coordinates (5, 5, 5)?


texts: Is a game like Subway Surfers suited for 2D or 3D?

texts:
I imaginated a mobile game and now I'm getting doubts as to whether its possible for my idea to be developed in 2D. Here's a crude illustration of the game scene:

It's pretty much like Subway Surfers. The game objective is simply a kid going along the street and buying particular fruits/vegetables. Can the sprites be changed in perspective?

As a side note, there's a reason for my particular love towards 2D. That's because:

I don't want to employ someone for 3D designing, I can manage 2D myself.
I want to finish developing this game quickly.


texts:
In my GLSL Compute Shader, I've declared a struct called ParticleData, and when I read in part of my buffer as a mat3, the size (which I assess by looking at the output) is different than if I use a float[9].

I haven't been able to find a definitive source explaining the mat3 structure. he data I'm writing to my buffer is simply 9 floats, stored in an std::array<float,9>.

What is the difference between a mat3 and a float[9], in terms of size?


texts: What is cutoff when calculating speed in this equation?

texts:
I saw a twitter post mention the following as way to make movement frame-rate independent:
changeRate = 1 - exp(-2.0 * PI * cutoff / fps)
speed -= speed * changeRate

What is cutoff?  And is fps a constant or the actual fps?
As someone unfamiliar with game development, I'm probably doing all these wrong, but the equation above is the green ball:
https://codesandbox.io/s/gallant-davinci-f7o19?file=/src/index.ts


texts: how to add an onclick event to a button?

texts:
If I will draw a button with canvas with any programming language (java,javascript....) I want to know how to add the events to what I've drawn for example If I will draw a button piture then what I have to do to be able to make an onclick event to that button in my case I'm trying to make a javascript application but In canvas it's a drawing so how could we add a button ? Please comment with any idea you have ?

  Example : When I run my game the player will find a welcome page with
  a start button drawn with Photoshop or something like that and it has
  been drawn by a canvas so how could I add a MouseListener to that
  button ?


texts: How to calculate height of a thought line over a known spot in 3rd person view?

texts:
Assuming a player object with third-person-view is in a 3d room and the center of the screen has a dot - let's call it "cursorTarget".

All I have is the position of the player, the position 5 meters in front of it - let's call it "spot" - and (if necessary) the position where the cursorTarget touches the ground if it's below the horizon.

With that given data, is it possible to calculate the height of the (thought) line between player and cursorTarget right above the spot?

I firstly thought of the intercept theorem, but I lack of knowledge of the camera height in that third-person-view.

Kind regards,
Stacky


texts: How do I detect if two 3D box shapes are overlapping each other?

texts:
I'm creating a Unity game, and for my building system inside the game, I need to detect if 2 3d box shapes are overlapping each other. What I'm doing this for is, lets say I'm building a wall, I need to detect if its overlapping another wall, or another specified shape. There will be a UI that turns red or green depending on whether its overlapping another shape. I researched a little, and I came across SphereOverlap, but it is not accurate enough for my needs.

I'm talking about a 3D context, not 2D.

Code examples(in c# preferred) would be appreciated. Thanks!


texts: Snooker/Pool AI Predicting end location of cue ball Unity

texts: I’m trying to implement a pool/snooker game. I figured the best way to implement the ball movement/potting mechanics is to use the physics simulation, apply an impulse to strike the cue ball and let the simulation deal with the rest. This seems straight forward enough but I have no idea where to start with the AI. For the AI to be anywhere near convincing it will need to consider the position of where the white ball will end up when planning what shot to play.  Can anyone offer any advice on how I can predict where the white will end up when working with the physics engine? Or does this requirement make using physics a really bad idea?


texts:
I've used this piece of code a lot in my games, but I still don't know exactly how it works.

 // Main loop
while (!done) {
     // Prepare for rendering the next frame
     // ...

     // Render single frame
    do {
        // The following loop ensures that the contents of the drawing buffer
        // are consistent in case the underlying surface was recreated
        do {
            // Get a new graphics context every time through the loop
            // to make sure the strategy is validated
            Graphics graphics = strategy.getDrawGraphics();

            // Render to graphics
            // ...

            // Dispose the graphics
            graphics.dispose();

            // Repeat the rendering if the drawing buffer contents
            // were restored
        } while (strategy.contentsRestored());

        // Display the buffer
        strategy.show();

        // Repeat the rendering if the drawing buffer was lost
    } while (strategy.contentsLost());
}

Why should I use those two do-while loops? What does it achieve? Well, I know why because of the comments, but I want to know exactly what happens

BufferStrategy: http://docs.oracle.com/javase/7/docs/api/java/awt/image/BufferStrategy.html


texts: How can I scroll sprites when swiping using Cocos2D?

texts:
I'm adding 3 sprites (layers) to CCParallaxNode:

BGLayer = [CCSprite spriteWithFile:@"Layer.png"];
[_backgroundNode
    addChild:BGLayer
    z:2
    parallaxRatio:layer1Speed
    positionOffset:ccp(screenSize.width/2,screenSize.height/2)
];

How can I create the scroll when swiping?


texts: What is elasticity? How do I implement such a thing?


texts: How can I move the snake toward the mouse cursor?

texts:
I am making a snake game. I have got it to animate. I just want it to follow the mouse pointer. I am able to find the mouse cursor position. I am also to get my snake to move to the right. What I want is to get my snake to move in the direction in the mouse pointer.

        private void timer1_Tick(object sender, EventArgs e)
    {
        Graphics g = this.CreateGraphics();
        SolidBrush greenBrush = new SolidBrush(Color.Green);
        SolidBrush blackBrush = new SolidBrush(Color.Black);
        Rectangle rect_green = new Rectangle(340 + x, 280 + y, 100, 10);
        Rectangle rect_black = new Rectangle(240 + x, 280 + y, 100, 10);
        g.FillRectangle(greenBrush, rect_green);
        g.FillRectangle(blackBrush, rect_black);
        if (x >= 340)
        {
            x = 340;
        }
        x += 5;
        greenBrush.Dispose();
        g.Dispose();

        if (MouseButtons == MouseButtons.Left)
        {
            Graphics g_two = this.CreateGraphics();
            SolidBrush greenBrush_two = new SolidBrush(Color.Green);
            SolidBrush blackBrush_two = new SolidBrush(Color.Black);
            Rectangle rect_green_two = new Rectangle(340 + x, 280 + y, 10, 100);
            Rectangle rect_black_two = new Rectangle(340 + x, 180 + y, 10, 100);
            g_two.FillRectangle(greenBrush_two, rect_green_two);
            g_two.FillRectangle(blackBrush_two, rect_black_two);
            y += 5;
            greenBrush_two.Dispose();
            g_two.Dispose();
        }
    }


texts: Is resource management a good idea when dealing with animations?

texts: New to the Unity environment here and I have a question concerning how to efficiently manage computer resources in a top down 2D game.  I have a large area that looks like a 2d rpg from the 90's and there are many water "tiles" that have an animation that plays constantly.  My question is: would it be a good idea to attach a script to the said water tiles to make them stop animating while the camera is not showing them?  The same question could be applied to any off screen animation that is currently running.  I guess what I'm not sure about is whether the constant testing for visibility is more "expensive" than the actual animation running.


texts: How to place planes for each face of frustrum in Unreal engine?

texts:
How to place planes for each side of frustrum from a Blueprint ?

How to get the rotation and size for each side of camera frustrum from Bleuprints ?


texts: Any good smartphone simulators available?

texts:
I'm trying to find a good smartphone simulator to test HTML5 games on. Doesn't matter if it is only 1 phone or a library of phones, iOS or android. As long as it's as close as it can get to the touchscreen experience.

Any suggestions?


texts: AI controlled monster vs player controlled monster stats

texts:
Does anyone know if in a pokemon game does the wild pokemon have the same stats when you catch it as it did in that battle?

and to make this a more programming question ... In that type of game should the "wild" enemies have the same limits imposed on them as if they were player controlled or should the enemies be stronger that if you caught them.

This question assumes that the creature is the same level in both cases.


texts:
I'm working on a 3D massively multiplayer space game in C++ and I'd like some advice from experienced game developers.

Essentially, the world (universe) simulated on the server is absolutely dynamic, which means the location, position, rotation of every single game object in the game is subject to change at any time, as the server is completely authoritive over this. Entire planetary systems can be moved. The server is persistent so movement of everything is simulated in real time. You could log in once, grab a spaceship, fly around a little, and log out again. Upon logging in the next day you log in to find yourself drifting towards a black hole!

So, GameDev, how would you approach sending every game object to the several clients that could be playing? This means loot on the floor, spaceships, space carriers, planets, stars, planetary systems, galaxies! I mean, how could I represent the game objects during travel to a client? As a 3D model name and associated attributes? Or maybe a single id that the client knows about, but then how would it handle users customizing their ships or adding other components to it? I am just unsure how I can replicate the game objects on the clients and allowing support of spaceship custimization and perhaps avoiding updating the game client for every new object added. Maybe it should actually send the model file over, Garrys Mod style?

Tips for network optimisations are welcome too but it isn't urgent this early in development.


texts: How can I efficiently render to multiple screens?

texts:
I know XNA is long dead, but I need it to update an old project. (I would have ported to MonoGame, but can't get multi-monitor support in it.)

My game does the following:

Wait for some objects which I get from server (in another thread)
I have some components which represent queue (about 5)
When the objects arrive, I generate texture based on the unique information, get a sprite from pool, apply the textures and add it on queue.
The game animates the queues from left to right (when one object is added to queue)

So you see lots of unique textures moving on the screen (the update is pretty fast).

Now I need to run two instance of the game to multiple monitors, and there is lag. The frame rate keeps dropping low and clearly the animation is not smooth.

Is running two games on two threads for two monitors a good idea? What could I do instead (running them on seperate processes)?
Could some one suggest a rendering optimization like skipping frames or something like that or how can i synchronize between the two instance ?
Or, even better, how can I draw on two screens from same game instance?


texts: LibGdx: How do I combine 2 GestureListener objects from 2 seperate classes into 1 GestureDetector

texts:
I'm trying to make 2 separate classes, 1 a VirtualJoystick class and 1 a VirtualButton class. I want to implement a GestureListener class in each, it just seems like good code to do so, but when I go to my main program, how do I add both GestureListener classes?

Here's some pseudocode that I'm thinking of:

VirtualJoystick vjs = new VirtualJoystick(x, y, width, height, bgImage, fgImage);
VirtualButton vb    = new VirtualButton(x,  y,  width, height, upImage, dnImage);

GestureDetector joyGestureDetector = new GestureDetector( vjs.getDetector() );
GestureDetector btnGestureDetector = new GestureDetector(  vb.getDetector() );

// Here's what I don't know how to do
GestureDetector combinedGestureDetector = ?

Gdx.input.setInputProcessor(combinedGestureDetector);

but as you can see, I'm stuck on how to combine the two, if there's a better way let me know, I'm just trying to get my code to "think through well" and be atomically contained in classes.


texts: How can I change the radius size width and other parameters in runtime in the Update?

texts:
using UnityEngine;
using System.Collections;

[RequireComponent(typeof(LineRenderer))]
public class DrawRadiusAroundTurret : MonoBehaviour
{
    [Range(0, 50)]
    public int segments = 50;
    [Range(0, 5)]
    public float xradius = 5;
    [Range(0, 5)]
    public float yradius = 5;
    [Range(0.1f, 5f)]
    public float width = 0.1f;
    LineRenderer line;

    void Start()
    {
        line = gameObject.GetComponent<LineRenderer>();

        line.positionCount = segments + 1;
        line.widthMultiplier = width;
        line.useWorldSpace = false;
        CreatePoints();
    }

    private void Update()
    {
        CreatePoints();
    }

    void CreatePoints()
    {
        line.widthMultiplier = width;

        float x;
        float y;
        float z;

        float angle = 20f;

        for (int i = 0; i < (segments + 1); i++)
        {
            x = Mathf.Sin(Mathf.Deg2Rad * angle) * xradius;
            y = Mathf.Cos(Mathf.Deg2Rad * angle) * yradius;

            line.SetPosition(i, new Vector3(x, 0f, y));

            angle += (380f / segments);
        }
    }
}

I tried this, At the top I added :
private float prevxRadius = -1.0f;
private float prevyRadius = -1.0f;
private float prevSegments = -1.0f;

Then in the Update , but it's never get to the CreatePoints it's only get to the first return no matter what values I change in the inspector.
private void Update()
    {
        if (xradius == prevxRadius) // and also check yradius and segment
            return;
        prevxRadius = xradius;

        if (yradius == prevyRadius) // and also check yradius and segment
            return;
        prevyRadius = yradius;

        if (segments == prevSegments) // and also check yradius and segment
            return;
        prevSegments = segments;

        CreatePoints();
    }

Then I tried this in the Update but it's not working either it's calling the CreatePoints after the
prevxRadius = xradius;

when I change the xradius value but the prev and current values are the same.
private void Update()
    {
        if (xradius == prevxRadius) // and also check yradius and segment
            return;
        prevxRadius = xradius;
        CreatePoints();

        if (yradius == prevyRadius) // and also check yradius and segment
            return;
        prevyRadius = yradius;
        CreatePoints();

        if (segments == prevSegments) // and also check yradius and segment
            return;
        prevSegments = segments;
        CreatePoints();
    }

The main goal is to change in real time in editor mode and runtime the values of the xradius,yradius and the segments.


texts: How to receive broadcast message in Unity?

texts:
I am trying to get the broadcasted message in overridden method of NetworkDiscovery.OnReceivedBroadcast(). For that what I had done is below:

I create class which implements NetworkDiscovery where I override the method OnReceivedBroadcast() to capture the broadcast messages.
In Unity Editor, I created an empty GameObject where I add the class in step #1 as component.

Now in code, I started the custom NetworkDiscovery class as below:

Discovery.Initialize();
Discovery.StartAsClient();

Now, when I start the broadcast in server, I am not receiving any broadcast message in OnReceivedBroadcast().

Below is my custom NetworkDiscovery class.

public class CustomNetworkDiscovery : NetworkDiscovery
{

// Use this for initialization
void Start()
{

}

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

}

public override void OnReceivedBroadcast(string fromAddress, string data)
{
    base.OnReceivedBroadcast(fromAddress, data);
}
}

One thing I noted is, If I use the NetworkDiscovery component directly in step #2; instead of using custom NetworkDiscovery class. I am able to see broadcast messages in it's default GUI.

How can I receive the broadcast message in the inherited class?

Any help will be appreciated.
Thanks.


texts: Excluding some scene elements from bloom effect

texts:
I've enabled HDR and bloom effects in my SceneKit app, but I don't want some of the elements in my scene to bloom.

For example, the lighter spots on the skybox are currently glowing.

Is there some way I can stop those elements from glowing selectively?


texts: How can I create my mesh so that textures applied to it are NOT rotated 90 degrees in Unity 3D?

texts:
I'm trying a really simple test in Unity 3D. I want to render a texture on the simplest plane possible.

So, I've created a two-triangle plane in Blender, then imported it into Unity. From there, I put that mesh on a GameObject, and then drop a texture on top of that. Every time I do this, the texture is rotated 90 degrees when drawn on the plane.

By contrast, if I just create a plane in Unity and drop the texture on that, it is not rotated.

Here is a screenshot showing the simple plane in front of the stock Unity plane:

http://cl.ly/0X052y1G0L1G0a181M1d

I noticed that the triangles in the stock Unity plane's mesh are oriented differently than the ones in the mesh I created (the hypotenuses go from bottom-left to top-right instead of bottom-right to top-left). I went into Blender, rotated the plane 90 degrees, then reimported it unto Unity, but it doesn't seem to make a difference.

What am I missing here?


texts:
How do you branch a unity project?
Suppose you have Game Project A, and say there is variant A' that requires a large convoluted plugin. But the idea is also that you want to keep developing this without the plugin getting in the way, for the other variants - say A and A'' - that don't require it.


texts: Java LWJGL - Monster follow script not working properly

texts:
I have written a script to be set off whenever a player is within a distance of the monster. The script checks if the x position is greater than or less than the players x, and same for the z. (y is automatically set to terrain) The checkWalkX and checkWalkZ functions work with my monsters walk function, which specifies a new position on a timer and walks to that position. But when I use the same kind of idea for the following, it doesnt work correctly.

public int checkWalkX(Vector3f position) {
    if (Math.floor(this.getX()) != Math.floor(position.x)) {
        if(this.getX() > position.x) return 1; //Greater
        if(this.getX() < position.x) return 2; //Less
    }
    return 0;
}
public int checkWalkZ(Vector3f position) {
    if (Math.floor(this.getZ()) != Math.floor(position.z)) {
        if(this.getZ() > position.z) return 1; //Greater
        if(this.getZ() < position.z) return 2; //Less
    }
    return 0;
}

public void follow(Player player) {
    walking = false;
    following = true;

    if(checkWalkX(player.getPosition()) == 1) this.setX(this.getX() - mobSpeed);
    else if(checkWalkX(player.getPosition()) == 2) this.setX(this.getX() + mobSpeed);

    if(checkWalkZ(player.getPosition()) == 1) this.setZ(this.getZ() - mobSpeed);
    else if(checkWalkZ(player.getPosition()) == 2) this.setZ(this.getZ() + mobSpeed);

    if(Math.floor(checkWalkX(walkToPosition)) == 0 && Math.floor(checkWalkZ(walkToPosition)) == 0) following = false;
}

For some reason when I run this script, the monster will only move within a distance of 2ish. He moves the right ways kinda, but he doesnt follow me. Would anyone know why this is?


texts: How control probability of win-lose in tile-matching games?

texts: In a random puzzle game, such as a match-three game, how can you control the probability of a winnable starting condition?


texts: How to move player out of multiple penetrating colliders?

texts:
The player in my game can teleport like Noctis from ffxv.The player shots a weapon projectile and then teleports to the projectile. I'm using raycast to calculate the weapon position after thrown. However, I need to check if the weapon is stuck in an unteleportable position after being thrown. It is possible to have multiple penetrating colliders. Ex: spear gets sandwiched between two walls that is narrow enough for the weapon to pass through but not tall enough for the player to stand. I want to somehow check for a nearby valid position for after teleporting in that situation.

I also want the teleport to fail if the weapon is horizontally in the middle of the "pipe".

I could do a bunch of overlapBox checks within a radius distance from the teleport point but that doesn't seem efficient. I want to give the player some leeway when aiming a teleport.

Also, the teleport is not immediate. The player can wait some time before teleporting to the weapon. So it is possible for a moving platform to block a raycast from the player. In which case I still want the raycast to succeed.

I'm using unity and a custom raycast based 2d character controller for normal movement.


texts: Creating polygons with separate outline/fill colors in OpenGL

texts:
Subject

I am creating a terrain map with triangle strips and I would like to make the bodies of the triangles black, but have their outlines be colored.

Problem

The solution appears to be to draw the triangles twice, once in solid black, using GL_FILL and once in color using GL_LINE.

The problem with this approach is that, since I am using depth testing and the vertices are at the same position each time, my color lines end up blending with the black lines

Attempted Solution

According to the OpenGL docs, and other sources, it looks like I should be able to utilize the glPolygonOffset() function to give polygons  that are drawn with GL_LINE "precedence" in the depth buffer by offsetting their comparison value by the argument to the function. (so I would think 1.0 would be sufficient)

This, however, does not appear to be working for me.

My Code

I have placed glEnable(GL_POLYGON_OFFSET_LINE); in my init function.

Here is the code in my draw loop where I do the actual rendering. col is the array that hods the real colors, col2 is filled with black.

Please excuse the mess.

glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

glPolygonOffset(1.0,0.0);

glDeleteBuffers(1,&vertex_buffer);
vertex_buffer = createBuffer(GL_ARRAY_BUFFER, vert, sizeof(GLfloat)*(buffer_size), GL_STATIC_DRAW);
attributeBind(vertex_buffer, 0, 3);

glDeleteBuffers(1,&color_buffer);
color_buffer = createBuffer(GL_ARRAY_BUFFER, col2, sizeof(GLfloat)*(buffer_size), GL_STATIC_DRAW);
attributeBind(color_buffer, 1, 3);

glPolygonMode(GL_FRONT_AND_BACK,GL_FILL);
glDrawArrays(GL_TRIANGLE_STRIP,0,s);

glDeleteBuffers(1,&color_buffer);
color_buffer = createBuffer(GL_ARRAY_BUFFER, col, sizeof(GLfloat)*(buffer_size), GL_STATIC_DRAW);
attributeBind(color_buffer, 1, 3);

glPolygonMode(GL_FRONT_AND_BACK,GL_LINE);
glDrawArrays(GL_TRIANGLE_STRIP,0,s);

I'm not sure if I need to call glPolygonOffset() each frame or not.

These are the attributeBind() and createbuffer() functions:

void attributeBind(GLuint buffer, int index, int points)
{
    glBindBuffer(GL_ARRAY_BUFFER, buffer);
    glVertexAttribPointer(
        index,              // position or color
        points,             // how many dimensions?
        GL_FLOAT,           // type
        GL_FALSE,           // normalized?
        0,                  // stride
        (void*)0            // array buffer offset
    );
}

GLuint createBuffer(GLenum target, const void *buffer_data, GLsizei buffer_size, GLenum usageHint)
{
    GLuint buffer;
    glGenBuffers(1, &buffer);
    glBindBuffer(target, buffer);
    glBufferData(target, buffer_size, buffer_data, usageHint);
    return buffer;
}


texts: How to manage screen and input when using libSDL2 for both desktop and Android?

texts:
I have worked on libSDL1.2. Since, the release of 2.0, SDL also supports android. So, I am trying to develop game that can work both on desktop and android. But there are few things that are confusing me.

When we are creating a window, we pass the width and height of screen. But on android game covers whole screen and different devices have different resolutions. So how can we create a screen which appears uniform on both desktop and android.
How to handle inputs like back button.
Also, how to load graphics based on DPI.


texts:
I have screen with dimensions: 800x600.
The object that I want to rotate around is located at (400,300, -50) - center of the screen.
Orthogonal projection:
Near plan - 0.1f, far plane - 1000.0f
left - 0, bottom - 0, right - 800, top - 600

Camera:
position at (0,0,0)
look at (0,0,-50)
up vector (0,1,0)

Now what I'm doing to rotate is calculate the X of "look at" using: 0 + width * cos(A).
Y remains the same (0).
Z is calculated using: -50 + width * sin(A).

Now the problem that I'm facing is that after some angle the object starts to disappear, and it doesn't rotate around the object. What can be the problem?


texts: I'm new to Farseer and have a simple question. The demos I went through didn't seem to demonstrate what I want. I would like to apply an impulse (not force) to an object at a specific position on that object. How would I go about doing this in code? (I've created the objects already). I'll be using XNA and SL, but I guess the code for this method would be the same. thanks


texts: Tools or techniques for UV unwrapping/texturing terrain with features such as roads?

texts:
I'm trying to create a map similar to Outset island in Loz: Wind Waker. Here is an example of what I'm trying to create:

As you can see, the roads more or less have dedicated tris. However, when I look at the UV data, it looks like a complete mess:

For reference, this is the texture without any overlays:

I have no idea how to go about creating a similar effect in my own game -- are there any tools I can use? What is this technique called?


texts: Imported meshes can't be picked deterministically

texts:
Using BabylonJS, I have a grid of cylinder meshes created simply by

var tile = BABYLON.MeshBuilder.CreateCylinder("tile-" + i, { tessellation: 6, height: 0.1 }, scene);

then I have following event callback

window.addEventListener("click", function (evt) {
    // try to pick an object
    var pickResult = scene.pick(evt.clientX, evt.clientY);
    if (pickResult.pickedMesh != null){
         alert(pickResult.pickedMesh.name)
});

Then mouse-click on one of tiles raises message box with correct tile name.

When I add some new meshes (3D model inside .babylon file) by

var house;
BABYLON.SceneLoader.ImportMesh("", "../Content/"
                              , "house.babylon"
                              , scene
                              , function (newMeshes)
                                { house = newMeshes[0]; });

For better imagination it's texture of house created from four different meshes which is placed over grid of cylinder tiles.

It's displayed fine but when mouse-click it too much often behave as it would totally ignore there is such a mesh and so pickResult.pickedMesh is either null or pickResult.pickedMesh.name points to tile underlaying my imported mesh in point I've clicked.

Just approximately 5% of mesh area corresponds properly to mouse-clicks (let's say in middle of roof, in middle of walls).

I've tried playing with setting some virtual (hidden) house.parent mesh for that which would not be created by importing meshes but seems as dead end.

Are you aware about some way how enforce that scene.pick(evt.clientX, evt.clientY); would respect mesh hierarchy and would consider all visible parts of overlaying texture?

Just for completeness I'm working with middle part of this 3D model (removed left and right house from that).

EDIT: Demo on BabylonJS playground


texts:
How do I add a PIXI container into a Phaser Game?

I have a game made ONLY with PIXI. but now i would like to port it to a Phaser.

All my game content happens inside a pixi container "screenContainer".  I tried to add a pixi container like this.

var created = function() {
       screenContainer = new PIXI.DisplayObjectContainer();
       var sprite = m.game.add.existing(screenContainer);
}

var.game = new Phaser.Game(gameWidth, gameHeight, Phaser.AUTO, "divId", { create: created });

but it stops here

"phaser.js" line 33067
/**
* The core update - as called by World.
* @method Phaser.Group#update
* @protected
*/
Phaser.Group.prototype.update = function () {
var i = this.children.length;

while (i--)
{
    this.children[i].update(); // UPDATE IS UNDEFINED
}

};

because Pixi.Container, does not have "update" method.

Is there any other way to add a pixi container inside a phaser game?


texts: How to use Input.GetAxis("Mouse X/Y") to rotate the camera?

texts:
I want to make a first person camera that rotates with the mouse.

I looked at the Input.GetAxis Scripting API page and found a sample code, which I have included at the bottom of my post. Upon trying it out, I realized that although it has the same basic functionality I hoped it would have, it does not keep the camera parallel to the xz plane, particularly when moving the mouse in circles. After a while the camera would be at an odd angle, and the player would be completely discombobulated!

Is there a quick fix to this code that would restrict the camera movement somehow, or is there a better way to rotate the camera?

 using UnityEngine;
 using System.Collections;

     public class ExampleClass : MonoBehaviour {
         public float horizontalSpeed = 2.0F;
         public float verticalSpeed = 2.0F;
         void Update() {
             float h = horizontalSpeed * Input.GetAxis("Mouse X");
             float v = verticalSpeed * Input.GetAxis("Mouse Y");
             transform.Rotate(v, h, 0);
         }
     }


texts:
I'm actually trying to do the reflection map for my water component, but even following the riemer's tutorial about reflection map the formulas provided doens't work. http://www.riemers.net/eng/Tutorials/XNA/Csharp/Series4/Reflection_map.php

I've read somewhere on the Internet that riemer uses Z-axis as UpVector, and I'm using the Y-axis instead.

So my system for now is somethink like this:

private void DrawReflectionMap()
{
        this.GraphicsDevice.SetRenderTarget(this.reflectionMap);
        this.GraphicsDevice.Clear(ClearOptions.Target | ClearOptions.DepthBuffer, Color.Black, 1.0f, 0);

        if (this.CameraPosition.Y > this.Options.Height)
        {
            Matrix reflectionMatrix = Matrix.Identity;

            // Camera position
            Vector3 reflectionCameraPosition = this.camera.Position;
            reflectionCameraPosition.Y = -this.camera.Position.Y + this.Options.Height * 2;

            // Camera target
            Vector3 reflectionCameraTarget = this.camera.TargetPosition;
            reflectionCameraTarget.Y = -this.camera.TargetPosition.Y + this.Options.Height * 2;

            Vector3 cameraRight = Vector3.Transform(new Vector3(1, 0, 0), this.camera.Rotation);
            Vector3 invUpVector = Vector3.Cross(new Vector3(1, 0, 0), reflectionCameraTarget - reflectionCameraPosition);

            reflectionMatrix = Matrix.CreateLookAt(reflectionCameraPosition, reflectionCameraTarget, invUpVector);

            Plane _reflectionPlane = this.CreatePlane(this.Options.Height - 0.5f, new Vector3(0, -1, 0), reflectionMatrix, true);

            if (this.Options.Draw != null)
                this.Options.Draw(reflectionMatrix, true, _reflectionPlane);
        }

        this.GraphicsDevice.SetRenderTarget(null);
}

and there is my camera: http://pastebin.com/hK9fi5DV

When I run all of this, I got this:

As you can see, it seems the reflection map is not in the right side and when I move my camera, the reflection map also moves thru the edges of the texture...

Do you have an idea from where this problem could come?

Thanks.


texts: how to devise a scoring algorithm based on elapsed time and number of moves

texts:
I want to devise an score algo for my game.
I want to award high scores to players who achieve the goal in minimum time and least number of moves.

I did this but its not going correctly:

var score = ((finishSeconds / moveCount).toFixed(2) * 100).toFixed(0);


texts:
I have reached some limits in my game experiments that seem to be solvable by working with content as 'point clouds'. My main concern now is how to convert the resulting point clouds into polygon meshes? I can't seem to find any algorithms anywhere, but I see people doing it in various programs, so it is clearly possible.

EDIT: Some elaboration. I am doing some simulation of, among other things, geological forces, and a polygon surface simply does not allow the needed detail. My goal is to create a landscape as a point cloud and use that to better simulate forces on it. But the changes are expected to be so complex that simply starting with a flat polygon surface and warping it will not be useful. So I need to taake the point cloud landscape and create a polygon surface for it, from the data it holds.


texts: How to draw an OpenGL object in another on Android? -> Eyes and Eyeballs

texts:
As i allready wrote in another question:

  I'm working on OpenGL since a Week, so i'm new to the most stuff. (also my englisch isn't the best. Hop you can understand the most anyway)
  So i'm working on an Tamagotchi App for a school project and want to make it with OpenGL.
  -> How to change/modify or animate an existing OpenGL object on Android?

So this is a further question.

My Tamagotchi is haveing to eyes. Like this:

To make it look real i want the eyes to blink and the eyeballs to move arround.
But the question here is what happens with the eyeball when the eyes are closed.
In my Situation you woud not see the eyeballs because they are the same color then the body of the Tamagotchi.
But i want the eyeballs to be a part of the eye. So if the Eye is closing the eyeballs shoud disapear where the eyes are closed whereever the eyeball is at the moment.

Here you can see the eye closed (down scaled y) but the eyeball is still visible....

I want the eyeball to be cut of or not shown where the eye is closed like this:

But i have no idear how to solve this.

Edit
Here is my Code for someone who want to look at it.
But i think it is not necessary.

public class GLEyes {

private int points = 1000;
private float vertices[]={0.0f,0.0f,0.0f};
private FloatBuffer vertBuff;

//Der Kreis wird von der Mitte der Fläche gezeichnet

public GLEyes(){

    vertices = new float[points * 2];
    for(int i=0; i< (points+3); i+=3)
    {
      double rad = 2*(Math.PI *i) / points; //Berechnung des radius

      vertices[i]=(float)Math.cos(rad);     //X Achsen Abschnitt
      vertices[i+1]=(float)Math.sin(rad);   //Y Achsen Abschnitt
      vertices[i+2]=0;                      //Z Achsen Abschnitt wird nur für 3D gebraucht
    }

    ByteBuffer bBuff=ByteBuffer.allocateDirect(vertices.length*4);
    bBuff.order(ByteOrder.nativeOrder());
    vertBuff=bBuff.asFloatBuffer();
    vertBuff.put(vertices);
    vertBuff.position(0);
}

public void draw(GL10 gl){

    lefteye(gl);
    righteye(gl);

}

private void lefteye (GL10 gl){
    gl.glPushMatrix();
    gl.glTranslatef(1, 1, 0);
    gl.glScalef(0.5f, 0.45f, 1.0f); //Skalierung einstellen
    gl.glColor4f(0.0f,0.0f,0.0f, 1.0f);
    gl.glVertexPointer(3, GL10.GL_FLOAT, 0, vertBuff);
    gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
    gl.glDrawArrays(GL10.GL_TRIANGLE_FAN, 0, points/2);
    gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);
    gl.glPopMatrix();

    gl.glPushMatrix();
    gl.glTranslatef(1, 1, 0);
    gl.glScalef(0.1f, 0.1f, 1.0f); //Skalierung einstellen
    gl.glColor4f(1.0f,1.0f,1.0f, 1.0f);
    gl.glVertexPointer(3, GL10.GL_FLOAT, 0, vertBuff);
    gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
    gl.glDrawArrays(GL10.GL_TRIANGLE_FAN, 0, points/2);
    gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);
    gl.glPopMatrix();
}

private void righteye (GL10 gl){
    gl.glPushMatrix();
    gl.glTranslatef(-1, 1, 0);
    gl.glScalef(0.5f, 0.45f, 1.0f); //Skalierung einstellen
    gl.glColor4f(0.0f,0.0f,0.0f, 1.0f);
    gl.glVertexPointer(3, GL10.GL_FLOAT, 0, vertBuff);
    gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
    gl.glDrawArrays(GL10.GL_TRIANGLE_FAN, 0, points/2);
    gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);
    gl.glPopMatrix();

    gl.glPushMatrix();
    gl.glTranslatef(-1, 1, 0);
    gl.glScalef(0.1f, 0.1f, 1.0f); //Skalierung einstellen
    gl.glColor4f(1.0f,1.0f,1.0f, 1.0f);
    gl.glVertexPointer(3, GL10.GL_FLOAT, 0, vertBuff);
    gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
    gl.glDrawArrays(GL10.GL_TRIANGLE_FAN, 0, points/2);
    gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);
    gl.glPopMatrix();

}

}


texts: How can I put my game on an NES cartridge?

texts: How can I create an NES cartridge? Is there any tutorial? I need to put a game that runs in an emulator and put it on a cartridge. How to do that? Is this possible from scratch? Or at least could I use an existing cartridge and overwrite the content there?


texts: How to make some monsters appear more dangerous than others?

texts:
My game is an open-world co-op MMO with retro graphics, permadeath and no leveling system.

The problem I'm facing, is the fact that I don't know how to make some monsters appear harder than others. Since nothing has a level, and characters can only get stronger by acquiring better items, it's difficult for me to "warn" players that a monster is difficult for them.

Fortunately, the whole world is designed by hand and we know which areas should be more difficult than others. So this means, I as developer knows which monsters are stronger than others.

But new players won't! I don't want them to get frustrated by walking into the wrong monsters reserved for higher players.

So then, how can I make monsters appear more dangerous than others?

Some things I thought of:

increasing the size of the monsters: This could work but it's not a valid rule for everything. For instance, the end-boss has small minions which are also powerful.
use of particles: I remember from playing WoW some monsters who were stronger excessively used particles to make them appear more powerful:

dividing the world into danger levels: Here I would add a danger level or something to the HUD that displays whether the player is in a safe zone or somewhere dangerous. It would change and display a notice whenever the player moves to a different danger level. Do-able although I have no clue how to portray it on the HUD.


texts: Prismatic Joint causes a crash-Box2D(cocos2d)

texts:
tried to set up a prismatic joint, but I get this error upon run time: Assertion failed: (IsLocked() == false), function CreateBody, file /Users/Aether/Developer/JFRecode/JFRecode/libs/Box2D/Dynamics/b2World.cpp, line 109.

Here is the code for the screen boundaries since I am using it as bodyB.

 CGSize s = [CCDirector sharedDirector].winSize;

//define screen boundaries
 // Create edges around the entire screen
 b2BodyDef groundBodyDef;
 groundBodyDef.position.Set(0,0);
 _groundBody = _world->CreateBody(&groundBodyDef);

 b2EdgeShape groundBox;
 b2FixtureDef groundBoxDef;
 groundBoxDef.shape = &groundBox;

 groundBox.Set(b2Vec2(0,0), b2Vec2(s.width/PTM_RATIO, 0));
 _bottomFixture = _groundBody->CreateFixture(&groundBoxDef);

 groundBox.Set(b2Vec2(0,0), b2Vec2(0, s.height/PTM_RATIO));
 _groundBody->CreateFixture(&groundBoxDef);

 groundBox.Set(b2Vec2(0, s.height/PTM_RATIO), b2Vec2(s.width/PTM_RATIO,
 s.height/PTM_RATIO));
 _groundBody->CreateFixture(&groundBoxDef);

 groundBox.Set(b2Vec2(s.width/PTM_RATIO, s.height/PTM_RATIO),
 b2Vec2(s.width/PTM_RATIO, 0));
 _groundBody->CreateFixture(&groundBoxDef);

Here is the code for the prismatic joint itself

b2PrismaticJointDef jointDef;
b2Vec2 worldAxis(1.0f,0.0f);
jointDef.collideConnected = true;
jointDef.Initialize(_shipBody,_groundBody,
                    _shipBody->GetWorldCenter(), worldAxis);
_world->CreateJoint(&jointDef);


texts: Handling increasing numbers of users (server)

texts:
For this post, we'll assume my game is multiplayer chess as it essentially requires the same functions. User logs in to the server and requests a game - the server provides a simple matching service and once done, they start the game. They get 30 seconds timed by the server per turn with 6 players in each game and however many spectators (probably very limited).

I would like to know how you would scale this.

I've considered two options:

Option 1

1) Main server to handle login / match making (which regardless of user numbers should be a fairly easy task)

2) Start new Node servers for each game that close when the game ends.

I'm not entirely sure how this could be implemented yet. (i.e. would the user connect to the main server still and the requests just be passed to the new server or would the user change connection to the new server and then back again when done? changing connection would reduce the load even further and as the two servers won't require communication between them, should be fairly simple)

Option 2

Have 1 Node server and somehow scale it.

--

Suggestions / input?

I'm planning on hosting on Amazon AWS and am well aware that the chances of my game even warranting this level of detail are probably nil but I'm taking this as a learning opportunity.

Thanks.


texts: Networking player input, UI, and ability use

texts:
I am currently working on a project to learn more about networking, specifically authoritative network architecture.

In most authoritative systems you capture a player's input queue them up then send them to the server after a certain count or time has passed. The input is "copied" to the local(client) loop and run as prediction while it waits for the server to return the authoritative state back to the local(client) for correction. The states are also sent to all connected players to recreate the observed behavior of remote players.

This system works well for things like player movement and shooting(raycasts). This gets more complicated as we start to integrate UI and player skill/ability bars. In most MOBA or MMO games there is UI that can also create "input". In these cases there isn't a truely 100% right way to accomplish the goal of networking these pieces. You wouldn't need or want the UI to be run on the server in most cases.

I have come up with a few concepts of sending the input for these to the server and would like to know if I am close to conventions that are used in professional system or if I am even thinking about it in the right way.

Case 1: Mapped config agreement
In this model the player can assign abilities to a skill bar that is both clickable and correspond to the number keys on the keyboard. This "mapping" of abilities to bar slots is stored in a player config and is sent to the server.
When the player presses a number key or clicks on an icon an input is generated and added to the input sent to the server that looks something like this:
[BarId:1,BarIndex:1,KeyId:1]
When this is received by the server the server looks up the player UI config that was sent to the server and see what abilityId was stored on that place in the bar, check if it is a valid move then update the server state.

Case 2: Server Command
In this case the player class has a UseAbility(abilityId,target) method that can be called from the client player instance but is executed on the server instance, this bypasses the normal input gathering loop by executing the command on the server immediately so incorporating this into the client/server step systems isn't clean.

Borrowing the use-case from Case 1:
The player presses the button on the keyboard or clicks the UI button. This is "mapped" locally to a specific skill. The button/keypress calls UseAbility(0x00012,self) and is run on the client and server immediately it is checked for validity and then a state is sent to all connected players.

Those are the two cases I have right now. One works well with how input is gathered and sent to the server for processing. The other makes more sense in that the code can be more explicit but it appears to break the server authoritative structure. Would you guys please tell me what you think and maybe we can have a conversation about best practices.

Thanks for reading my post.


texts: How to do camera follow without drag and drop in Inspector in Unity?

texts:
How to do camera following an object with special tag without drag and drop into Inspector?
I have 2 prefab model they are not into hierarchy for the moment when player start play. To load selected model into scene I'm using the below code.

public GameObject[] players;
void Start ()
{
LoadPlayer ();
}
private void LoadPlayer()
{
GameObject player =Instantiate(players[PlayerPrefs.GetInt(MyModel")]);
}

Because in other scene I can change my player model but I can't follow it using in c# script for camera
public Transform cause of I can't drop it in that place in Inspector. So in what way I can find current player object when game start to follow it by camera?


texts: Unity: Make a moving rigidbody stop exactly at a given distance

texts:
I have an object that only moves along Z-axis, its rigidbody has a mass of 1 and a drag of 0.2.

That object accelerates till MaxVelocity and then moves at that constant velocity in the Z-axis.

When the user pushes the brakes I want to add a force on that rigidbody to make it stop completely at a given distance (lets say 10 meters from where it pushed the button).

I've tried using: .

Which is what you get when solve for t in the first and replace in the second:

Where v is final velocity and in my case I want it to be zero.

The code

I call this method every FixedUpdate since user pushed brakes:

private float CalculateBrakeAccel(float targetPos)
{
    // targetPos has the position in the z axis the object should stop
    // i.e.: velocity is 0.0f
    float remainingDistance = (targetPos - rigidbody.position.z);
    // formula: a = 0.5 * v0^2 / (e0 - e)
    float brake = 0.5f * rigidbody.velocity.sqrMagnitude / remainingDistance;
    return brake;
}

That alone always results in a braking distance less than the expected (passing 10m as Braking distance and the object brakes at ~8.4m).
I thought it could be drag. So I tried to compensate my braking accel with the drag (for the drag calculation I used the formula found here):

public float Accel = 8f;
private float maxVelocity = 19.44f; // in m/s, approx. 70km/h
[...]
void FixedUpdate ()
{
    Vector3 forwardForce;
    if (playerController.PowerInput < 0.0f)  // if user braking, PowerInput = -1
    {
        float brakeAccel = CalculateBrakeAccel(playerController.BrakeTarget); // BrakeTarget is the transform.position.z where the user pushed the brakes + 10 meters
        forwardForce = new Vector3(0.0f, 0.0f, brakeAccel * playerController.PowerInput);
        Vector3 drag = rigidbody.velocity * Mathf.Clamp01(1f - rigidbody.drag * Time.fixedDeltaTime);
        if (drag.z > 0.0f)
            forwardForce += drag;
        else
        {
            forwardForce -= drag;
        }
        rigidbody.AddForce(myTransform.TransformDirection(forwardForce));
    }
    if (!CapAtMaxSpeed())    // if max. vel not reached, accel force can be applied:
    {
        forwardForce = new Vector3(0.0f, 0.0f, playerController.PowerInput * Accel);
        rigidbody.AddForce(myTransform.TransformDirection(forwardForce));
    }
}

bool CapAtMaxSpeed()
{
    // velocityMagnitude == rigidbody.velocity.magnitude but without sqrt() operation.
    velocityMagnitude = Vector3.Dot(rigidbody.velocity, myTransform.forward);
    if (velocityMagnitude > maxVelocity)
    {
        rigidbody.velocity = rigidbody.velocity.normalized * maxVelocity;
        return true;
    }
    return false;
}

That code gave the best results till now for any given distance (but with that specific Accel and maxVelocity). For example, it returns something in between 9.93-9.97 meters for a given distance of 10 meters (which I would accept as valid enough and a precision issue with floating operations).

The problem is if I encrease the Accel or the maxVelocity, the distance the object reaches full stop is progressively less and less than the one I'm passing to the script.

Also, if I push brake while not at maxVelocity and still accelerating (i.e., applying positive force along Z-axis), the braking distance is way shorter. Common sense suggests it should be larger in any case. And CalculateBrakeAccel() is using the current velocity at any given moment so the correct accel should be a calculated.


texts: Do SpriteBuilder's Smart Sprite Sheet need to be loaded to memory?

texts: When I create an Smart Sprite Sheet Folder using SpriteBuilder and publish it, must I load that SpriteSheet into memory "FrameCache" with code or does SpriteBuilder do this automatically (so I just have to access any image inside of SpriteSheet?)


texts: How to spin a 2D quad in place using only matrices?

texts:
In short, I have a textured 2D quad (a sprite).  I would like to rotate/spin it about the z-axis (coming out of the screen) using nothing but matrices.

If I do the following to a transform with scale in it already, the object spins, but also follows a circular path around the origin.   As a test, if I first undo the scale, then this works fine (the object spins in place).  But I'm not normally keeping scale, orientation and translation separate and then computing the matrix every frame in this case.  I'm mutating the matrix all the time.  So this isn't workable.  Can this be done without first undoing the scale?

self is the current transformation matrix (4x4)
pivot is the "center" of the quad's AABB (recomputed immediately before this)
eulerAngles is a vec3 containing {0.0, 0.0, z-angle}

/* translate to the origin */
translate(self, -pivot);

/* rotate */
rotate(self, eulerAngles);

/* go back */
translate(self, pivot);

(I'm using OpenGL, but that probably doesn't matter much here)

There are other related articles, but I didn't get to a solution.  I'm linking for reference:

Combining rotation,scaling around a pivot with translation into a matrix
How can I rotate about an arbitrary point in 3D (instead of the origin)?


texts: How do I calculate a vertex's position on the CPU?

texts:
I'm creating light processor and I need light position and vertex position after translating, rotating and scaling (to calculate distance between them to check if light is affecting my vertex somehow).

But my question is how to properly multiply my position in Vector3 with transformation matrix to get real vertex position in the world?

To calculate it in GLSL I just simply use something like this:

vec4 vertexInWorldPosition = transformMatrix * vec4(vertexPosition,1.0);

But how properly do that with my vertex (Stored in Vector3) and Matrix4 in C++ code? Do I need to multiply each row or column by my original vertexPosition stored to Vector4? I have no idea what to do.


texts: What is the best practice for creating a system of platforms that does not use Unity's tag system?

texts:
Right now I'm finalizing my character raycast controller, but have come to the realization that Unity's tag system, which I'm using as a way for my raycasts to detect different types of platforms, is limited and may cause issues further into development when I start adding more platform types, or use the controller for AI (do I want my AI to be affected the same way the player is affected by platforms?).

So far I've got a bunch of different platforms, like passable platforms, icy blocks and jump boosts. These all work great, and change the character's default movement parameters, but I rely on things like this in order for changes to be made:

if (hit.collider.tag == "platformPassable")

Is there a better way to do this? I am not the most experienced programmer, but my initial solution was to create a Platform class with a TypeOfPlatform enum that will allow me to make sub classes that implement changes based on this type, but I'm worried that having to access a component for each raycast on a platform on which the character or AI is standing will lead to horrible performance issues. Would I have to reference the base class in the character controller, or would I access the character controller in the base class?

I'm just not very comfortable with inheritances like this and would appreciate some guidance.

Update: here's a segment of my code (there are many other likes this) that hopefully helps illustrate what I believe will become problematic as I continue development:

private void MoveVertically(ref Vector3 deltaMovement)
{
    float directionY = Mathf.Sign(deltaMovement.y);
    float rayLength = Mathf.Abs(deltaMovement.y) + skinWidth;

    for (int i = 0; i < verticalRayCount; i++)
    {
        Vector2 rayOrigin = (directionY == -1) ? raycastOrigins.bottomLeft : raycastOrigins.topLeft;
        rayOrigin += Vector2.right * (verticalRaySpacing * i + deltaMovement.x);

        RaycastHit2D hit = Physics2D.Raycast(rayOrigin, Vector2.up * directionY, rayLength, collisionMask);

        Debug.DrawRay(rayOrigin, Vector2.up * directionY * rayLength, Color.red);

        if (hit)
        {
            if (hit.collider.tag == "platformPassable" || hit.collider.tag == "icePassable")
            {
                State.IsCollidingWithPassablePlatform = true;

                if (directionY == 1)
                {
                    State.IsCollidingAbove = false;
                    continue;
                }

                if (CanJumpDown)
                {
                    State.IsCollidingBelow = false;
                    continue;
                }
            }

            if (hit.collider.tag == "iceNormal" || hit.collider.tag == "icePassable")
            {
                Parameters.accelerationTimeGrounded = 1.0f;
                Parameters.accelerationTimeAirborne = 3.0f;
            }

            else if (overrideParameters == null)
            {
                Parameters.accelerationTimeGrounded = defaultParameters.accelerationTimeGrounded;
                Parameters.accelerationTimeAirborne = defaultParameters.accelerationTimeAirborne;
            }

            deltaMovement.y = (hit.distance - skinWidth) * directionY;
            rayLength = hit.distance;

            if (State.IsClimbingSlope)
            {
                deltaMovement.x = deltaMovement.y / Mathf.Tan(State.SlopeAngle * Mathf.Deg2Rad) * Mathf.Sign(deltaMovement.x);
            }

            State.IsCollidingBelow = directionY == -1;
            State.IsCollidingAbove = directionY == 1;
            CanJumpDown = false;
        }
    }

As you can see there are a lot of platform types that are somewhat similar. Plus, since this script will be placed on any character, such as the player or the enemy, both of these entities will be bound to the same movement parameters. What if I didn't want an enemy to slide around on an ice block? I'm not sure there's a way to prevent this in my code in its current structure.


texts: If I have a series of PNGs that I'd like to use as a single animated texture, would I be able to use them as they are, or would I first need to convert them to a different format, like a single TGA?


texts:
I was originally fine with diagonal movement but it's clashing with my sprite animation...

    public void keyPressed(KeyEvent e){
    int key = e.getKeyCode();

    switch(key){
        case KeyEvent.VK_W:{
            dir = 3;
            velY = -speed;
            break;
        }
        case KeyEvent.VK_S:{
            dir = 2;
            velY = speed;
            break;
        }
        case KeyEvent.VK_A:{
            dir = 1;
            velX = -speed;
            break;
        }
        case KeyEvent.VK_D:{
            dir  = 0;
            velX = speed;
            break;
        }
    }
}

public void keyReleased(KeyEvent e){
    int key = e.getKeyCode();

    switch(key){
        case KeyEvent.VK_W:{
            velY = 0;
            break;
        }
        case KeyEvent.VK_S:{
            velY = 0;
            break;
        }
        case KeyEvent.VK_A:{
            velX = 0;
            break;
        }
        case KeyEvent.VK_D:{
            velX = 0;
            break;
        }
    }
}

    public void update(){
    y += velY;
    x += velX;
}

I thought that perhaps a switch statement or an if else statement would prevent multiple keys from firing at once, but it's not working out. I even tried synchronizing some methods but still to no avail. Any suggestions? And please ignore the dir variable I use it to find the direction the player is facing.


texts:
I have a script that destroys the player object when a collider with that script touches it. The thing is that, even if there is no time specified in the script, it takes couple seconds before it destroys the player. Why does this happen, and how do I get around it?

public class DestroyScript : MonoBehaviour
{
    public GameObject player;

    void OnTriggerEnter(Collision otherObj)
    {
        if (otherObj.gameObject.tag == "Player")
            Destroy(player);
    }
}


texts: Can you remove Steamworks DRM from your own game after release?

texts:
Is it possible to remove Steamworks DRM from a Steam game after release? I'm sure that some developers have accidentally used DRM, without fully understanding the drawbacks for a consumer (the Steam client has to be running during gameplay, forced online checks etc.). Using DRM is optional, you can release your game on Steam without copy protection of any kind.
I haven't released a game on Steam, I'm asking for someone who has to answer.


texts: How do I implement the functionality of Game Makers point_direction() function?

texts:
I am trying to understand the logic behind Game Maker's point_direction(x1, y1, x2, y2) function, which takes the vector from (x1, y1) to (x2, y2) and returns the counter-clockwise angle it forms from the positive x-axis, in degrees.

(Diagram from the YoYo Games documentation of point_direction)

How do I implement this functionality in my own code?

Here's my attempt so far:

//custom_point_direction script

var x1 = argument0;
var y1 = argument1;
var x2 = argument2;
var y2 = argument3;
var targetAngle;

targetAngle = radtodeg(arctan2(y2,x1));

return -targetAngle;

Here's an example of how I want to use this function. This is the step event of an object that should face/point towards the player object:

direction = custom_point_direction(x,y,player_obj.x,player_obj.y);
image_angle = direction;

This does not work like GameMaker's point_direction() function. How do I make my custom_point_direction() work similar to point_direction()?


texts:
I've used Entitas a bit and it appeared to me as a great way of creating clean, modular code. I've seen few examples of games created with this framework, and most of them were puzzles, TD's, simple RPG's, etc. Those made me come to think, that ECS like that is not suitable for games making big use of Unity built-in physics engine. Rigidbody in this case is part of View layer, but it would affect for example "position" component, so we can't say they are really separated. Unity Physics also works at it's own pace, so there is not really a chance for independent Component-System based simulation.

Are there any generally accepted solutions, or if I don't wan't to write my own physics engine, I should give up Entitas?


texts: Converting a multidimensional array to a distance field

texts:
I've been working (as so many others before me have) on a small Voxel-type game prototype.
So far, i have a 3d array (16 by 16 by 255 elements) that contains block ids - and as of right now, 0 means "no block"/"air", and "1" means "block".
For the purposes of isosurface extraction (for use with e.g. Marching Cubes), i now want to convert this format to a distance field - but i am having a hard time understanding how to do this.
Can anyone give a short explanation or point me in the right direction?


texts: Calculating a quaternion so a bone points in a specified direction

texts:
In an attempt to solve this question, I decided to figure out the absolute (world space) directions of each joint in the source pose (as normalized unit vectors), and then rotate the joints of the target to match that direction. The problem is, how do I calculate the rotation quaternion such that the bone (the vector from the joint to its child) is in the specified direction in world-space.

UPDATE: Here's my current thinking. For each bone, the transformation matrix will be:

(1) absolute transform = local rotation * relative transform to parent in bind pose * parent absolute trasform

So, say we have 3 joints: Shoulder -> Elbow -> Wrist. We already have an absolute transform for Shoulder, and are trying to calculate the rotation for Elbow such that Elbow -> Wrist will go in the same direction it is in the source animation. From (1), the absolute transformations will be:

(2) ELBOW absolute = ELBOW local * SHOULDER to ELBOW relative * SHOULDER absolute

(3) WRIST absolute = WRIST local * ELBOW to WRIST relative * ELBOW absolute

By substitution we get:

(4) WRIST absolute = WRIST local * ELBOW to WRIST relative * ELBOW local *
                     SHOULDER to ELBOW relative * SHOULDER absolute

Our constants are: ELBOW to WRIST relative, SHOULDER to ELBOW relative, and SHOULDER absolute. WRIST local will consist only of rotation, no translation/scale. The problem is to find a value for ELBOW local such that...

(5) normalize(position(ELBOW absolute) - position(WRIST absolute)) = desired direction

(6) ELBOW local consists only of rotations (no translation/scale)

Now since we know the length of the bone and the desired direction it's possible to estimate the position part of of WRIST absolute, but the rotation will be unknown (and this problem seems impossible to do recursively, AFAICT).

My initial thought was that because WRIST local is rotation-only and I will solve for it in the next iteration of the loop, I could completely ignore it in the calculation of ELBOW local. Steven Stadnicki's answer below suggested it might not be that easy, since the orientation of the bone is important for skinning. However, if I can get this working on a stick figure I can cross that bridge later.


texts: Unity : Changing color of 2D sprite distorts sprite shape

texts:
In my 2D game, my circle shape for example, appears round, but when I change the color then it turns into a low poly circle with 8-16 points, more like a potato. Is there any way around this?

    myColor = new Color32 ((byte)colorR1, (byte)colorG2, (byte)colorB3, visibility);
    Color32 negativecolor = new Color32 ((byte)colorR1, (byte)colorG2, (byte)colorB3, (byte)(255-visibility));
    MaterialPropertyBlock props = new MaterialPropertyBlock ();
    props.SetColor ("_Color", myColor);
    rend.SetPropertyBlock (props);
    props.SetColor ("_Color", negativecolor);
    backchildrend.SetPropertyBlock (props);


texts: ArgumentNullException Parameter name: format

texts:
I have made a simple game using Unity with Vuforia and exported for Android and iOS. It works fine on Android, but on iOS it crashed and gave the error:

ArgumentNullException: Argument cannot be null. Parameter name:
format at System.Type.GetTypeFromHandle (RuntimeTypeHandle handle) [0x00000] in :0
at System.String.FormatHelper (System.Text.StringBuilder result, IFormatProvider provider, System.String format, System.Object[] args) [0x00000] in :0
at System.String.Format (IFormatProvider provider, System.String format, System.Object[] args) [0x00000] in :0
at System.String.Format (System.String format, System.Object[] args) [0x00000] in :0
at UnityEngine.Debug.LogFormat (System.String format, System.Object[] args) [0x00000] in :0
at Vuforia.TrackerManager.InitTracker[T] () [0x00000] in :0
at Vuforia.TrackerManager.InitTracker[T] () [0x00000] in :0
at Vuforia.TrackerManager.InitTracker[T] () [0x00000] in :0

  (Filename: currently not available on il2cpp Line: -1)


texts: Cocos2d v3 - addChild method make performance problems

texts:
i have currently a performance problem with the addChild method in cocos2d version 3.3. My scenario is currently that i have about ten CCNode which holds a bundle of other CCNode (about 500), i called those ten "Big Node".

The childs of the "Big Node" has their own childs (about 3). Those CCNodes are sprites.

None of the childs from "Big Node" runs any actions. Everthing happens in their update method (if this relevant).

In my main scene i figured out which "Big Node" are on screen. If their is a new "Big Node" or the old one is not anymore visible on the screen i run this code:

self = mainScene
_allBigNodes = holds all avaible big nodes

        NSMutableArray * childsToRemove = [NSMutableArray arrayWithCapacity: _children.count];

        for(CCNode * child in _children){
            if([child isKindOfClass:[BigNode class]]){
                [childsToRemove addObject:child];
            }
        }

        for(CCNode * child in childsToRemove){
            [child removeFromParentAndCleanup:NO];
        }

        [childsToRemove removeAllObjects];

        for(int BigNodeIndex = _fromBigNodePosition; BigNodeIndex<=_toBigNodePosition; ++BigNodeIndex){

            BigNode * BigNode = [_allBigNodes objectAtIndex: BigNodeIndex];

            [self addChild: BigNode];

        }

The main screen has normaly maximum two childs. The above method works fine.

In concerning to the question: sometimes in my game i have some jittery movement. So i figure out with the profiling tool that the addChild method above cost between 60-100ms.

Running Time    Self                        Symbol Name
90.0ms   79.6%  0.0                         -[CCNode addChild:]
90.0ms   79.6%  0.0                          -[CCNode addChild:z:name:]
89.0ms   78.7%  0.0                           -[CCNode onEnter]
88.0ms   77.8%  0.0                            -[NSArray makeObjectsPerformSelector:]
88.0ms   77.8%  0.0                             -[CCNode onEnter]
72.0ms   63.7%  0.0                              -[NSArray makeObjectsPerformSelector:]
71.0ms   62.8%  0.0                               -[CCNode onEnter]
42.0ms   37.1%  0.0                                -[NSArray makeObjectsPerformSelector:]
42.0ms   37.1%  0.0                                 -[CCNode onEnter]
39.0ms   34.5%  0.0                                  -[CCScheduler scheduleTarget:]
38.0ms   33.6%  2.0                                   PrioritySearch
1.0ms    0.8%   1.0                                   DYLD-STUB$$objc::DenseMap<objc_object*, unsigned long, true, objc::DenseMapInfo<objc_object*> >::grow(unsigned int)
1.0ms    0.8%   0.0                                  -[CCNode physicsNode]
1.0ms    0.8%   0.0                                   -[CCNode physicsNode]
1.0ms    0.8%   1.0                                  objc_msgSend
1.0ms    0.8%   1.0                                  objc_object::sidetable_release(bool)
28.0ms   24.7%  0.0                                -[CCScheduler scheduleTarget:]
26.0ms   23.0%  1.0                                 PrioritySearch
1.0ms    0.8%   0.0                                 -[CCScheduler scheduledTargetForTarget:insert:]
1.0ms    0.8%   1.0                                 DYLD-STUB$$objc_msgSend
1.0ms    0.8%   0.0                                -[CCNode physicsNode]
1.0ms    0.8%   1.0                               DYLD-STUB$$objc_msgSend
16.0ms   14.1%  0.0                              -[CCScheduler scheduleTarget:]
14.0ms   12.3%  0.0                               PrioritySearch
2.0ms    1.7%   0.0                               -[CCScheduler scheduledTargetForTarget:insert:]
1.0ms    0.8%   0.0                            -[CCScheduler scheduleTarget:]
1.0ms    0.8%   1.0                           -[CCNode wasRunning:]

So my question would be: Is there a way to deactivate a ccnode or what is the best solution to handle this scenario of having many ccnodes or these "Big Nodes" which are offscreen?

Thank you in advance


texts:
In Unity 5 I would like to be able to print out the CPU Usage and Available Ram left in MB. I followed the code posted on http://zamov.online.fr/EXHTML/CSharp/CSharp_927308.html and used it, however my CPU usage is always 100 and available ram is 0. According to the windows task manager CPU usage should be around 15-20% and available memory is around 4700MB. This is my first time using performance counters and further searching gives me the same code as below (from link):

public class ClientValues : MonoBehaviour {

PerformanceCounter cpuCounter;
PerformanceCounter ramCounter;
public float myCPU;
public float myRAM;

// Use this for initialization
void Start () {

    cpuCounter = new PerformanceCounter();

    cpuCounter.CategoryName = "Processor";
    cpuCounter.CounterName = "% Processor Time";
    cpuCounter.InstanceName = "_Total";

    ramCounter = new PerformanceCounter("Memory", "Available MBytes");
}

// Update is called once per frame
void Update ()
{
    myCPU = getCurrentCpuUsage ();
    myRAM = getAvailableRAM ();
    //UnityEngine.Debug.Log (myCPU);
}

public float getCurrentCpuUsage(){
    return cpuCounter.NextValue();
}

public float getAvailableRAM(){
    return ramCounter.NextValue();
}
}

What needs to change for this to give me the correct values?


texts: Is game software design the same as non-game software design?

texts:
Is the software design process for a game similar to a non-game?
Do developers create UML diagrams?
I ask because of the iterative nature of game development, I wonder if creating a UML diagram would just be a waste.


texts: Persistent game where you program your own bot(s)

texts:
I'm looking for an online game with a persistent world where you are allowed to code (and add) your own 'players' (it can be in any language / script).

A sort of RTS but for bots.

Does that even exist?


texts: Multiple Mesh Renderes with Matrices. (Direct X11, C#)

texts:
im just confused: Im trying to render 2 cubes instead of one. So in my main class i have my WORLD matrix. Then if i render the mesh the camera is multiplying all matrices with the worldProjectionBuffer etc... But how do i add the MeshRenderer´s world matrices to the of the Camera? And how do i add them to the Buffer then? :/ Please help me!

Creating the Buffer:

worldViewProjectionBuffer = new SharpDX.Direct3D11.Buffer(device1, Utilities.SizeOf<Matrix>(), ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0);

Setting the Buffer:

context.VertexShader.SetConstantBuffer(0, worldViewProjectionBuffer);

The Camera is updated every Frame:

currentCamera.Update(context, worldViewProjectionBuffer);
OnFrameUpdate();
renderer.Draw(context);

The Update of the Camera is recreating the matrices, but how would i add 2 other world matrices to the camera?

internal void Update(DeviceContext context, SharpDX.Direct3D11.Buffer worldView)
        {
            viewProjection = Matrix.Multiply(view, projection);
            worldViewProjection = world * viewProjection;
            worldViewProjection.Transpose();
            context.UpdateSubresource(ref worldViewProjection, worldView);
        }

And the MeshRenderer has it own world matrix - but how do i add the vertices from the model to it?!

 public sealed class MeshRenderer : BaseRenderer, IDisposable, ICloneable
    {
        private Model mesh;
        private Material material;
        private Matrix world;
...

Thank in Advance,

Best Regards, Kerbo


texts: Sfml: Sprite scale transformation animation

texts:
Is there any way to animate a transformation on sf::Sprite like setScale or setPosition?

ie: sprite.setScale(0.5f,0.5f);. I want the transition between normal and half scale be smooth.

Thanks!


texts: Online leaderboard systems for (small/indie) PC games?

texts:
Are there any free/affordable systems/libraries out there for adding online features to a small PC game? (most likely, for a small primarily-Windows-based indie game)

I'm not concerned about matchmaking or online multiplayer - but I'm interested in leaderboards, and maybe slightly more advanced features, such as the upload/download of user-created-content (e.g. replays or player-created levels). Maybe even automatic updates or downloadable content?

Whilst it probably shouldn't be too hard to implement at least the very basics from scratch, it seems like a big wheel to reinvent, and a tried-and-tested system would be preferable, to reduce development time, and reduce the chance of gaping security holes. Is there anything in reach of low/no-budget indie developers?


texts:
I am trying to move my image along with the shape so I can make the collider with the shape (some kind of space shooter) but my image does not move along with the circle I make for it. It dissapears to the next spawned circle instead of completing it's track towards the bottom of the screen (I want to make a vertical linear move from top to bottom but everytime another circle+image spawns, the previous circle goes down but the image spawns to the next circle and so on)

update method:

    timePassed+=delta;
    if(timePassed>700){
        timePassed=0;
        RandomInt = random.nextInt(400);
        gigis.add(new Circle(200+RandomInt,0,40));
        gigiSkin.add(new Image("img/gegi.png"));
    }

    for(Circle c: gigis){
        c.setCenterY(c.getCenterY()+(delta/6f));
        gigiY= c.getCenterY()+(delta/6f);
    }

    for(Circle c: bullets){
        c.setCenterY(c.getCenterY()-(delta/1.25f));
        projY = c.getCenterY()-(delta/1.5f);
    }

render method:

    for(Circle c: bullets){
        g.draw(c);
    }
    for(Image skin: bulletSkin){
        skin.draw(projX,projY,80,80);
    }

    g.setColor(Color.red);
    for(Circle c: gigis){
        g.draw(c);
    }
    for(Image skin: gigiSkin){
        skin.draw(200+RandomInt,gigiY,80,80);
    }
}


texts: Combining cylindrical Billboarding and aligning with velocity (unity)

texts:
I'm trying to make a custom GPU particle solution on Unity to fullfill some needs on my project, using compute shaders and custom shader + Graphics.DrawProceduralNow() to draw them.

While I managed to make the system, I'm struggling making the particles cylindrical billboards and align them to their velocity axis as I'm not really used to work with matrices.

I achieved to make both effect working individually (using usefull ressources on the forum) but I can't manage to combine the two rotations without obtaining wrong results

v2f vert(uint id : SV_VertexID, uint inst : SV_InstanceID)
{
    v2f o;

    //Vertex position
    float3 q = quad[id];

    float3 newPos = q * particles[inst].size * _SizeMul;

    //PARTICLE DIRECTION

    float3 particleDirection = normalize(particles[inst].velocity);

    float3x3 rotMatrix;

    float3 xaxis = cross(float3(0,0,1), particleDirection);
    xaxis = normalize(xaxis);

    float3 zaxis = cross(xaxis, particleDirection);
    zaxis = normalize(zaxis);

    //Matrix for particle direction
    rotMatrix[0].xyz = float3(xaxis.x, particleDirection.x, zaxis.x);
    rotMatrix[1].xyz = float3(xaxis.y, particleDirection.y, zaxis.y);
    rotMatrix[2].xyz = float3(xaxis.z, particleDirection.z, zaxis.z);

    newPos = mul(rotMatrix, newPos);

    //CYLINDRICAL BILLBOARDING

    // Distance between the camera and the center
    float3 dist = _WorldSpaceCameraPos - particles[inst].position;

    // With atan the tree inverts when the camera has the same z position
    float angle = atan2(dist.x, dist.z);

    float cosinus = cos(angle);
    float sinus = sin(angle);

    // Matrix for billboarding
    rotMatrix[0].xyz = float3(cosinus, 0, sinus);
    rotMatrix[1].xyz = float3(0, 1, 0);
    rotMatrix[2].xyz = float3(- sinus, 0, cosinus);

    newPos = mul(rotMatrix, newPos);

    newPos += particles[inst].position;

    o.pos = mul(UNITY_MATRIX_VP, float4(newPos.xyz,1));

    o.uv = q + 0.5f;

    o.col = particles[inst].alive * particles[inst].color;

    return o;

}

Another way to say it is i would like Y to point toward the velocity direction and then rotate the quad around it's new Y axis to make the billboard point at best toward camera.

Any help would be much appreciated and any other approach for cylindrical billboarding that would work once quad is aligned to velocity vector would be welcomed too. Have a good day!


texts: How can I detect hex edges and corners for Catan map?

texts:
The following messy code implements a decent hex map, but I have no way to detect edges and corners:

function blankMap($scenario_array){
    $hexMap = null;
    $hexCss = "";
      echo $hexCss.$hexMap;
    }
}

How do I move on from here so that I can click on edges and corners of the hexes?


texts:
In a level editor that supports multiple editing modes, written in an oop language, how would you go about switching from mode to mode, considering that data itself remains the same?

I am using a MVC pattern like so.

A data model for the level's structure.
One model for the editor's state depending on the current editing mode and it contains data about the user's editing activities that was not applied or does not affect the level model (i.e what entities or item are currently selected).
A view for each mode (they all render similarly but differently cause they put emphasis on different items in the level).
Controllers accepting input and manipulating the state. These also differ from one mode to another.

The Controller accepts input from the user. It calls the corresponding methods on the State model which in turn modifies the LevelData. The controller refreshes the View after changes are made to the LevelData and State so these changes are properly reflected to the user.

Currently, to switch, I have all controllers inherit from a base controller that contains the mode switching capability. I have a class called AppContainer (each mode is like an app) that is being informed that a switch needs to be made. This class deactivates the controller and activates a new controller instead. The new controller refreshes the view and clears the state upon reinitialization.

I am wondering if there is a simple way to accomplish the same thing that I haven't though of.

I basically need to switch the Controller, the State and the View. HaxeFlixel does this pretty elegantly. Does anyone know how that is accomplished in high level abstraction?


texts:
I'm working on an old-style isometric RPG like the early Diablo or Fallout games. It has a central story with branching paths, and a lot of player freedom to explore the open world. The combat system is pretty integral to the game as well, considering the number of spells, attacks and enemies I'm hoping to add.

Currently I'm wondering whether I should have fixed item stats, or have them randomised within a given range (say, +-0-10% from a given value). But I can only see disadvantages with the randomised stats system. If the range is too large it'll become grindy, and if it's too small it'll become irrelevant.

Could someone give me a list of the pros and cons for each approach?


texts: Moving character controller on twisted track

texts:
I am trying to move a ball using Unity's character controller component. I want to move the ball along the twisted track so that it can go upside down.
Below is the video of the problem when moving using Unity's Character Controller:
https://gfycat.com/dismalaridjoey
I want the ball to move upside-down along the twisted track.
I have the following questions:

What kind of modifications are required to achieve this using a
character controller?
Which other methods (physics or splines) can be used to implement such ball movement? I am flexible to switch the appraoch.

I would appreciate any suggestions and thoughts on this topic. Thank you.


texts: Game Engine Design – Ubershader - Shader management design

texts:
I want to implement a flexible Ubershader system, with deferred shading. My current idea is to create shaders out of modules, which deal with certain features, such as FlatTexture, BumpTexture, Displacement Mapping, etc. There are also little modules which decode color, do tone mapping, etc. This has the advantage that I can replace certain types of modules if the GPU doesn't support them, so I can adapt to the current GPU capabilities. I am not sure if this design is good. I fear I could make a bad design choice, now, and later pay for it.

My question is where do I find resources, examples, articles about how to implement a shader management system effectively? Does anyone know how the big game engines do this?


texts: How do I save which NPCs the player has talked to?

texts:
I have built a save system that saves the players name, x and y location, map and the direction they are looking at in JSON.

{
data: [
    {
        x: 400
        y: 424
        d: UP
        name: Ezia
        mapname: startmap
    }
]
}

Now I have dialogue in my game, but I want to progress in that as well. So for example you have "Guy 1" who I just talked to, he says some stuff, afterwards he says something else, different text. How can I save it so the game knows I have already talked to "Guy 1"? I need to do this for a lot of NPCs eventually, so it would be nice if I didn't do stuff like:

Guy1TalkedTo = 1
Guy2TalkedTo = 0
Guy3TalkedTo = 1

Etc.


texts: Are there special APIs used to make PS4 games?

texts: Game engines can build games for PS4, but how are those engines written to support it? Is there any special kind of support, API or something provided by the PS4? Does it have like a new programming language or new specification like OpenGL or DirectX?


texts: My object just automatically "launch" or do stuff without me clicking on my mouse when it respawn?

texts:
I've already set the ball (my object) initially at the start where I have to click for the ball to launch from the paddle (it's a ping pong game).
private void LockBallToPaddle() {
    Vector2 paddlePos = new Vector2(Paddle.transform.position.x,
        Paddle.transform.position.y);
    transform.position = paddlePos + paddleToBall; //For the ball to stick to the paddle
}

Launch the Ball:
private void LaunchBall() {
    if (Input.GetMouseButtonDown(0)) {
        hasStarted = true;
        rbBall.velocity = new Vector2(Random.Range(-2f, 2f),speedVelocity);
    }
}

Both of which I put under Update()
private void LaunchBall() {
    if (Input.GetMouseButtonDown(0)) {
        hasStarted = true;
        rbBall.velocity = new Vector2(Random.Range(-2f, 2f),speedVelocity);
    }
}

Now the problem is when my ball hits a certain collider, I want it to respawn the position back to the paddle. So instead of Destroy the game object, I just copy and paste those same methods under collision
if (collision.gameObject.tag == "bottom") {
    LockBallToPaddle();
    LaunchBalls();
}

But now it just launches straight away from the paddle when hit the collision without me clicking anything like what "Launchballs()" intended to. What should I do?


texts: Weird problem with advect program in fluid simulator

texts:
I implemented 2d fluid simulator. Solver runs entirely on GPU. All works fine... on my work PC. But on home PC I have some awful glitches, and I can`t understand how to fix them. Empirically I discovered that problem is localized somewhere in advect program. This is very strange cause at work I have integrated video, and at home — NVIDIA GeForce 9800 GT. Here is the GLSL source of advect program (some lines were dropped for clearness):

#version 130

out vec3 value;

uniform sampler2D q;
uniform sampler2D velocity;
uniform float dt;
uniform float inverseSize;

void main()
{
  vec2 p = gl_FragCoord.xy * inverseSize;

  vec2 np = p - dt * texture(velocity, p).xy;

  value = texture(q, np).xyz;
}

And some screenshots.

Work PC:

Home PC:


texts: Sprites blurred in Unity (filter mode set to point)

texts:
I'm new to Unity and I'm developing Android game. When I connect my phone with Unity Remote and launch game, all textured are blurred and they look awfull.

Did some research and set Filter mode to point as everyone suggested but that didn't work at all.

My sprite settings are as follows:
- Texture type: Sprite (2D and UI)
- Packing Tag: isn't set
- Pixels per unit: 100
- Pivot: Center
- Generate Mip Maps: unchecked
- Filter mode: point

Can anyone help me with this?


texts:
I am trying to implement a simple shader for point lights, but I am struggling with the attenuation function. I know that normally you would use three coefficients (constant, linear, and quadratic), however in my framework point lights only have position, intensity (color) and range.

Is there any formula that only requires the light's range to work?


texts: Implementations of task-based parallelism in game engines_

texts:
I'm looking for implementations of this because I'm having an especially hard time understanding how data is usually handled. As I understand it, simply using critical sections and locking code regions where modification of shared resources happens is a no-go, because locking and unlocking imposes quite severe performance penalties on the program.

So another approach would be to simply copy all relevant data when I create the task and pass it to a thread and overwrite the original data at the end or at the beginning of the following frame with whatever the worker thread returns to me... which results in the problem that if two tasks modify the same resource... it's unclear to me how to meaningfully resolve that "result collision".

I guess it's theoretically possible to apply only deltas of incoming changes: Let's say each entity, at the beginning of a frame, checks the messaging system for modifications to itself. If there are n modifications to the entities component e, then the new e would probably just be the old e plus the sum of all "old_e - new_e" for each n. But that seems kind of ugly and I'm not sure if it even works for things which are not just simple changes to single numbers.

Are there any open source examples which implement this system that I could actually look at?


texts: Getting a pixel of Sprite at the cursor position in Unity

texts:
Summary: I've been trying to figure out a way to use simple box colliders as a nice and efficient "first pass" collider. For the "second pass", I want to check that the area clicked has an alpha value > 10%. I know this is generally possible with graphics programming, but I'm struggling to find a way to do this in Unity2D with packed sprites (packed via the native Sprite Packer tool).

What I was hoping to do (but Unity will not allow) would've been something like...

// Check to see if a point intersects with a solid color
private bool CheckPoint()
{
    Vector2 cursorWorld = Camera.main.ScreenToWorldPoint(Input.mousePosition);

    //foreach (Collider2D col2D in Physics2D.OverlapPointAll(cursorWorld))
    foreach (RaycastHit2D hit in Physics2D.RaycastAll(cursorWorld, Vector2.zero))
    {
        if (hit.collider.gameObject != gameObject) continue;

        foreach (SpriteRenderer sprRend in hit.collider.gameObject.GetComponentsInChildren<SpriteRenderer>())
        {
            Texture2D tex = (Texture2D)sprRend.sprite.texture;

            // this is the missing link; easy with 3d, but impossible with 2d?
            Vector2 pixelUV = hit.??????;

            int uvX = (int)(pixelUV.x * tex.width);
            int uvY = (int)(pixelUV.y * tex.height);

            Color hitColor = tex.GetPixel(uvX, uvY);

            if (hitColor.a > 0.1) return true;
        }
    }

    return false;
}

So far: I've been able to find some solutions for doing this with (3D) meshes and 3D colliders. However, the 2D colliders do not include the UV data that would be needed to make this work.

Someone was also able to get this working for their specific game using SpriteManager2 (which we're not using since Unity 4.3 makes SM2 mostly unnecessary) and posted their solution here...  http://answers.unity3d.com/questions/17903/detecting-mouseclick-on-pixels-in-sprite-using-sm2.html and I think the same approach might work with minor adaptations for Unity2D, but I'm thinking there might be a more robust approach.

I'm also looking at trying to do something like http://answers.unity3d.com/questions/687116/what-is-the-easiest-way-to-convert-raycasthit2d-to.html but even if I can calculate the local UV, that wont help me with the real UV for the packed sprite unless I can somehow get the sprite's UV offset into the sheet.


texts:
I have a camera that follows the position and direction of the player. These are updated using spin and velocity. The velocity is updated like so:

auto velocity = get_velocity();
velocity += get_acceleration().x * get_right();
velocity += get_acceleration().y * get_up();
velocity -= get_acceleration().z * get_forward();

set_velocity(velocity);

... where acceleration is relative to the object, not the world. This is the first time I have used OpenGL and I am not sure if this is the best solution, but it does what I want. I was wondering if there is a better way to do this using OpenGL Mathematics (GLM).

Additionally, this method works like a rocket, which is good for what I am trying to do, but if I want something more like a human, I have to change it to:

auto velocity = get_velocity();
auto const y = velocity.y + get_acceleration().y;
velocity += get_acceleration().x * get_right();
velocity -= get_acceleration().z * get_forward();
velocity.y = y;

set_velocity(velocity);

... to prevent the player from being able to fly by looking up. Is there a way of simplifying this case, too?

Acceleration is defined as:

switch (dir) {
    case left:  return glm::vec3(-1,  0,  0);
    case right: return glm::vec3( 1,  0,  0);
    case front: return glm::vec3( 0,  0, -1);
    case back:  return glm::vec3( 0,  0,  1);
    case up:    return glm::vec3( 0,  1,  0);
    case down:  return glm::vec3( 0, -1,  0);
    default: assert(false);
}