texts:
I'm currently working on taking an idea I've been toying with in C++ and bringing it into Unity, but I'm struggling to figure out how to make it performant and how to do things the "Unity way".

My world is made up of cubes and cube shaped tiles viewed from a fixed angle (à la Monument Valley). I've watched their behind the scenes video and seen that they have a step in their workflow that removes the unused faces from their cubes and combines them into quads. I want to achieve something similar.

Ideally I want to build up my world using a bunch of prefab cube objects (with different textures and components) and then run some kind of process over my scenes before I export/play to optimize them (otherwise I'm going to be doing potentially thousands of draw calls that I don't need to do and have lots of colliders I don't need).

My questions are as follows:

What hooks does Unity provide to do this sort of processing? Should I be using PostProcessSceneAttribute for this?
I understand that I can use Mesh.CombineMeshes to combine my cubes, but what about for their colliders?
How can I determine groups of cubes that are touching (for removing faces and combining colliders)? In my C++ project I keep all of the blocks in a 3D array and use that, but using the Unity editor to place the blocks means I don't have this available. Is there a way I could easily build one from my scene, or is there a more "Unity" way of doing this?
Is my approach sensible? Or should I drop the idea of placing individual cubes in the editor and take a different approach?


texts: How to properly interact with game objects in Unity3D?

texts:
I am trying to make a game where player will be placed in the scene and the goal is to explore it. He can interact with game objects that player can find in the environment, like picking object, examining, dropping and putting back. Basically it is something like first person exploration...

So the problem is how to properly implement code regarding interaction. One way I see and saw it on the internet is Raycasting. So the idea would be to in Update() method place Raycast fire code and see what it hits. Also all game objects with which player can interact are placed on separate Layer and also limit length of Raycast (which is obvious thing to do as player cannot interact with objects that are like 10 meters from him)...

So as I understand, game objects should have at least some kind of collider (I know box and sphere colliders are simple, but sometimes I will need to use more complex one)...

That being said, I wonder is this right approach:

Separate layer for interactable objects
Raycast that checks objects in that layer
Raycast length limited to like 1 meter

This approach should not be that much CPU consuming or is there any other way?

I am also thinking to putting some invisible box area (trigger) where raycasting would make sense, but I am not sure will this be overhead or not....

So, at the end what would be the right approach to this?


texts: How to make the transparent parts of a sprite also clickable using a Raycast

texts:
I have been making using the following code to add mouse clicks to my game objects.

RaycastHit2D hit = Physics2D.Raycast(Camera.main.ScreenToWorldPoint(Input.mousePosition), Vector2.zero);
    if ((hit.collider != null && hit.collider.gameObject.name == gameObject.name)
    )
    {

    //do something here
}

I have a game object which I made using a sprite with transparent areas. I would like the transparent areas to also be recognized as the game object being clicked. I am not sure if this can be achieved using a raycast. If not, I am open to other ways of achieving the same result.


texts: Circle ceases to be a circle when radius is below a certain value

texts:
I'm using the LineRenderer component to draw a circle. It renders fine, but it's a little too large. The smallest I can set the radius is .06f. If I try to set the radius to anything less than that, such as .05f, it ceases to become a circle and resembles more of an oblong shape instead. I posted a couple of pictures below, as well as the full script that I'm using. You can attach this script to your own gameObject and test it out for yourself. If anyone can help, I'd really appreciate it.

radius is at .06f

radius is at .05f

using UnityEngine;

[RequireComponent(typeof(LineRenderer))]
public class Circle : MonoBehaviour
{
    private LineRenderer _line;

    [SerializeField]
    private float _radius;

    private void Start()
    {
        _line = GetComponent<LineRenderer>();
        DrawCircle(_radius);
    }

    public void DrawCircle(float radius)
    {
        var segments = 360;

        _line.useWorldSpace = false;
        _line.startWidth = .03f;
        _line.endWidth = .03f;
        _line.positionCount = segments + 1;

        var pointCount = segments + 1; // add extra point to make startpoint and endpoint the same to close the circle
        var points = new Vector3[pointCount];

        for (int i = 0; i < pointCount; i++)
        {
            var rad = Mathf.Deg2Rad * (i * 360 / segments);
            var x = Mathf.Sin(rad) * radius;
            var z = Mathf.Cos(rad) * radius;
            points[i] = new Vector3(x, 0, z);
        }

        _line.SetPositions(points);

        transform.Rotate(Vector3.right * 90);
    }
}


texts:
I have a capsule (sphere sweep) that I've computed the collision on a mesh with.

I know the point of impact and normal of the face it collides with.

My moving object - I'm using a capsule to represent it for collision purposes - has a quaternion describing its direction of travel.

How do I compute the new quaternion for the object to travel in on the bounce?


texts: i'm making a video game, and i'm having, i think, a concept problem. The game will be a platformer which will use tile maps, so to start i will create a mask matrix indicating the tiles to be loaded, and etc..., so my problem is, how to handle the scrolling? should i create a giant mask matrix indicating in each position of the whole level what is supposed to be loaded, and according to the position of the player, change the section to be drawed?? Is this a correct approach to this situation??


texts: How should bullet reflections be implemented?

texts:
Im working on a tank game where bullets are relected off of walls.  The formula for a relfection is r=d−2d⋅n∥n∥2n where d is the incoming vector and n is the normal of a wall.  My bullets stick to the walls and then "bounce" off at the corners; an undesirable effect.  Im honestly questioning my formula implementation at this point.
func collision():
    for i in get_slide_count():
        var collision = get_slide_collision(i)
        if collision.collider.is_in_group(globals.wall_group):
            var normal = collision.normal
            velocity = velocity - ((2 * velocity.dot(normal)) / normal.length_squared()) * normal
            rotation = velocity.angle() + PI

if i use the is_on_wall function and simply negate the velocity this does produce a bouncing effect but not a correct one.  I still need the normal.
I orignally used rigid bodies as seen in the image.  But i have switched to kinematic bodies.


texts: Access Violation when trying to bind Vertex Object Array

texts:
I've just started digging into OpenGL and I've run into a problem trying to set a VOA.

It's giving me a run-time error of :

An unhandled exception of type 'System.AccessViolationException'

At

    // Create and bind a VAO
GLuint vao;
glGenVertexArrays(1, &vao);
glBindVertexArray(vao);

I have searched the internet high and low for a solution and I haven't found one. The rest of my function looks like this:

int main(array<System::String ^> ^args)

{

// Initialise GLFW
if( !glfwInit() )
{
    fprintf( stderr, "Failed to initialize GLFW\n" );
    return -1;
}

glfwOpenWindowHint(GLFW_FSAA_SAMPLES, 0); // 4x antialiasing
glfwOpenWindowHint(GLFW_OPENGL_VERSION_MAJOR, 3); // We want OpenGL 3.3
glfwOpenWindowHint(GLFW_OPENGL_VERSION_MINOR, 3);
glfwOpenWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); //We don't want the old OpenGL

// Open a window and create its OpenGL context
if( !glfwOpenWindow( 800, 600, 0,0,0,0, 32,0, GLFW_WINDOW ) )
{
    fprintf( stderr, "Failed to open GLFW window\n" );
    glfwTerminate();
    return -1;
}

// Initialize GLEW
if (glewInit() != GLEW_OK) {
    fprintf(stderr, "Failed to initialize GLEW\n");
    return -1;
}

glfwSetWindowTitle( "Game Engine" );

// Create and bind a VAO
GLuint vao;
glGenVertexArrays(1, &vao);
glBindVertexArray(vao);

glfwEnable( GLFW_STICKY_KEYS );


texts:
I have path areas set up in a game I'm making for canvas/html5 and have got it working to keep the player within these areas. I have a function isOut(boundary, x, y) that returns true if the point is outside the boundary. What I do is check only the new position x/y separately with the corresponding old position x/y. Then if each one is out I assign them the past value from the frame before. The old positions are kept in a variable from a closure I made.

like this:

opos = [x,y];//old position
npos = [x,y];//new position

if(isOut(bound, npos[0], opos[1])){
    npos[0] = opos[0]; //assign it the old x position
}
if(isOut(bound, opos[0], npos[1])){
    npos[1] = opos[1]; //assign it the old y position
}

It looks nice and works good at certain angles, but if your boundary has diagonal regions it results in jittery motion. What's happening is the y pos exits the area while x doesn't and continues pushing the player to the side, once it has moved the player to the side a bit the player can move forward and then the y exits again and the whole process repeats.
Anyone know how I may be able to achieve a smoother slide? I have access to the player's velocity vector, the angle, and the speed(when used with the angle). I can move the play with either angle/speed or x/yvelocities as I've built in backups to translate one to the other if either have been altered manually.


texts: Programmatically generated mesh vertex colors not showing up in Unity?

texts:
I'm sorry if this is an obvious thing to solve but I just can't figure it out...did I miss something...I've generated a mesh and during vertices generation I've also set its colors (and colors32 just in case) by reading those values from a ply file, and afterwards I've added a number of vertex color shaders but none of them will show the vertex point colors in play mode, it's either solid black or just like I added no material to the mesh (which I've tried doing manually in play mode too).

Did I miss something please?


texts: Average for damage formula (Min-Max Attack - Min-Max Defense)

texts:
We wanted to create a quick spreadsheet to rapidly adjust enemies' Attack and Defense from players' estimated values of Attack and Defense.

One of the key values to adjust is the "hits until dead", and to derive this we need an average of the damage.

A basic calculation of the damage is done as following. Both players and enemies have minimum and maximum values for attack and defense. Two random values are generated between these and the difference is the damage received. Note that the minimum damage is zero (or miss).

attack = random(attack_min, attack_max);
defense = random(defense_min, defense_max);
damage = max(attack - defense, 0);

When attack_min > defense_max, a simple formula like this can be used to obtain the average damage:

attack_mean = (attack_min + attack_max) / 2;
defense_mean = (defense_min + defense_max) / 2;
damage_mean = attack_mean - defense_mean;

But in the other case, there is a chance of missing, and this formula is not accurate.

Let this be an example where the initial formula works:

attack_min = 10; attack_max = 20;
defense_min = 0; defense_max = 5;

attack_mean = (10 + 20) / 2 = 15;
defense_mean = (0 + 5) / 2 = 2.5;
damage_mean = 15 - 2.5 = 12.5;

And, this is an example where it does not:

attack_min = 10; attack_max = 20;
defense_min = 5; defense_max = 35;

attack_mean = (10 + 20) / 2 = 15;
defense_mean = (5 + 35) / 2 = 20;
damage_mean = 15 - 20 = -5;

There is low chance, but there is damage between 5 and 15! Empirical values suggest an average of around 2.

So, the request is the following: we need a formula that gives us the average damage regardless of whether defense is higher than attack or not. (We need a formula, not a procedure, so RNG is off the table).

Can anyone enlighten us on this? Thank you!!

Thanks to @DMGregory's answer, a reader may find the Excel VBA custom formula below, in case it can suit they.

Function TriangleSum(n)

TriangleSum = WorksheetFunction.Max(n ^ 3 + 3 * n ^ 2 + 2 * n, 0) / 6

End Function

Function GetMeanDamage(attackMin, attackMax, defenseMin, defenseMax)

GetMeanDamage = ( _
                TriangleSum(attackMax - defenseMin) _
                - TriangleSum(attackMax - defenseMax - 1) _
                - TriangleSum(attackMin - defenseMin - 1) _
                + TriangleSum(attackMin - defenseMax - 2) _
            ) / ( _
                (attackMax - attackMin + 1) * (defenseMax - defenseMin + 1) _
            )

End Function


texts: Inverse transformation matrix for checking whether a point is inside a rect

texts:
I'm trying to determine which nodes in my scene graph contain a given point in global coordinate space, using the inverse of the node's global transformation matrices.

Here's a simplified version of the Node (real version does dirty checks and caches matrix etc).

class Node {
  parent: Node;

  width: number;
  height: number;

  translation: Vec2;
  rotation: number;
  scale: number;

  // Get the transformation matrix required to draw this node onscreen
  get matrix() {
    let mat = mat2d.clone(this.parent.matrix);
    mat2d.translate(mat, mat, this.translation);
    mat2d.rotate(mat, mat, this.rotation);
    mat2d.scale(mat, mat, [this.scale, this.scale]);
    this.matrix = mat;
  }

  // Check if point is inside this node's rect
  contains(x: number, y: number) {
    let point = this.toLocalPoint(x, y);

    return (
      point.x >= this.translation.x &&
      point.y >= this.translation.y &&
      point.x <= this.translation.x + this.width &&
      point.y <= this.translation.y + this.height
    );
  }

  // Convert a point in global space to local space
  toLocalPoint(x: number, y: number) {
    let inverse = mat2d.create();
    mat2d.invert(inverse, this.matrix);

    let point = vec2.fromValues([x, y]);
    vec2.transformMat2d(point, point, inverse);

    return point;
  }

}

This is working fine for the renderer. Here's an example of how that looks for reference.

for (let node of nodes) {
  renderer.push(node.matrix);
  renderer.draw(node.texture);
  renderer.pop();
}

The Node#contains method has some problems. It seems to adjust correctly to detect rotation and scale changes, but as soon as there's a translation applied to a node, the inverse matrix gives the wrong results.

Here's an example that shows a test of whether the mouse cursor is inside a node.

The cyan node is at the origin, given a scale, and rotation.
The magenta node has the same scale and rotation, but it has also
been translated along the X axis.

There are points off to the right that are registering as inside the node though.

I'm fairly sure that this means that the separate steps of the matrix transform are being applied in the wrong order, but I'm not sure how to apply the inverse matrix in any other way (without decomposing it into the 3 individual components of the transform and applying them in the reverse order that the Node#matrix getter does).

Have I misunderstood how the inverse matrix works here?


texts: XMMATRIX XMMatrixRotationY wants the angle in radians or degrees? DirectX

texts:
The documentation is totally unclear about it.
And also what does" Angles are measured clockwise when looking along the rotation axis toward the origin" mean? Are they measured clockwise looking from where?
Documentation:
https://msdn.microsoft.com/en-us/library/windows/desktop/microsoft.directx_sdk.matrix.xmmatrixrotationy(v=vs.85).aspx


texts: How to set blur on mouse over and remove on mouse out in AS3?

texts:
How can I do it? I want to active glow when the mouse is over a Sprite and remove it when the mouse is out. Is it possible?

I have the following code:

var myGlow:GlowFilter = new GlowFilter();
myGlow.color = 0xFFFFFF;
myGlow.blurX = glowMobilha.blurY = 20;
var miniatura:MovieClip = _scene.d1[link];
miniatura.addEventListener(MouseEvent.CLICK,
                           function(e:Event):void {
                               MainSoundManager._sm.stopAllSounds();
                               GameManager.loadSection(link, false);
                           });
miniatura.addEventListener(MouseEvent.MOUSE_OVER,
                           function(e:Event):void {
                               miniatura.filters = [myGlow];
                               miniatura.gotoAndStop(2);
                               _control.visible = true;
                               _controle.gotoAndPlay(2);
                           });
miniatura.addEventListener(MouseEvent.MOUSE_OUT,
                           function(e:Event):void {
                               miniatura.gotoAndStop(1);
                               _control.visible = false;
                               _control.gotoAndStop(1);
                           });
miniatura.buttonMode = true;

I set the blur at:

miniatura.addEventListener(MouseEvent.MOUSE_OVER,
                           function(e:Event):void {
                               miniatura.filters = [myGlow];
                               miniatura.gotoAndStop(2);
                               _control.visible = true;
                               _controle.gotoAndPlay(2);
                           });

How can I "hide" the blur at:

miniatura.addEventListener(MouseEvent.MOUSE_OUT,
                           function(e:Event):void {
                               miniatura.gotoAndStop(1);
                               _control.visible = false;
                               _control.gotoAndStop(1);
                           });

UPDATE
I think I found the solution in the following code:

miniatura.addEventListener(MouseEvent.MOUSE_OVER,
                           function(e:Event):void {
                           glowMobilha.alpha = 1;
                           miniatura.filters = [glowMobilha];
                           _controle.visible = true;
                           _controle.gotoAndPlay(2);
                           });
miniatura.addEventListener(MouseEvent.MOUSE_OUT,
                             function(e:Event):void {
                             glowMobilha.alpha = 0;
                             miniatura.filters = [glowMobilha];
                             _controle.visible = false;
                             _controle.gotoAndStop(1);
                           });

is it the best solution?


texts:
I'm trying to figure out how to implement C# scripting into my XNA game. How do I call functions that take more than one frame to finish?

For example:

class UserScript : Script
{
    public override void execute(Game game)
    {
        //script must wait for dialog to be closed
        game.openDialog("This is a dialog");

        //script should'nt wait for this
            int goldToGive = 100;
            goldToGive += 100;
            game.addGold(goldToGive);
        //

        //script should wait for cinematic to end
        game.startCinematic("name_of_cinematic");

        //doesn't wait
        game.addGold(100);
    }
}

I found a question that suggests you can do it with yield, but I'm not sure if it's the correct way, as the referenced article is from 2010, and no longer exists. Is using yield the answer? If so, how do I use it? If not, should I take a differant approach, or am I better off with multi-threading?


texts: Unity Texture2D raw data TextureFormat problem

texts:
I am trying to load raw image data into a Texture2D in Unity using LoadRawTextureData but I can't get it to work correctly.

First I receive an array of bytes from an unmanaged function that captures a window. I am pretty sure these bytes represent an image in BGRA32 format.

int dataSize = width * height * 4;
byte[] imgData = new byte[dataSize];
bool success = CaptureWindow(windowInfo, imgData, (uint)(dataSize));

Then I try to create a new Texture2D with this data

Texture2D tex = new Texture2D(width, height, TextureFormat.BGRA32, false, true);
tex.LoadRawTextureData(imgData);
tex.Apply();

And finally I create a new plane and assign this texture to its material.

GameObject plane = GameObject.CreatePrimitive(PrimitiveType.Plane);
plane.GetComponent<MeshRenderer>().material.mainTexture = tex;

This doesn't work (Notice how the color channels are mixed up):

However, when I reverse the byte array before loading it into the texture as ARGB32, it does work:

Texture2D tex = new Texture2D(width, height, TextureFormat.ARGB32, false, true);
Array.Reverse(imgData);
tex.LoadRawTextureData(imgData);
tex.Apply();

The problem with this solution is that Array.Reverse is too slow.

Why doesn't loading it as BGRA32 work? Isn't BGRA32 just the reverse of ARGB32?

FYI: I am using Unity 5.1.2f1 on Windows and SystemInfo.SupportsTextureFormat returns true for both BGRA32 and ARGB32.


texts: Debug Unity DLLs in Windows standalone build

texts:
I'm trying to publish a game on the Windows Store using a standalone Windows build in Unity 5.6.2 and Desktop Bridge. Despite unchecking "development build", three Unity DLLs remain in debug mode, which blocks deployment:

The binary UnityEngine.Networking.dll is built in debug mode.
The binary UnityEngine.UI.dll is built in debug mode.
The binary UnityEngine.dll is built in debug mode.

How can I force Unity to give me release DLLs if unchecking "development build" isn't enough?


texts:
I am trying to make simple RTS game, and here is the problem I encountered. I need to get model height in any position. Model will not be rotated or scaled. For example, I have a terrain model like this:

and I want to get terrain height in unit`s position to place it correctly.

Thanks in advance!


texts: Looking at the mouse position in a top down Unity game?

texts:
I'm trying to make a simple top down game where the player looks at wherever the mouse is pointed.  The player is only going to rotate on the Y axis.

Here's what I have so far but I can't seem to get it working.

private void RotateToMouse()
{
    //Veriables
    Vector3 ScreenMouse;
    Vector3 ShipPos;

    //Get Mouse Point ON screen
    ScreenMouse.x  = Input.mousePosition.x;
    ScreenMouse.y  = Input.mousePosition.y;
    ScreenMouse.z  = 1;

    //Get Mouse Point In World
    WorldMouse = Camera.main.ScreenToWorldPoint(ScreenMouse);
    //Get Ship Position
    ShipPos = transform.position;

    //Get Angle Of Mouse From Ship Position
    Angle = Mathf.Atan2(ShipPos.z - WorldMouse.z,ShipPos.x - WorldMouse.x) * 180 / Mathf.PI;

    transform.localEulerAngles = new Vector3(0,Angle,0);
}


texts: Learning Web Development and Game Development at the same time?

texts:
I'm a junior-level developer, currently working full time and trying to get experience with working with ASP.NET MVC. I love web development, and want to continue to pursue it as my career, but I also love gaming and have done a few game tutorials with Monogame/XNA, and love that as well.

For anyone that has been in this situation, Can you tell me, from experience, if you noticed any form of degenerative results when trying to split focus between a full-time career in another field and beginning game development? I am looking for concrete examples of people who managed to split their time, and what their experience was like. I'm concerned that if I focus on game development on my spare time, then my growth in web development might suffer. I hope to use your input to determine for myself, how I should split up my free time, and manage my "Extracurricular" web projects, AND game development projects, so that I don't end up as a jack of all trades, master of none. I don't know why this is such a hard decision for me. :(


texts: How to code a lot of cards in a trading card game java

texts:
I want to make a trading card game like Yu-Gi-Oh or Magic. I have a lot of cards in my game and even the user can make new cards. Cards are objects and they have attributes like HP and Mana ,etc but they also has special power which is another object and has different types some of them activate when a card is played into the field, some of them activate at death and etc. One way is simply hardcoding all the different cards in different classes but This way, I cannot implement a user-built card. I am going to use enums for the essential cards but I don't know what to do for user defined cards.

Is there any standard way to implement things like this?

I am very new to Java and OOP. I think maybe Databases could help but I don't know what should I use or search to find the appropriate choice for this matter.


texts:
We have tried the following methods to upload sample Unity3D build to a desktop application in Flex: HTML Loader, NavigateToURL, iFrame and resolvePath.

But we only see the text content, not the 3D content. What is the solution for that? How can I host a Unity game inside Flex?


texts: 2D Rigidbody with Touchscript movement in Unity won't stay in boundaries

texts:
I'm trying to make a pong game where the player has to move both paddles. They are currently set as dynamic 2D Rigidbodies (collision detection continuous) and have a box collider (is NOT trigger) attached. The problem is the paddles won't collide with the surrounding box colliders I set on the camera, using the following script:

 using UnityEngine;
 using System.Collections;

  namespace UnityLibrary
     {
      public class EdgeCollider : MonoBehaviour
      {

public float colDepth = 4f;
public float zPosition = 0f;
private Vector2 screenSize;
private Transform topCollider;
private Transform bottomCollider;
private Transform leftCollider;
private Transform rightCollider;
private Vector3 cameraPos;
// Use this for initialization
void Start () {
//Generate our empty objects
    topCollider = new GameObject().transform;
    bottomCollider = new GameObject().transform;
    rightCollider = new GameObject().transform;
    leftCollider = new GameObject().transform;

//Name our objects
    topCollider.name = "TopCollider";
    bottomCollider.name = "BottomCollider";
    rightCollider.name = "RightCollider";
    leftCollider.name = "LeftCollider";

//Add the colliders
    topCollider.gameObject.AddComponent<BoxCollider2D>();
    bottomCollider.gameObject.AddComponent<BoxCollider2D>();
    rightCollider.gameObject.AddComponent<BoxCollider2D>();
    leftCollider.gameObject.AddComponent<BoxCollider2D>();

//Make them the child of whatever object this script is on, preferably on the Camera so the objects move with the camera without extra scripting
    topCollider.parent = transform;
    bottomCollider.parent = transform;
    rightCollider.parent = transform;
    leftCollider.parent = transform;

//Generate world space point information for position and scale calculations
    cameraPos = Camera.main.transform.position;
    screenSize.x = Vector2.Distance (Camera.main.ScreenToWorldPoint(new Vector2(0,0)),Camera.main.ScreenToWorldPoint(new Vector2(Screen.width, 0))) * 0.5f;
    screenSize.y = Vector2.Distance (Camera.main.ScreenToWorldPoint(new Vector2(0,0)),Camera.main.ScreenToWorldPoint(new Vector2(0, Screen.height))) * 0.5f;

//Change our scale and positions to match the edges of the screen...
    rightCollider.localScale = new Vector3(colDepth, screenSize.y * 2, colDepth);
    rightCollider.position = new Vector3(cameraPos.x + screenSize.x + (rightCollider.localScale.x * 0.5f), cameraPos.y, zPosition);
    leftCollider.localScale = new Vector3(colDepth, screenSize.y * 2, colDepth);
    leftCollider.position = new Vector3(cameraPos.x - screenSize.x - (leftCollider.localScale.x * 0.5f), cameraPos.y, zPosition);
    topCollider.localScale = new Vector3(screenSize.x * 2, colDepth, colDepth);
    topCollider.position = new Vector3(cameraPos.x, cameraPos.y + screenSize.y + (topCollider.localScale.y * 0.5f), zPosition);
    bottomCollider.localScale = new Vector3(screenSize.x * 2, colDepth, colDepth);
    bottomCollider.position = new Vector3(cameraPos.x, cameraPos.y - screenSize.y - (bottomCollider.localScale.y * 0.5f), zPosition);
}

  }
 }

The ball collides with the paddles and bounces off as it should as well as collides with the surrounding box colliders and bounces off perfectly. However the paddles move right through the surrounding box colliders (EdgeColliders). Please note that I use the Touchscript package from the Unity Asset Store to control movement. It does not move the Rigidbody, it uses transform. Another thing to note is that when I make the paddles very light (0.0001 mass) and add gravity to them, they do collide with the edge colliders and don't go through the screen.


texts: Optimal touch controls for a twin-stick shoot 'em up?

texts:
So we recently launched a shoot 'em up arcade-type game (think Smash TV or I Made a Game with Zombies in It!). You can move in one direction and fire in another, so the ideal control scheme is probably two analog joysticks (like the Xbox 360 has). We support WASD to move and arrow keys to fire. The best way to control though is to move with WASD and aim with the mouse.

We're getting a lot of people asking for mobile versions of the game (mostly for iPad and Android) and the problem is we just can't come up with a good way to translate the controls over to a touch device.

Interestingly, someone actually hacked an early version of our game a while back to work on Android by overlaying D-pads, and sure enough, it was almost impossible to control. The game gets really difficult later on, and the thought of releasing a game with a crappy control scheme that nobody could possibly ever use to beat the game does not sit well with me.

So I was wondering if anyone has any previous experience or suggestions on how to approach this problem? Overlaying two D-pads on the screen is clearly not the way to go and we're kind of at a loss for other ideas.


texts: Difference between texture.Load() and texture.Sample() methods in DirectX?

texts:
The question is simply that: What is the difference between texture.Load() and texture.Sample() in DirectX?

I've used a Texture2D to store the depth in a pass of a DirectX Shader (with SharpDX), and now that I want to extract the depth from the texture I'm not sure which of the two methods I should use


texts:
I'm working on a 2d side-scrolling RPG-ish game. Currently the movement of the main character(hero) is based on the A and D keys, because it's 2d and I don't really care about jumping. I would like to change it to a mouse oriented system.
   Something like this: if the hero is at position 100(x-axis) and I click at x=200, it would move(tween/ease) to 200px with 50px/s.
   PS: I'm using java with libgdx.


texts: Huge level size after build APK in Unity

texts:
I made maps used bunch of small objects which are mostly scenary, like part of road, buildings, obstacles. They are all lightmap static, batching static, occludee static.

However after build APK, "levels" takes most spaces:

Uncompressed usage by category:
Textures      23.4 mb    5.3%
Meshes        24.9 mb    5.6%
Animations    4.5 mb     1.0%
Sounds        1.9 mb     0.4%
Shaders       1.8 mb     0.4%
Other Assets  4.8 mb     1.1%
Levels        287.1 mb   65.0%
Scripts       2.1 mb     0.5%
Included DLLs 3.9 mb     0.9%
File headers  389.1 kb   0.1%
Complete size 442.0 mb   100.0%

As you can see, it's 287.1mb, it's too big. Actual APK size is almost 100mb. Funny thing is that in my game, I don't use lightmap. I have 9 different maps, all of them don't have light map, only has baked navigation mesh and occlusion data.

I don't think that occlusion data and navigation mesh takes that much, because I can see that occlusion data is less than 1MB even in the biggest map.

Does it matter that using lots of small objects to create level without lightmapping takes much spaces?

Also I combined those scenary objects together with MeshBaker, which is Unity Asset that combine meshes and materials/textures. After build, there's a little size reduction only in "Levels" part, however overall game performance getting worse and total apk size is not changed.

So, why I have those huge "levels" size, and how do I reduce it? Is there something that I missed?

And which situtation is proper to combine multiple meshes into single? In stats result, average batches are 40 in my game. Should I combine those bunch of small objects as big single object?


texts: How could I implement 3D player collision with rotation in LWJGL?

texts:
I have a problem with my current collision implementation.

Currently for player collision, I just use an AABB where I check if another AABB is in the way of the player, as shown in this code.
(The code below is a sample of checking for collisions in the Z axis)

for (int z = (int) (this.position.getZ()); z > this.position.getZ() - moveSpeed - boundingBoxDepth; z--)
{
    // The maximum Z you can get.
    int maxZ = (int) (this.position.getZ() - moveSpeed - boundingBoxDepth) + 1;
    AxisAlignedBoundingBox aabb = WarmupWeekend.getInstance().currentLevel.getAxisAlignedBoundingBoxAt(new Vector3f(this.position.getX(), this.position.getY(), z));
    AxisAlignedBoundingBox potentialCameraBB = new AxisAlignedBoundingBox(this, "collider", new Vector3f(this.position.getX(), this.position.getY(), z), boundingBoxWidth, boundingBoxHeight, boundingBoxDepth);
    if (aabb != null)
    {
        if (potentialCameraBB.colliding(aabb) && aabb.COLLIDER_TYPE.equalsIgnoreCase("collider"))
        {
            break;
        }
        else if (!potentialCameraBB.colliding(aabb) && z == maxZ)
        {
            if (this.grounded)
            {
                playFootstep();
            }
            this.position.z -= moveSpeed;
            break;
        }
    }
    else if (z == maxZ)
    {
        if (this.grounded)
        {
            playFootstep();
        }
        this.position.z -= moveSpeed;
        break;
    }
}

Now, when I tried to implement rotation to this method, everything broke. I'm wondering how I could implement rotation to this block (and as all other checks in each axis are the same) and others. Thanks in advance.


texts: Can you create a game on an anime/serie/saga already existing?

texts:
I had kind of an "illumination" by watching a TV serie, and got the urge desire to make it in a game the way I want it. I of course don't intend to make money out of it. So I was curious to know, would I be in a trouble if I made a game, mostly a demo about the first two episodes of the TV serie, on it without asking for any money. Won't the original developper (if by chance hear about it), get me in a court or something ?
(of course in the credits or something i would say that the original serie came from them)
PS : if they don't, then my second question is : Am i allowed to ask for donation, help or something to continue making a sequel, or a full game from that demo ?


texts: How can I get Steam username and avatar image from leaderboard?

texts:
After I downloaded leaderboard data (using the Steamworks.NET API), I couldn't find any related info about the user's name and the avatar picture. The only thing I can get is a CSteamID.
I saw some games implement a Steam Leaderboard, displaying their name and avatar images, and I'm trying to achieve the same thing. However, I've searched on the Steamworks documentation and on Google for almost a day, but couldn't find any related information.
The only thing I found was an API with SteamFriends, there were some API's that retrieved the user's name and avatar image.
Here's the code I'm trying:
private CallResult<LeaderboardScoresDownloaded_t> m_DownloadResult = new CallResult<LeaderboardScoresDownloaded_t>();

...

SteamAPICall_t hSteamAPICall = SteamUserStats.DownloadLeaderboardEntries(
    m_CurrentLeaderboard,
    ELeaderboardDataRequest.k_ELeaderboardDataRequestGlobalAroundUser,
    -4,
    5
);
m_DownloadResult.Set(hSteamAPICall, OnLeaderboardDownloadScore);

...

void OnLeaderboardDownloadScore(LeaderboardScoresDownloaded_t pCallback, bool failure) {
    Debug.Log("Failure: " + failure);

    if (!failure) {
        int count = pCallback.m_cEntryCount;

        for (int i = 0; i < count; i++) {
            LeaderboardEntry_t leaderboardEntry;

            SteamUserStats.GetDownloadedLeaderboardEntry(
                pCallback.m_hSteamLeaderboardEntries,
                i,
                out leaderboardEntry,
                null,
            0);

            CSteamID user = leaderboardEntry.m_steamIDUser;

            Debug.Log("Rank" + i);
            Debug.Log("User Name: " + leaderboardEntry.    // how to get user name and avatar?
            Debug.Log(leaderboardEntry.m_nScore);

            Debug.Log("===========================");
        }
    }
}

In LeaderboardEntry, I can only get the score and CSteamID. In SteamUser and SteamUserStat classes, there was no API that can get the user's name and avatar image.


texts: How to load assets into the game engine editor fast?

texts:
I am making a game engine with C++ and OpenGL. Currently I'm stuck making the asset explorer. I would like to be able to import assets into an engine project and then when I open the project just use them in various game scenes (like in Unity). However the only thing I am doing right now is loading everything from the 'Assets' folder of the opened editor project. That is incredibly slow even when done asynchronously  with multithreading. I don't understand how does Unity load assets so fast. I've noticed that it takes a while to import the assets for the first time but then it's very fast anytime you open the project after the first import. Is there any way to cache loaded assets? And should I generate all the buffers for OpenGL right on the asset import or should I wait for the asset to be 'used'?

Unity's asset explorer:

All imported assets can be inspected like that, and then you can use them in the scenes (for example drag and drop a model into the scene):


texts: How do I implement branching dialogue in javascript?

texts:
I'm making a very basic visual novel type of game in JavaScript. I'm a beginner, so I'm just doing this for fun and learning, and due to bad planning I have run into a bit of a problem when you get to a branch in dialogue.

Currently I hold the script for the game in a string variable and I break up each scene with a tag such as "#~" into smaller arrays so that the game script looks like this:

var script = "Hello World!#~How are you today?"
var gameText = script.split("#~");
//gameText[0]= Hello World!

This works great for linear stuff, but how should I handle a branch in the dialogue tree? This method seems very complicated, as I would have to know exactly how long each path is and then if I ever needed to change anything it would be a headache.

How can I do this in a simpler way? I'm trying to stick to vanilla JavaScript as I'd like the game to work with Web Run Time.


texts: Coding for a really, really high-resolution display array

texts:
I've been tasked with building a real time "full screen" demo to run on a 5x2 array of 60+ inch LED TVs: or, in other words, a 20 megapixel display.

We've got a machine built that can run a single Win7 desktop spread across the displays at full resolution, and some pretty decent video cards.

My question is: aside from the ridiculous amount of work that my pixel shaders are going to be doing, are there any other limitations of DX10.* that would come into play here that wouldn't on a more sanely sized viewport? I won't have access to the hardware until next week but I'd like to have something written by then that I can use to benchmark the system.

Update

While Imanaged to get this working on a single machine with a bunch of AMD EyeFinity (6 output) cards - to keep things working smoothly, the "easiest" way turned out to be to create a DX window per display as having a window span displays caused some performance issues - I also got it working pretty well by distributing the task across a group of machines, each of which drives two displays.

It was surprisingly easy. For my test XNA app, I added a GameComponent that captures some game state (camera position/orientation, etc.) and UDP-spams it across the local subnet per frame.

That component has a Mode switch (send or receive). If it's in Receive mode, it catches UDP datagrams and updates the game state with the information from the sender. Send mode just sends state packets, and, via a service/daemon, causes nodes to start or stop the client app. Any client can act as a "master", and switching a client into Send mode requests all other nodes to switch into Receive. It's pretty entertaining to see what happens when people are fighting over control.

Another neat benefit: I created a console app which processes a series of keyframe state definitions - location, time, etc. - interpolates as needed, and sends them using the same code as is used in the game engine. This lets me easily script movement, submit transforms from a web browser, etc.

All in all, it took about 50 lines of code to keep multiple copies of the app running in sync. Some additional complexity came from off-setting the camera position for each machine and correcting some perspective/projection annoyances, but most of that came down to a per-node configuration file.


texts: How do I keep a rigidbody from making unnecessary collisions on smooth surfaces in Unity3d?

texts:
I have been having trouble with a custom character controller I am making. The root of the problem lies with collisions. I am trying to make movement code, but I have a problem with ground movement. Pay attention to this gif. It might be hard to notice due to the low frame rate, but the collider registers collisions with objects (in red) that do not point out of the ground. They share the same y-position as the ground. I've printed the normals of the collisions, and there are a lot of normals that are perpendicular to the normal of the ground (which is causing the rigidbody to get stuck).

The problem lies with collisions in unity. If I were to print the y-position of the bottom of my collider, it would be just a tad lower than the y-position of the ground. The collider actually rests below the ground by an almost negligible amount (which is why it doesn't always collide with these objects).

Here is what I have tried: I created a function that runs at the beginning of every FixedUpdate() that uses current collisions to change the y-position of the rigidbody. It only runs on collisions that would ground the player (meaning that they are below the collider). The problem with this approach is that the same issue can occur with walls, meaning that the collider can get stuck on walls. I cannot create another function that would do the same for walls for various reasons.

Here is what would fix the issue: I need help figuring out how I can make collisions more discrete in unity. Colliders rest slightly below objects when ontop of them. They can also "sink" just a little into walls. In other words, colliders can rest into other colliders, and I need this to stop.

Any help is appreciated. Thank you.


texts: Actor does not perform action when spawned?

texts:
In the level blueprint I made a code so that after 5 seconds an NPC was spawned, it happens that it does nothing.

Only the NPC I added by the level editor acts correctly.

Image of what happens:

Level Blueprint:

NPC Blueprint:

I did a search, because I imagine that to solve this is to just modify the event to some of the type: When created or when spawned.

Search:

I also thought of something like an event involving the collision between the NPC and the ground, but I considered it silly.

Link I found and at first I'm thinking that the solution may not be as simple as this:

https://answers.unrealengine.com/questions/204154/event-dispatcher-on-a-spawned-actor.html

EDIT 1 (Attempt based on ColdSteel's comment)

I added 2 impressions to see if the Event Begin Play was not even running:

The event is being started correctly and the loop is also:

But the NPC does not go towards the target points and I do not know the reason.


texts:
OK, I feel like this should be on meta, because it is a very meta question, but I thought it would be interesting to discuss here. it is relevant and it might provide a little break from coding.

Using these sites you can essentially get a very good answer to any problem. In fact I think it would be safe to say you can pretty much get people to discuss the best algorithm for any given problem.

I was wondering if it would be interesting to create a whole game this way. you would ask the first question for instance:

What type of game would be the best game to make if the project was going to be worked on by an unknown amount of designers and developers?

The answer would be subjective, but people could discuss and after a time the answer with the most votes could be chosen and the question locked out. This would be the hardest question I suppose, because after that you would get more and more technical and the questions would become more and more like the questions you ask on these forums.

What would be the best class structure for this segments of a game?

What would be the best way of testing for collisions etc..

Do you think it would be possible to create a whole game this way? Sorry if this seems bizarre or annoying, but I think it might be worth a try! Think of this as the zeroth question. What do you think?


texts:
I'm having issues getting the UnityYAMLMerge tool to work, in order to fix conflicts merging a scene in 2 different branches (myBranch into dev). Here's what I've done:

Set Asset Serialization to Force Text: In Edit > Project Settings > Editor menu, I set Force Text under Asset Serialization Mode. This has been set for the entire lifetime of the project so all applicable git-tracked files should have this setting.
Treat the Files as Binary to Avoid Git Merging Them Automatically: created .gitattributes in project root dir with the following then pushed:

*.unity binary
*.prefab binary
*.asset binary

Set up UnityYAMLMerge with Git: copypasted the following into .git/config:

[merge]
tool = unityyamlmerge

[mergetool "unityyamlmerge"]
trustExitCode = false
cmd = 'C:/Program Files/Unity/Hub/Editor/2019.2.17f1/Editor/Data/Tools/UnityYAMLMerge.exe' merge -p "$BASE" "$REMOTE" "$LOCAL" "$MERGED"

Note: the Unity docs state that the UnityYAMLMerge.exe should exist at:

C:\Program Files\Unity\Editor\Data\Tools\UnityYAMLMerge.exe

or

C:\Program Files (x86)\Unity\Editor\Data\Tools\UnityYAMLMerge.exe

However I do not have an Editor/ directory at either of these locations, and instead I found the executable at C:/Program Files/Unity/Hub/Editor/2019.2.17f1/Editor/Data/Tools/UnityYAMLMerge.exe (2019.2.17f1 does match the version of Unity I'm building this project in).

However after all this, when I am in my branch dev and try to merge my branch myBranch into dev, I still receive conflict warnings and am asked to manually fix them:

$ git merge myBranch
warning: Cannot merge binary files: Assets/Scenes/ManagerScene.unity (HEAD vs. myBranch)
warning: Cannot merge binary files: Assets/Scenes/2-Paint.unity (HEAD vs. myBranch)
warning: Cannot merge binary files: Assets/Resources/Prefabs/UI/Heatmap.prefab (HEAD vs. myBranch)
Auto-merging Assets/Scenes/ManagerScene.unity
CONFLICT (content): Merge conflict in Assets/Scenes/ManagerScene.unity
Auto-merging Assets/Scenes/2-Paint.unity
CONFLICT (content): Merge conflict in Assets/Scenes/2-Paint.unity
Auto-merging Assets/Resources/Prefabs/UI/Heatmap.prefab
CONFLICT (content): Merge conflict in Assets/Resources/Prefabs/UI/Heatmap.prefab
Automatic merge failed; fix conflicts and then commit the result.

From what I understand, the UnityYAMLMerge tool should automatically resolve these conflicts without causing git to prompt me to fix them. Is this correct? Otherwise, what else must I do to use this tool properly?

Thanks for any help!


texts:
I'm working on SAO (http://graphics.cs.williams.edu/papers/SAOHPG12/) and I want to store my ambient obscurance term (a value between 0.0 and 1.0) in a texture.

When I did shadowmapping, I created my depth-texture as DXGI_FORMAT_R32_TYPELESS and the shader resoure view as DXGI_FORMAT_R32_FLOAT, however with this I want a DXGI_FORMAT_R8_TYPELESS format and a FLOAT equivalent, yet there appears to be none according to the docs (http://msdn.microsoft.com/en-us/library/windows/desktop/bb173059(v=vs.85).aspx)

1) What texture/srv/rtv format should I use if I want to store/read/write 8-bit float values?

2) Does the format used really matter? Does directx do any behind-the-scenes alterations to the texture data? Is a DXGI_FORMAT_R8_UNORM treated differently from a DXGI_FORMAT_R8_SNORM for example?


texts:
I would like to implement dual depth peeling in my engine. I read the original paper and examined the corresponding source code. I understand the algorithm, except how the blending works, especially in the front-to-back part. I'm so confused now, I'm not sure anything about alpha blending.
So let's start with the basics. I think there are two options: either we compute the pixel's color and it's transparency and store them separately (straight), or we multiply them and then we don't use the alpha channel's value (premultiplied alpha). The second option is what we usually do when we set glBlendFunc's parameters to GL_SRC_ALPHA and GL_ONE_MINUS_SRC_ALPHA. When we blend two pixels, the GPU multiplies the source color with the source alpha and it multiplies the destination color with (1 - source alpha). We don't multiply the destination color with the destination alpha because basically it's already multiplied with it. So we assume the destination alpha is 1 (and also the destination alpha is not correct, because of the GL_SRC_ALPHA and GL_ONE_MINUS_SRC_ALPHA parameters, so we can't use it anyways). Am I right so far?
At this point the back-to-front part of the dual depth peeling makes sense to me. In  dual_peeling_peel_fragment.glsl we just store the color with the alpha (we can't blend it yet because we have to use max blending in this shader).
void main(void)
{
    ...
    gl_FragData[2] = vec4(0.0);
    ...
    if (fragDepth == nearestDepth) {
        ...
    } else {
        gl_FragData[2] += color;
    }
}

Then in the dual_peeling_blend_fragment.glsl shader we just blend it with the background.
void main(void)
{
    gl_FragColor = textureRect(TempTex, gl_FragCoord.xy);
    ...
}

Here we use additive blending with the already mentioned parameters which makes sense to me.
But when we compute the front-to-back part in dual_peeling_peel_fragment.glsl, I don't understand the code.
void main(void)
{
    ...
    vec4 forwardTemp = textureRect(FrontBlenderTex, gl_FragCoord.xy);
    ...
    gl_FragData[1] = forwardTemp;
    ...
    float alphaMultiplier = 1.0 - forwardTemp.w;
    ...
    vec4 color = ShadeFragment();
    ...
    if (fragDepth == nearestDepth) {
        gl_FragData[1].xyz += color.rgb * color.a * alphaMultiplier;
        gl_FragData[1].w = 1.0 - alphaMultiplier * (1.0 - color.a);
    } else {
        ...
    }
}

Here we compute the color value and multiply it with some alpha values and we also compute the alpha. I don't see where these equations come from. We don't modify the destination color (which is the nearer), but we multiply the source color with the source alpha and with (1 - destination alpha). And then we also compute the alpha value. So this not straight neither premultiplied. Also in the paper they use slightly different equations in page 6.

Where the paper multiplies with destination alpha the source code multiplies with (1 - destination alpha). I found a blog post where the author is also confused about that.
And then, at the end in dual_peeling_final_fragment.glsl we blend together the back-to-front part with the front-to-back part.
void main(void)
{
    vec4 frontColor = textureRect(FrontBlenderTex, gl_FragCoord.xy);
    vec3 backColor = textureRect(BackBlenderTex, gl_FragCoord.xy).rgb;
    float alphaMultiplier = 1.0 - frontColor.w;
    gl_FragColor.rgb = frontColor + backColor * alphaMultiplier;
}

But I don't understand why we only multiply the back part with (1 - front part alpha). In this part we use additive blending.


texts: Libgdx inputlistener scrolled is not working

texts:
I am currently using libgdx. Below codes are added to a stage.

this.addListener(new InputListener() {
        public boolean touchDown (InputEvent event, float x, float y, int pointer, int button) {
            System.out.println("down");
            return true;
        }

        public void touchUp (InputEvent event, float x, float y, int pointer, int button) {
            System.out.println("up");
        }
        public void touchDragged(InputEvent event, float x, float y , int pointer) {
            System.out.println("dragged");
            zoom(0.01f);
        }
        public boolean scrolled(InputEvent event,
                    float x,
                    float y,
                    int amount) {
            System.out.println("scrolled");
            zoom(0.01f);
            return true;
        }

everything is working just fine (touchUp touchDragged Touchdown) except scrolled. Can someone tell me what is the reason?

-edited for reply comment and answer-
On screen class outside stage, I think I already added like screen.set input processor(stage). So touch dragged is working properly and print message 'dragged' and zoom is working. But when I scroll, message 'scrolled' is not printed and zoom function is not called I think. Thank you for comment and answer


texts: Scale VBO magnitudes based on aspect ratio

texts:
On my screen I have drawn a box. When I adjust my screen size (to a non 1:1 aspect ratio) I get a rectangle. This is obviously something wrong with my projection matrix.

I am attempting to keep everything in my engine scaled from 0->1 to make it simple to define assets and have them look good on any size screen.

I would like to make my internal VBO sizes scale with the window's aspect ratio. In this example I have one asset that I define as having a width and height of "0.01" which is 1/100th the screen size.

I create the following VBO with this...

    GLuint VAO, VBO, EBO;
    GLfloat verts[] = {
            width, height, 0.0f,
            width,   0.0f, 0.0f,
             0.0f,   0.0f, 0.0f,
             0.0f, height, 0.0f
    };
    GLuint idxs[] = {
            0, 1, 3,
            1, 2, 3
    };

    glGenVertexArrays(1, &VAO);
    glGenBuffers(1, &VBO);
    glGenBuffers(1, &EBO);

    glBindVertexArray(VAO);

    glBindBuffer(GL_ARRAY_BUFFER, VBO);
    glBufferData(GL_ARRAY_BUFFER, sizeof(verts), verts, GL_STATIC_DRAW);

    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(idxs), idxs, GL_STATIC_DRAW);

    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), NULL);
    glEnableVertexAttribArray(0);

    glBindBuffer(GL_ARRAY_BUFFER, 0);
    glBindVertexArray(0);

I'm using an ortho matrix from (0, 1, 0, 1, 0, 1), I'm correclty doing my PVM multiplication in my shader, and I've correctly translated my matrix.

My boxes are still rectangles and I believe that this is because my original "1/100th" screen size is different from my new screen's width and height. How do I correctly scale my width and height that I've given to my VBO?

Edit: PS you can find all of the important pieces of code in my git repo (https://github.com/gravypod/solid-snake/). I'd link directly to the right section but StackExchange seems to have a karma based limit...


texts: How to represent a map in a top-down perspective game with low algorithm complexity?

texts:
This is the first time I develop a video-game, and I am kind of lost.

I would like to know about ways on representing 2D maps on a top-down perspective game...

(Like this one: vengadoravg.github.io/1/game.html btw, this is the first game I develop)

So far, I've found one way to represent a 2D map in a top-down perspective game:

Using a matrix. Where a normal floor place is represented by some number (or character), the obstacles are represented by a different number, and the enemies by another different number. This matrix would allow me to run graph theory algorithms and crazy things, but i think it would be, algorithmically, very complex, because the graph would be really populated and dense. Thus, all the sprites should be the same size, otherwise, the matrix would be really, really big.

Are there any other (better) ways?

In terms of algorithm complexity, which of them are the best to run graph theory algorithms?

I apologize if the question sounds subjective... but i think the superiority of an approach can be determined by its algorithmic complexity :)


texts: Is there a way to control the ordering and grouping of ShaderLab Blend command?

texts:
I'm writing a shader in Unity that responds to 3 lights: 1 directional and 2 point lights. The point lights are processed in the ForwardAdd pass (once per light). I need the ForwardAdd pass to blend with the ForwardBase pass multiplicatively (Blend Zero SrcColor). But I also need the lights in the ForwardAdd pass to stay additively blended.

Since I can only set the Blend once per pass and the ForwardAdd pass gets run once for light, I can only end up with everything blended multiplicatively.

So my question is: is there a way to keep the lights in ForwardAdd pass additively blended? In other words, is there some way to control the ordering/grouping of the Blend command?

If not, is there any other way to achieve my desired effect? The goal I'm going after is to have point lights (that are pixel lights) to mask out all other lights (directional, vertex, and SH lights).

Thanks in advance!


texts: How to get an OnClick Event in Unity to action?

texts:
I am new to Game Dev and I am following a Tutorial.  Within this tutorial, we create a quest system, that allows you to accept or decline a quest. This tutorial is based on Unity 5 and I am using 2020.1 so there could be version differences that could be causing the issue.
I have a script called:
Quest001Buttons.cs
public class Quest001Buttons : MonoBehaviour {
    public GameObject ThePlayer;
    public GameObject NoticeCam;
    public GameObject UIQuest;
    public GameObject ActiveQuestBox;
    public GameObject Objective01;
    public GameObject Objective02;
    public GameObject Objective03;

    public void AcceptQuest() {
        Debug.Log("Accept Registered");
        ThePlayer.SetActive(true);
        NoticeCam.SetActive(false);
        UIQuest.SetActive(false);
        StartCoroutine(SetQuestUi());
    }

    IEnumerator SetQuestUi() {

        ActiveQuestBox.GetComponent<Text>().text = "My First Weapon";
        Objective01.GetComponent<Text>().text = "Reach the Clearing";
        Objective02.GetComponent<Text>().text = "Open Chest";
        Objective03.GetComponent<Text>().text = "Get Weapon";
        QuestManager.ActiveQuestNumber = 1;
        yield return new WaitForSeconds(0.5f);
        ActiveQuestBox.SetActive(true);
        yield return new WaitForSeconds(1);
        Objective01.SetActive(true);
        yield return new WaitForSeconds(0.5f);
        Objective02.SetActive(true);
        yield return new WaitForSeconds(0.5f);
        Objective03.SetActive(true);
        yield return new WaitForSeconds(9);
        ActiveQuestBox.SetActive(false);
        Objective01.SetActive(false);
        Objective02.SetActive(false);
        Objective03.SetActive(false);

    }
}

I have an Empty GameObject called "QuestButtonManager" which I have assigned the above script to.
I also have a UI GamObject called "Accept" and I have attached the QuestButtonManager GameObject to the OnClick() Event within that component.  I have selected:
"Runtime Only" and the function of "Quest001Buttons.AcceptQuest".
When I run the game and press the Accept Button...the game seems to not function after that and is stuck on that screen, with the button highlighted...not even the Debug.Log text is printed in the console.
Any help is greatly appreciated before I give it up and look for a more updated version to learn on.


texts: Full-screen post-processing and texture size

texts:
I am newbie writing a post-processing code for mobile devices, and asking some trivial, conventional solution for a specific problem.

AFAIK, post-processing in OpenGL is trivially done with FBO bound to a texture. Anyway, target screen size is usually not square and non-POT(power-of-two) numbers, while texture size needs to be the POT numbers. For example, iPhone 4 screen size is 640x960 pixels. Because all textures need to be POT sized, texture size for post-processing should be 1024x1024 to cover all the pixels. But in this case, over half of the pixels are just wasted. It really feels bad to me. Because simply wasted amount is huge.

Of course I can use smaller 512x512 texture if the post-processing doesn't need to be pixel-perfect. But still, I waste large portions of memory if I keep aspect-ratio. I can fill the texture by adjusting aspect-ratio, but in this case, we need to adjust fragment shader algorithms to get correct result.

Here're my questions.

If I need pixel-perfect post-processing, should I use larger texture which wasting large portion of it? Is this trivial? Or is there better solution? (For example, binding multiple small texture patches to a FBO.)
If I use smaller texture, what is trivial method to handle the aspect-ratio issue? Just use only small portion of the texture keeping aspect-ratio? Or adjust the fragment shader algorithm?


texts: What are other sources of screen tearing?

texts:
I have a DirectX11 based engine / application that is showing screen tearing on a certain system.  The system has a large TV monitor with a GTX 980 graphics card.  The tearing tends to happen in roughly the same spot on the screen when the camera / eyepoint is moving around.  If we change settings (e.g. turn Ambient occlusion on ) then the tearing might move to a different location but it is still consistent.  Our statistics show that application is running at 60Hz and vsync is turned on in the application.  We also have an OpenGL based version of the application that doesn't exhibit this problem.

Things we've tried:

Force vsync on in nvidia's control panel
Turn on triple buffering on in nvidia's control panel
Updated the nvidia driver
Changed the monitor's refresh rate (tried 60, 59, and 24 hz)

None of these changes have changed screen tearing behavior.
What are other sources of screen tearing and how can they be addressed?

Update:

This computer is using windows 7 but doesn't have windows aero enabled (its using a classic theme).  On another computer, that didn't initially have any tearing problems, turning off windows aero makes screen tearing occur in the application.


texts: How can I write a dots effect shader when the character is behind an object?

texts:
I watched an interesting effect while I was playing Super Mario Odyssey: when Mario or another character was behind an obstacle (walls, etc), a tiny gray silhouette mesh appears.

I tried to build something similar using an amplify shader with Unity but I could not achieve it.

How could I write this?

Here is an example from the game:


texts: Unity: BuildFailedException Reference Library Missing Texture at index 1

texts:
I'm new to Unity and I have no idea what this error means, I'm following a tutorial on YouTube which had no error of the sort.

Any idea how can I fix this?

BuildFailedException: ARCore Image Library Generation: Reference library at 'Assets/ReferenceImageLibrary.asset' is missing a texture at index 1.
UnityEditor.XR.ARCore.ARCorePreprocessBuild.BuildImageTrackingAssets () (at Library/PackageCache/com.unity.xr.arcore@2.1.8/Editor/ARCoreBuildProcessor.cs:286)
UnityEditor.XR.ARCore.ARCorePreprocessBuild.OnPreprocessBuild (UnityEditor.Build.Reporting.BuildReport report) (at Library/PackageCache/com.unity.xr.arcore@2.1.8/Editor/ARCoreBuildProcessor.cs:33)
UnityEditor.Build.BuildPipelineInterfaces+<>c__DisplayClass15_0.<OnBuildPreProcess>b__1 (UnityEditor.Build.IPreprocessBuildWithReport bpp) (at <af78ad00a40d4f61b82afc6cafb0a416>:0)
UnityEditor.Build.BuildPipelineInterfaces.InvokeCallbackInterfacesPair[T1,T2] (System.Collections.Generic.List`1[T] oneInterfaces, System.Action`1[T] invocationOne, System.Collections.Generic.List`1[T] twoInterfaces, System.Action`1[T] invocationTwo, System.Boolean exitOnFailure) (at <af78ad00a40d4f61b82afc6cafb0a416>:0)
UnityEngine.GUIUtility:ProcessEvent(Int32, IntPtr)

The code is the following:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.XR;
using UnityEngine.XR.ARFoundation;

public class RecognitionScript : MonoBehaviour
{
    private ARTrackedImageManager _arTrackedImageManager;

    private void Awake()
    {
        _arTrackedImageManager = FindObjectOfType<ARTrackedImageManager>();

    }

    public void OnEnable()
    {

        _arTrackedImageManager.trackedImagesChanged += OnImageChanged;
    }

    public void OnDisable()
    {
        _arTrackedImageManager.trackedImagesChanged -= OnImageChanged;
    }

    public void OnImageChanged(ARTrackedImagesChangedEventArgs args)
    {
        foreach (var trackedImage in args.added)
        {
            UnityEngine.Debug.Log(trackedImage.name);
        }
    }
}


texts: Error suddenly when compiling Desktop on Android Studio - all projects - nothing changed - LibGDX

texts:
I have just gone into Android Studio to open a project. It will run in Android but not my Desktop configuration.
Nothing of the code has been changed and I have now tried 3 projects, also a brand new project straight from the LibGDX Project Generator .jar file.

The error I get in Studio is:
Exception in thread "LWJGL Application" java.lang.NullPointerException
    at com.badlogic.gdx.backends.lwjgl.LwjglGraphics.createDisplayPixelFormat(LwjglGraphics.java:322)
    at com.badlogic.gdx.backends.lwjgl.LwjglGraphics.setupDisplay(LwjglGraphics.java:216)
    at com.badlogic.gdx.backends.lwjgl.LwjglApplication.mainLoop(LwjglApplication.java:142)
    at com.badlogic.gdx.backends.lwjgl.LwjglApplication$1.run(LwjglApplication.java:124)

Process finished with exit code 0

Please can anybody help me here? thanks


texts: How to change colors where two boxcollider2d objects intersect (Unity 5 2D)

texts:
I'm creating a 2D game in Unity that relies on combining colors.  For instance, if the yellow sprite in in a position, and the player slides a magenta sprite partly over it, the area where the two intersect should become red.  If someone then slides a cyan sprite, the cyan+yellow should be green, the cyan+magenta should be blue, and the cyan+red should be black.

I was planning to use box collider 2d and use a OverlapArea on TriggerStay2D, but that didn't work.  I'm assuming in my code below that pointA is the upper left coordinate of the first sprite, and pointB is the upper left coordinate of the second sprite (though perhaps I'm wrong on that).

void OnTriggerStay2D(Collider2D collisionInfo)
{
    Debug.Log("I am still colliding");

    Vector2 pointA;
    Vector2 pointB;

    pointA = this.transform.position;
    pointB = collisionInfo.transform.position;

    Vector2 pointC = Physics2D.OverlapArea(pointA, pointB);

}

After reading the documentation, I think I'm not understanding what OverlapArea returns - it seems to return a Collision, but that doesn't make a whole lot of sense.

Any thoughts on this?  Is there a better way than trying to find a pair of 2-Tuples that would bound the collision area and create a new sprite of the new color over that area?


texts:
I have a gameloop for a simulation I'm making, I noticed that the simulation is going very slow, When i checked the DeltaTime it was very small, I set the target fps to be 1 (deltatime should be 1 in that case) and it was still very small (1.1920929E-07) which is making the simulation super slow even with huge numbers.
Here's the gameloop code
    public void Run()
    {
        Ticks = 0;
        _running = true;

        float totalTimeBeforeUpdate = 0;
        float previousTimeElapsed = 0;

        var clock = new Stopwatch();
        clock.Start();

        while (_running)
        {
            var totalTimeElapsed = (float) clock.Elapsed.TotalSeconds;
            var deltaTime = totalTimeElapsed - previousTimeElapsed;
            previousTimeElapsed = totalTimeElapsed;

            totalTimeBeforeUpdate += deltaTime;

            if (totalTimeBeforeUpdate >= TimeUntilUpdate)
            {
                GameTime.Update(deltaTime, (float) clock.Elapsed.TotalSeconds);
                totalTimeBeforeUpdate = 0;

                Update(GameTime);

                Draw(GameTime);

                Ticks++;
            }
        }
    }

Edit: Yes I'm getting the correct target fps
Edit: Here's the results I'm getting when debugging
Ticks: 0, Total Time Elapsed: 1.0002049, Delta Time: 1E-07, FPS: 10000000
Ticks: 1, Total Time Elapsed: 2.0000005, Delta Time: 1E-07, FPS: 10000000
Ticks: 2, Total Time Elapsed: 3.0000003, Delta Time: 1E-07, FPS: 10000000
Ticks: 3, Total Time Elapsed: 4.0000004, Delta Time: 1E-07, FPS: 10000000
Ticks: 4, Total Time Elapsed: 5.0000004, Delta Time: 1E-07, FPS: 10000000
Ticks: 5, Total Time Elapsed: 6.0000005, Delta Time: 1E-07, FPS: 10000000
Ticks: 6, Total Time Elapsed: 7.0000004, Delta Time: 1E-07, FPS: 10000000
Ticks: 7, Total Time Elapsed: 8.0000003, Delta Time: 1E-07, FPS: 10000000
Ticks: 8, Total Time Elapsed: 9.0000002, Delta Time: 1E-07, FPS: 10000000
Ticks: 9, Total Time Elapsed: 10.0000003, Delta Time: 1E-07, FPS: 10000000
Ticks: 10, Total Time Elapsed: 11.0000012, Delta Time: 1E-07, FPS: 10000000
Ticks: 11, Total Time Elapsed: 12.0000005, Delta Time: 1E-07, FPS: 10000000
Ticks: 12, Total Time Elapsed: 13.0000005, Delta Time: 1E-07, FPS: 10000000
Ticks: 13, Total Time Elapsed: 14.0000005, Delta Time: 1E-07, FPS: 10000000
Ticks: 14, Total Time Elapsed: 15.0000005, Delta Time: 1E-07, FPS: 10000000
Ticks: 15, Total Time Elapsed: 16.0000004, Delta Time: 1E-07, FPS: 10000000
Ticks: 16, Total Time Elapsed: 17.0000005, Delta Time: 1E-07, FPS: 10000000
Ticks: 17, Total Time Elapsed: 18.0000005, Delta Time: 1E-07, FPS: 10000000
Ticks: 18, Total Time Elapsed: 19.0000006, Delta Time: 1E-07, FPS: 10000000
Ticks: 19, Total Time Elapsed: 20.0000005, Delta Time: 1E-07, FPS: 10000000
Ticks: 20, Total Time Elapsed: 21.0000006, Delta Time: 1E-07, FPS: 10000000
Ticks: 21, Total Time Elapsed: 22.0000006, Delta Time: 1E-07, FPS: 10000000
Ticks: 22, Total Time Elapsed: 23.0000002, Delta Time: 1E-07, FPS: 10000000

it says the FPS is really high, that's because I'm using the deltatime to calculate it, you can see its running at 1 FPS (which is what i set it to) from the Ticks and total time elapsed, Delta Time is really smalls (very close to 0) and it should be actually 1 since I'm running at 1 FPS


texts: Libgdx Box2D random positions and intervals falling bodies

texts:
I need to make that objects fall from the top of the screen random intervals and positions. Here's my code where I create lot of objects and add them to ArrayList

private void createBalls() {
        BodyDef ballBodyDef = new BodyDef();
        ballBodyDef.type = BodyDef.BodyType.DynamicBody;

        CircleShape shape = new CircleShape();
        shape.setRadius(10/Constants.PPM);
        shape.setPosition(new Vector2(w/4/ Constants.PPM, 5));

        FixtureDef fd = new FixtureDef();
        fd.density = 1;
        fd.friction = 0.5f;
        fd.restitution = 0.5f;
        fd.shape = shape;

        do {
            float rand = MathUtils.random(-2.0f, 2f);
            shape.setPosition(new Vector2(w/4/ Constants.PPM + rand, 5));
            fd.shape = shape;

            bodyArrayList.add(world.createBody(ballBodyDef));
            bodyArrayList.get(bodyArrayList.size() - 1).createFixture(fd);
        } while (bodyArrayList.size() < 100);

        shape.dispose();
    }

this code works fine (except that all objects fall at single time). So is it possible to make that objects would fall at different time?


texts:
I'm not sure if the title matches what I'm actually facing

I'm trying to test if I can see a point is in my field of view (in the context of an NPC seeing in it's direction.)

I know that:

cos0 = (A.B)/||A||||B||

We have our point x. We have our heading h. We have our position p.

cos0 = (h.(p-x))/||h||||x-p||

So to test whether a point is in it's view we simply check if

cos0 >= view/2;

But for some reason the bigger the angle, the closer you have to be to the center in order for it to detect you. For smaller angles it's the opposite:

Here is what I have now. (click the " Play flash full screen " , for some reason the hosting settings won't show it in it's original size)

You can see that the bigger views actually respond only when you are near the center.
While the smaller views start rotating even though you're not even in their view.

for now I'm using the mouse coordinates. I'm pretty sure all vectors operate in the same space coordinates.

Properties and constructor:

private var heading:Vec2 = new Vec2(); // Always a unit vector
private var position:Vec2 = new Vec2();
private var fovDeg:Number = 30.0;
private var fovRad:Number = 0.0;
private var distance:Number = 300;
private static const toRad:Number = (Math.PI / 180);

public function Fieldofview(degree:Number = 45.0 )
{
   fovDeg = degree;
   fovRad = fovDeg * toRad;
   fovRad /= 2;
   heading._x = 1.0;
   heading._y = 0.0;
   drawField();
}

The function to test wether it's within the view

public function pointIsInView(p:Vec2) : Boolean
{
    //vector from our position to point to test
    var diffVec:Vec2 = p.sub(position);
    var diffNorm:Vec2 = diffVec.normalize();
            //both are unit vectors so the dot should be enough
    var dot:Number = diffNorm.dot(heading);

    if (diffVec.length() > distance ) {
        return false;
    }

    //Check if we are in bound
    if ( dot >= fovRad) {
        return true;
    }

    return false;

}

Anyone have an idea what is causing this?


texts: Actually Implementing "C# as a scripting Language" in XNA

texts:
Following an example from this thread, I've made an application that dynamically loads in C# "scripts" (actually, plugins) into my game -- but I've hit a snag: how do I reference the assemblies for XNA when compiling? Can I even be sure the XNA assemblies will be around on the end-user's machine?

This line from the example:

     options.ReferencedAssemblies.Add(Assembly.GetExecutingAssembly().Location);

Adds the referenced assemblies for my game only, not the XNA assemblies (for instance, for Vector3, Matrix, etc.). The only way to add the assemblies seems to be inlining an absolute URI to the necessary .dll files.

EDIT: Looking at this thread I have discovered how to load all of the required assemblies:

foreach (AssemblyName assemblyName in executingAssembly.GetReferencedAssemblies())
        cp.ReferencedAssemblies.Add(Assembly.Load(assemblyName).Location);

But apparently the XNA assemblies aren't included in this list for me :(


texts:
We're currently developing a 2D Platformer and we decided to take some time to implement Accessibility Features. But we couldn't find good information about Accessibility Features, muss less how to implenent them. With Accessibility Features we mean things like to reduce risk of seizure (Photosensitive Epilepsy). There will be a Accessibility Menu to manually activate these.

So does anybody have some Ideas what Features we could implement and some helpful tips about how to implement them?


texts: What are some methods to represent train tracks?

texts:
I looked into this a while back for a small project, but didn't get too far.  I'd like to create a small program that lets a user draw a train track and then allows a "train" to follow said track on a 2D plane.  I'd like the track to be pretty free form and result in a nice smooth line.  I played around with cubic splines and had decent results, but had a ton of trouble getting the train to follow the spline.  I also had a lot of trouble creating multiple tracks and switching a train from one track to another.

Does anyone have advice, articles, or source code that can help me figure something out?  Thanks!


texts: Check if a game object's component can be destroyed

texts:
Developing a game in Unity, I'm making liberal use of [RequireComponent(typeof(%ComponentType%))] to ensure components have all dependencies met.

I'm now implementing a tutorial system which highlights various UI objects. To do the highlighting, I'm taking a reference to the GameObject in the scene, then I clone it with Instantiate() and then recursively strip away all components which aren't needed for display. The problem is that with the liberal use of RequireComponent in these components, many cannot be simply removed in any order, since they are depended on by other components, which have not been deleted yet.

My question is: Is there a way to determine whether a Component can be removed from the GameObject it is currently attached to.

The code I'm posting technically works, however it throws Unity errors (not caught in try-catch block, as seen in the image

Here's the code:

public void StripFunctionality(RectTransform rt)
{
    if (rt == null)
    {
        return;
    }

    int componentCount = rt.gameObject.GetComponents<Component>().Length;
    int safety = 10;
    int allowedComponents = 0;
    while (componentCount > allowedComponents && safety > 0)
    {
        Debug.Log("ITERATION ON "+rt.gameObject.name);
        safety--;
        allowedComponents = 0;
        foreach (Component c in rt.gameObject.GetComponents<Component>())
        {
            //Disable clicking on graphics
            if (c is Graphic)
            {
                ((Graphic)c).raycastTarget = false;
            }

            //Remove components we don't want
            if (
                !(c is Image) &&
                !(c is TextMeshProUGUI) &&
                !(c is RectTransform) &&
                !(c is CanvasRenderer)
                )
            {
                try
                {
                    DestroyImmediate(c);
                }
                catch
                {
                    //NoOp
                }
            }
            else
            {
                allowedComponents++;
            }
        }
        componentCount = rt.gameObject.GetComponents<Component>().Length;
    }

    //Recursive call to children
    foreach (RectTransform childRT in rt)
    {
        StripFunctionality(childRT);
    }
}

So the way this code generated the last three lines of the debug log above is the following: It took as input a GameObject with two components: Button and PopupOpener. PopupOpener requies that a Button component is present in the same GameObject with:

[RequireComponent(typeof(Button))]
public class PopupOpener : MonoBehaviour
{
    ...
}

The first iteration of the while loop (denoted by the text "ITERATION ON Button Invite(clone)") attempted to delete the Button first, but couldn't as it is depended on by the PopupOpener component. this threw an error. Then it attempted to delete the PopupOpener component, which it did, since it is not depended on by anything else. In the next iteration (Denoted by the second text "ITERATION ON Button Invite(clone)"), it attempted to delete the remaining Button component, which it now could do, since PopupOpener was deleted in the first iteration (after the error).

So my question is whether it is possible to check ahead of time if a specified component can be removed from its current GameObject, without invoking Destroy() or DestroyImmediate(). Thank you.


texts: Move rigidbody using WASD keys but rotate it based on camera/mouse movement

texts:
I am very new to unity and my scripts are based on some scripts found on the web.

I want to make a first person view so the camera is attached to my rigidbodys head. Then i want to move my rigidbody based on keyboard input (wasd) and rotate it using the mouse movement.

Until now, i used the following code for moving my rigidbody:

void Update() {

    /* calculate rigidbody movement */
    movement = new Vector3( Input.GetAxisRaw("Horizontal"), 0, Input.GetAxisRaw("Vertical")).normalized;

    /* calculate mouse look to rotate the rigidbody*/
    mouseDelta = new Vector2(Input.GetAxisRaw("Mouse X"), Input.GetAxisRaw("Mouse Y"));
    mouseDelta = Vector2.Scale(mouseDelta, new Vector2(sensitivity * smoothing, sensitivity * smoothing));
    smoothV.x = Mathf.Lerp(smoothV.x, mouseDelta.x, 1f / smoothing);
    smoothV.y = Mathf.Lerp(smoothV.y, mouseDelta.y, 1f / smoothing);
    mouseLook += smoothV;

}

void FixedUpdate() {

    /* apply rigidbody movement from Update() */
    transform.Translate( movement * moveSpeed * Time.deltaTime );
    /* apply rigidbody rotation from Update() */
    transform.localRotation = Quaternion.AngleAxis(mouseLook.x, transform.up);
    /* apply camera rotation from Update() */
    Camera.main.transform.localRotation = Quaternion.AngleAxis(-mouseLook.y, Vector3.right);

}

I learned today that i dont have to move a rigidbody's transform but now i am totally confused and it seems i have to restart my whole (first!) project.

So when i use MovePosition and MoveRotation, how do i rotate it based on the camera perspective/mouse movement?

I think the movement Vector is ok so i can simply rewrite the FixedUpdate to something like

rigidbody.MovePosition(movement * speed * Time.deltaTime)

but i am totally stuck on how to apply the camera rotation to my rigidbody to use it like

void FixedUpdate() {
    /* move the rigidbody */
    rigidbody.MovePosition(movement * moveSpeed * Time.deltaTime);
    /* rotate the camera */
    camera.transform.localRotation = Quaternion.AngleAxis(-mouseLook.y, Vector3.right);

    /* but how can i rotate the rigidbody based on the cameras rotation??? */
    rigidbody.MoveRotation(?????);

}

I hope its clear what i want, thank you!


texts:
I've basically just started developing with PyGame and I am having trouble with the whole Sprite concept. I have been looking every where for guides on how to use it, I just can't seem to find any. I would like to know the basic concept of how it all works. This is the code I have been working on:

import pygame, sys, os, time
from pygame.locals import *

windowWidth = 320
windowHeight = 640
halfWidth = int(windowWidth / 2)
halfHeight = int(windowHeight / 2)

#main blocks width and height (32x32)
blockSize = 32

#rgb
red = [255,000,000]
green = [000,255,000]
blue = [000,000,255]
black = [000,000,000]
white = [255,255,255]

bgColor = black
playerColor = white
blockColor = green

fps = 60

assert windowWidth % blockSize == 0, "Too much space/not enough space for the ground"
floorAmt = windowWidth/blockSize
print floorAmt

floorY = windowHeight-blockSize
print floorY

floor = pygame.sprite.Group()

def main():

    global fpsClock, displayScreen

    inAir = False

    upVel = 0
    downVel = 0
    leftVel = 0
    rightVel = 0

    fpsClock = pygame.time.Clock()
    displayScreen = pygame.display.set_mode((windowWidth, windowHeight))
    pygame.display.set_caption("Jump Test")

    grass = pygame.image.load("grass.png")
    grass = grass.convert_alpha()
    grassRadius = blockSize

    floorDraw(blockSize, floorAmt, floorY, grass)

    while True:
        fpsClock.tick(fps)

        for event in pygame.event.get():
            if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE):
                pygame.quit()
                sys.exit()
                raise SystemExit, "Exit"

        displayScreen.fill(black)
        floorDraw(blockSize, floorAmt, floorY)

        pygame.display.flip()
        pygame.display.update()
        fpsClock.tick(fps)

def floorDraw(blockSize, floorAmt, floorY, grass):
    for i in range(floorAmt):
        floorX = i*blockSize
        grassRect = (floorX, floorY, blockSize, blockSize)
        floor.add(grass)
        displayScreen.blit(grass, grassRect)

        v
if __name__ == "__main__":
    main()

basically I just want to know how to make these grass blocks into sprites in a group, so that when I add my player (also a sprite) I can determine whether or not he is in the air or not through the collision system. Can someone please explain to me how I would do this. All I am looking for is basically a kick starter because some of the documentation is quite bad in my opinion as it doesn't completely tell you how to use it. Any help is greatly appreciated :)


texts: Implement Negascout Algorithm with stack

texts:
I'm not familiar with how these stack exchange accounts work so if this is double posting I apologize. I asked the same thing on stackoverflow.

I have added an AI routine to a game I am working on using the Negascout algorithm.

It works great, but when I set a higher maximum depth it can take a few seconds to complete. The problem is it blocks the main thread, and the framework I am using does not have a way to deal with multi-threading properly across platforms.

So I am trying to change this routine from recursively calling itself, to just managing a stack (vector) so that I can progress through the routine at a controlled pace and not lock up the application while the AI is thinking.

I am getting hung up on the second recursive call in the loop. It relies on a returned value from the first call, so I don't know how to add these to a stack.

My Working c++ Recursive Code:

MoveScore abNegascout(vector<vector<char> > &board, int ply,
                  int alpha, int beta, char piece) {
if (ply==mMaxPly) {
    return MoveScore(evaluation.evaluateBoard(board, piece, oppPiece));
}

int currentScore;
int bestScore = -INFINITY;
MoveCoord bestMove;
int adaptiveBeta = beta;

vector<MoveCoord> moveList =
    evaluation.genPriorityMoves(board, piece,
                                findValidMove(board, piece, false));

if (moveList.empty()) {
    return MoveScore(bestScore);
}

bestMove = moveList[0];

for(int i=0;i<moveList.size();i++) {
    MoveCoord move = moveList[i];

    vector<vector<char> > newBoard;
    newBoard.insert( newBoard.end(), board.begin(), board.end() );
    effectMove(newBoard, piece, move.getRow(), move.getCol());

    // First Call ******
    MoveScore current = abNegascout(newBoard, ply+1, -adaptiveBeta,
                                    -max(alpha,bestScore), oppPiece);

    currentScore = - current.getScore();

    if (currentScore>bestScore){
        if (adaptiveBeta == beta || ply>=(mMaxPly-2)){
            bestScore = currentScore;
            bestMove = move;
        }else {
            // Second Call ******
            current = abNegascout(newBoard, ply+1, -beta,
                                  -currentScore, oppPiece);
            bestScore = - current.getScore();
            bestMove = move;
        }

        if(bestScore>=beta){
            return MoveScore(bestMove,bestScore);
        }
        adaptiveBeta = max(alpha, bestScore) + 1;
    }
}
return MoveScore(bestMove,bestScore);
}

If someone can please help by explaining how to get this to work with a simple stack. Example code would be much appreciated. While c++ would be perfect, any language that demonstrates how would be great.

Thank You.


texts: Middleware to Bring 3D Meshes into OpenGL ES 2.0

texts:
Say I develop a game for mobile platform running OpenGL ES 2.0. I have done 2D part, and now I wish to import some 3D objects.

The imported 3D objects must contain the following:

Vertices positions
Normals
UVs
Texturing information
Animation information
Collision mesh
Maybe some other things...

I am aware, that I could and (maybe should) create my own file format that brings these data from 3D authoring application (3ds Max, Maya, Softimage) into the game.

However, doing so from scratch is going to be really be a lot of work. Therefore, is there any available solution/middleware, that will let me import 3d meshes into my game, ready to use?

The solution/middleware should be:

easy to use
easy to port
efficient
not consuming too much memory with unnecessary things
containing all the above mentioned features plus things I haven't considered yet

Programming language is: C++.

Currently, I'm developing under Windows 7, Visual Studio 2010, and OpenGL ES 2.0 emulator.

Later, the product will be ported to iOS and possibly Android.


texts: Programmatically creating new tags in Unity

texts:
I'm writing a custom editor script to add tags programmatically.

I got the error of IndexOutOfRangeException: Array index is out of range from the lines below:

SerializedObject tagManager = new SerializedObject(AssetDatabase.LoadAllAssetsAtPath("ProjectSettings/TagManager.asset")[0]);
SerializedProperty tagsProp = tagManager.FindProperty("tags");

These are my codes:

SerializedObject tagManager = new SerializedObject(AssetDatabase.LoadAllAssetsAtPath("ProjectSettings/TagManager.asset")[0]);
SerializedProperty tagsProp = tagManager.FindProperty("tags");

// Adding a Tag
string s = "Instantiated";

// First check if it is not already present
bool found = false;

for (int i = 0; i < tagsProp.arraySize; i++)
{
    SerializedProperty t = tagsProp.GetArrayElementAtIndex(i);
    if (t.stringValue.Equals(s)) { found = true; break; }
}

// if not found, add it
if (!found)
{
    tagsProp.InsertArrayElementAtIndex(0);
    SerializedProperty n = tagsProp.GetArrayElementAtIndex(0);
    n.stringValue = s;
}

Latest Update:
Error IndexOutOfRangeException: Array index is out of range is solved by resolving file location in my original script. I apologized for that.

Fixed:
Added a line in the script to update the properties

if (!found)
{
    tagsProp.InsertArrayElementAtIndex(0);
    SerializedProperty n = tagsProp.GetArrayElementAtIndex(0);
    n.stringValue = s;
    tagManager.ApplyModifiedPropertiesWithoutUndo();
}


texts: How to hit an enemy, or "how do entities interact with each other?"

texts:
The title might be a tad simple for the purpose, but bear with me.

I'm a tad lost about how to do the interaction between game objects. I use an entity-component-system framework and I've got the basics up and running: the player can run around, collisions get reported correctly, graphics are updating nicely and so on. I even have an AI enemy wandering around.

However, what if I want to hit the enemy with a sword? How do I know what the player hit? The naive solutions (for e.g. Box2D) do something like this:

void BeginContact(b2Contact* contact)
{
    // Get the colliding bodies
    b2Body* body1 = contact->GetFixtureA()->GetBody();
    b2Body* body2 = contact->GetFixtureB()->GetBody();

    // Get the user data
    int body1UserData = body1->GetUserData();
    int body2UserData = body2->GetUserData();

    // Check if the enemy hit the player
    if((body1UserData == PLAYER && body2UserData == ENEMY) ||
       (body2UserData == PLAYER && body1UserData == ENEMY))
    {
        // Enemy collided with player, damage the player
        causeDamageToPlayer();
    }
}

This solution "works", but to my understanding has very little use in real-life scenario. Again: what if I want to hit an enemy with a sword? Which enemy did I hit? Should I really keep adding and removing the sword collider from the game world? I can't really find any good reads on this topic. There's lots of articles and books about game engines, but the actual game architecture is commonly left out.

I'm purposefully leaving this a bit vague since there is probably multiple ways to do that. I'm after some real-life usage examples and how to do things in a bigger scale, where there's tens of different enemies / entities, various weapons and so on.


texts: Simple coherent noise function to use in a GLSL shader

texts:
I'm looking for a simple (but especially fast) coherent noise function to use it in a shader written in GLSL.

I don't need it to be excessively smooth or good looking, I just need that it has the following properties:

Passing in the same input value will always return the same output value.
A small change in the input value will produce a small change in the output value.
A large change in the input value will produce a random change in the output value.

I really need it to be fast, as it will be called once for each pixel by the GPU (to have an idea of how fast it should be, I tried Perlin Noise and it crashed my application).

What method should I use? I'd also like if the same pattern didn't repeat over time.


texts: Do I need a database to support a sign-in system to associate a player with their save/highscore data?

texts:
I am making a 2d game with Unity, and in my game I want to add a username and a password for each player, so that when the player signs in, they will get all the data about what they played until the moment they signed in (like their highscore and so on)

So my question is: do I need to use a database like sqlite, or could this be done with Unity without needing an external database?


texts: Where to start in a project after the design phase?

texts:
I want to start a new project but I'm a beginner. I already have most of the ideas in terms of gameplay, lore,... I have written pages of notes and concepts about the game. Basically, I know most of the things I want to put in my game and a big part of their design is done.

I made a few small projects with Unity, I know how to program, I know how to use Blender and I have edited some textures. Basically, I know the basis most of the technologies I'll need to use.

The problem is that I don't know where to begin. Should I start with modelling? Create maps? Start with scripting? I'm undecided because many of these tasks can be done in parallel if you have people working with you and are more or less independent in early stages of development.

All of the answers I read were for people who didn't even have ideas in the first place and knew nothing about development. My problem is more about project management after the design phase.


texts: How do I rotate a structure of hexagonal tiles on a hexagonal grid?

texts:
My 2D isometric game uses a hexagonal grid map. In reference to the image below, how do I rotate the light blue hexagon structures by 60 degrees around the pink hexagons?

EDIT:

Main hex is (0,0). Other hexes are children, count of them is fixed.  I'm going to define only one position (in this case its right) and calculate other directions if needed (left-bottom, right-botom, right-top, left-top and left). Other hexes are defined like: Package.Add(-1,0), Package.Add(-2,0) and so on.

switch(Direction)
{
case DirRightDown:
    if(Number.Y % 2 && Point.X % 2)
        Number.X += 1;
    Number.Y += Point.X + Point.Y / 2;

    Number.X += Point.X / 2 - Point.Y / 1.5;
    break;
}

In this code Number is the main hex and Point is the hex that I want to rotate, but it doesn't work:


texts: Maths and basics for a 2d top down game (object moving and rotating around center)

texts:
I want to eventually create a pseudo 3d game engine like the original Wolfenstein or doom. I am starting from 0 so my first step is to create a 2d top down view where my character would be in the center of the screen always looking up and objects would move around him.

I know how to create a game like Zelda where objects move but dont rotate and the center character just look in different directions. But after that i need some help. I tried to do some research online but could not find exactly what i was looking for.

I dont know yet what language i would use to code my engine. My 1st choice would be c++ but i want my evenual game to be easily ported on different platforms. For that reason ill probably go with Java.


texts: Text not being rendered until I recreate the text class in SDL

texts:
I made a Text class, it is as shown below:

Text::Text(const int score, const float &x, const float &y, const float &w, const float &h, SDL_Renderer *rend)
{
    font = TTF_OpenFont("font/Subway.ttf", 50);
    if (font == NULL)
    {
        std::cout << "Something went wrong\n%s\n" << TTF_GetError();
    }

    rect = { x, y, w, h };
    color = { 100, 100, 100 };

    tempSurface = TTF_RenderGlyph_Blended(font, *std::to_string(score).c_str(), color);
    tex = SDL_CreateTextureFromSurface(rend, tempSurface);

    SDL_FreeSurface(tempSurface);
}

void Text::draw(SDL_Renderer *rend)
{
    SDL_RenderCopy(rend, tex, NULL, &rect);
}

Text::~Text()
{
    //Clean up stuff
    font = nullptr;
    tempSurface = nullptr;
    SDL_DestroyTexture(tex);
    tex = nullptr;
}

I created two of these class objects to hold the image that is created from the players score variables. Issue is that the first time these objects are created, they are not shown on the screen. It's only when the objects are created again that they are shown.

In gameloops constructor class:

GameLoop::GameLoop()
{
    window = new Window("Pong Test", 640, 480, SDL_WINDOW_SHOWN);
    player1 = new Paddle(50, 50, 10, 60);
    player2 = new Paddle(580,50,10,60);

    player1ScoreText = new Text(player1Score, SCREEN_WIDTH * .25 - 50 / 2, SCREEN_HEIGHT * .25, 50, 75, r);
    player2ScoreText = new Text(player2Score, SCREEN_WIDTH * .75 - 50 / 2, SCREEN_HEIGHT * .25, 50, 75, r);

    ren = new Renderer((*window).GetWindow(), -1, SDL_RENDERER_ACCELERATED);

    r = (*ren).getRenderer();

    ball = new Ball("ball.bmp", r);
}

It's created then its rendered here:

void GameLoop::Render()
{
    ren->setColor(0, 0, 0, 0);
    ren->clear();
    player1->Draw(r,255,255,255,255);
    player2->Draw(r,255,255,255,255);
    player1ScoreText->draw(r);
    player2ScoreText->draw(r);
    ball->draw(r,255,255,255);

    ren->present();
}

It's not showing.. not until this happens:

void GameLoop::Score()
{
    delete ball;

    player1ScoreText = new Text(player1Score, SCREEN_WIDTH * .25 - 50 / 2, SCREEN_HEIGHT * .25, 50, 75, r);
    player2ScoreText = new Text(player2Score, SCREEN_WIDTH * .75 - 50 / 2, SCREEN_HEIGHT * .25, 50, 75, r);

    ball = new Ball("ball.bmp", r);
}

From what I can see it doesn't matter where you recreate the classes, it will work. Is this due to how the classes are being initialised?

My first thought is that it would be this line:

tempSurface = TTF_RenderGlyph_Blended(font, *std::to_string(score).c_str(), color);

due to the fact I pass in a pointer to converted integer. However if I don't pass in a pointer I get this error:

error C2664: 'SDL_Surface *TTF_RenderGlyph_Blended(TTF_Font *,Uint16,SDL_Color)' : cannot convert argument 2 from 'const char *' to 'Uint16'

Any help would be greatly appreciated.