texts: Unity & inheritance. Different results DebugMode/Build

texts:
Here are my 2 Classes

public class Item : MonoBehaviour
{
    [SerializeField] protected TextMeshProUGUI txt_itemNom;
    [SerializeField] protected string itemNom;

 //No Start
 //No Update
}

public class Article : Item
{
    public int articleLevel = 1;

    public void Start()
    {
        txt_itemNom.SetText(itemNom);
    }

//Called by a button OnClick
    public void OpenBuyWindow()
    {
            PlayerRessources.instance.OpenBuyWindow(base.txt_itemNom.text + " Lvl " + articleLevel);
    }
}

It is very simple. When I start the game, the GameObject with the Article script set the correct item name in the TextMeshProUGUI object named txt_itemNom.
The player can click a button to buy this item, it will displays a confirmation window.
And it works perfectly! Or at least, it works when I press Play in the editor but weirldy it behaves differently in the build version.

In the build version, the value of base.txt_itemNom.text in

PlayerRessources.instance.OpenBuyWindow(base.txt_itemNom.text + " Lvl " + articleLevel);

is the original value of base.txt_itemNom.text. (which is "Item name" or something).
So I don't get it because base.txt_itemNom.text is correctly setted in the Start because it's displayed in the UI.

It looks like the Article loses its parent class (Item) reference when the player click to OpenBuyWindow(). But only for the TextMeshProUGUI contained in the Item class.

Additionnal info:

The Article script is attached to a prefab.
The prefab is not instantiated by a script. I just added it in the Hierarchy
If I use the string variable itemNom instead of base.txt_itemNom.text, then it will work.


texts: Efficiently representing a dynamic transform hierarchy

texts: I'm looking for a way to represent a dynamic transform hierarchy (i.e. one where nodes can be inserted and removed arbitrarily) that's a bit more efficient than using a standard tree of pointers . I saw the answers to this question ( Efficient structure for representing a transform hierarchy ), but as far as I can determine the tree-as-array approach only works for static hierarchies or dynamic ones where nodes have a fixed number of children (both deal-breakers for me). I'm probably wrong about that but could anyone point out how? If I'm not wrong are there other alternatives that work for dynamic hierarchies?


texts: Scripting a sophisticated RTS AI with Lua

texts:
I'm planning to develop a somewhat sophisticated RTS AI (eg see BWAPI).  have experience programming, but none in game development, so it seems easiest to start by scripting the AI of an existing game I've played, Warhammer 40k: Dawn of War (2004). As far as I can tell, the game AI is scripted with some variant of Lua (by the file extension .ai or .scar). The online documentation is sparse and the community isn't active anymore.

I'd like to get some idea of the difficulty of this undertaking. Is it practical with a scripting language like Lua to develop a RTS AI that includes FSMs, decision trees, case-based reasoning, and transposition tables?

If someone has any experience scripting Dawn of War, that would also help.


texts:
This may sound pretty obvious to game devs here but I'm wondering if a game can be called 3D if it has 3D assets but static isometric like camera view and not rotating at all.

I tried searching the different types of video game graphics but I only find the inverse which is called 2.5D because it tries to fake 3D and that it uses 2D isometric assets.

My question is

1) What really makes a game a 3D game?

2) If a game have 3D assets with a static non rotating isometric camera view is not called a 3D game, then what?


texts:
I am experimenting with Crafty.js, and I have called .image() on an entity, and the image is not loading. When I look through the web inspector, I can see that the cloud entity exists, and that the cloud image is found, but it is not showing up. What is the proper way to load an image on an entity, and what is wrong with my code?

mainCrafty.js:

Crafty.e('myCloud, 2D, DOM, Image')        // cloud
        .attr({x: 300, y: 10, w: 45, h: 30})
        .image('images/cloud.png');

Here is the directory structure:

index.html
images/
   cloud.png
scripts/
   crafty.js
   mainCrafty.js


texts: WorldToGUIPoint seems always off by about 2 pixels

texts:
I'm trying to draw small boxes at each vertex of a mesh, in the editor. My OnSceneGUI code looks like this:

foreach (Vector3 vertex in _mesh.vertices) {
    Vector3 worldVertex = _meshTransform.localToWorldMatrix.MultiplyPoint3x4(vertex);
    Vector2 guiPoint = HandleUtility.WorldToGUIPoint(worldVertex);
    var rect = new Rect(guiPoint, Vector2.one * BOX_SIZE);
    EditorGUI.DrawRect(rect, Color.red);
}

I want the upper-left corner of each box to align with the mesh vertices. With the above code, the boxes are drawn at the wrong location, as you can see in the picture below. If I apply an offset of (2, -2) in GUI coordinates, however, the boxes are drawn at the correct location.

I'd like to avoid having to hard-code this (2, -2) offset into each draw call. Why is Unity off by a few pixels here? I also tried using GUI.Box to do the drawing, but it was off by the same amount. What is going on?

Incorrect

Correct. With constant (2, -2) offset

Update: I have an untested hypothesis as to why this is happening. I am rendering a GUI rect with the default GUIStyle. The default GUIStyle has the padding and margin values set. I bet that if I created a custom GUIStyle with zero padding and margin the rects would draw where I want them to.


texts: Unity custom inspector - How to serialize scene objects in ScriptableObject?

texts:
I am writing a custom inspector for the artist in our team to design some simple animations (without using mecanim).

The basic setup is the following:

Animations are saved as ScriptableObjects. There is a class AnimationBase that inherits from ScriptableObject and different Animation classes that inherit from AnimationBase.

There is an AnimationSystem script that stores the animations for one gameobject. Animations can be added dynamically for different events (I got multiple MyAnimation[] to store those per event type). It also stores a string with the name of a ScriptableObject AnimationList. That ScriptableObject stores the filenames for all the used animations in lists of strings for the different animation event types.

Now I have an animation "EnableAnimation" (inheriting from AnimationBase and therefore a ScriptableObject) that should enable a gameobject. If I select a gameobject from the assets, the reference is saved in the EnableAnimation asset as expected. But when I select a gameobject from the scene, the EnableAnimation assets shows "Type mismatch" instead.

I think the problem is that I use a EnableAnimation asset but want to store information in the scene. Is it possible to store the ScriptableObject in the scene instead?

Other things to take into account for solving the problem:

The custom inspector should work for prefabs, prefab instances and normal gameobjects. If possible prefab instances should be allowed to use the same animations as the prefab but change some values per scene.
I have a prefab "A" that has an AnimationSystem component and a child gamobject "B". With the default inspector I can select B as an gameobject in a script and apply that change to the prefab. If I select a different gameobject in the scene and try to apply, the prefab does not save the reference. If possible, this behaviour should be used too.

Thank you for your help!


texts:
In D3D9, you could set BackBufferFormat to D3DFMT_UNKNOWN in the presentation parameters and D3D would select the format for you.

However, in D3D10, if I set the swap chain descriptor's BufferDesc.Format to DXGI_FORMAT_UNKNOWN, I get this error:

D3D11 ERROR: ID3D11Device::CreateTexture2D: A Texture2D does not support the following Format (0, UNKNOWN). [ STATE_CREATION ERROR #92: CREATETEXTURE2D_UNSUPPORTEDFORMAT]

By the way, if I'm calling D3D10CreateDeviceAndSwapChain, why am I getting a D3D11 error? I guess in Windows 8.1 d3d10 is implemented with d3d11 behind the scenes. Strange. Back to the question, I want to have D3D select the back buffer format for me, is it possible?

Edit: If it's not possible to select automatically, where can I find a good rationale to select it myself? The amount of choices is baffling.


texts:
Where can I find an easy to use and up to date C++ parser/library for the .tmx map format (used by the Tiled Map Editor) ?

EDIT: David's comment, 'Unless you want to build your game around the format of the parser..', got me thinking... So I have downloaded pugixml, which is an easy to use xml-parser with very straightforward documentation. Together with the spec for the TMX Map Format, I think I'll give it a try myself. I'll probably compare with Cocos2d-x's CCTMXTiledMap at some point.


texts:
I was wondering what efficient techniques are out there for mapping collision filtering between various bodies, sub-bodies, and so forth.
I'm working on a physics engine and I need ways for a user to easily specify some complex relationships between bodies (what should/shouldn't collide), and ways to organize that filtering data so that it's easily attainable / memory-efficient.   One part of my engine that could also be taken advantage is what my 'bodies' actually are. They're like folders that you can put convex shapes, and other bodies in as to organize the parts of a complex rigid body.

I'm familiar with the simple idea of having different layers of 2D bodies, but this is not sufficient for more complex mapping:

EXAMPLE:
(Think of having sub-bodies of a body, such as limbs, collide with each other by placing them on the same layer, and then wanting to only have the limbs collide with the ground but not the body)
- I don't see how a user could accomplish the above example with just a bunch of different layers... The body must collide with the ground and therefore be in the same layer, but the limbs must also be in the same layer as the ground, causing unwanted collision between the body and the limbs.

This can be solved with a multidimensional layer setup, but I would probably end up just creating more and more layers to the point where the simplicity and efficiency of layer filtering would be gone.

Are there any more complex filtering techniques that would solve complex situations such as the example? And even more possibly complex situations?


texts: Player fly's off of canvas when key pressed

texts:
I am fairly new to game development. I am programming a basic JavaScript canvas game. Whenever I press a key my player goes flying off of the canvas. Here is the controller code

document.onkeydown = function(event){
    if(event.keyCode === 87){
        player.up = true;
    }
    else if(event.keyCode === 83){
        player.down = true;
    }
    else if(event.keyCode === 65){
        player.left = true;
    }
    else if(event.keyCode === 68){
        player.right = true;
    }
}

document.onkeyup = function(e){
    if(e.keyCode === 87){
        player.up = false;
    }
    else if(e.keyCode === 83){
        player.down = false;
    }
    else if(e.keyCode === 65){
        player.left = false;
    }
    else if(e.keyCode === 68){
        player.right = false;
    }
}

if(game.keys && game.keys[87]){
        player.speedY += -0.4;
        if(player.speedY > player.maxSpeed){
            player.speedY = player.maxSpeed;
        }
    }
    if(game.keys && game.keys[83]){
        player.speedY += 0.4;
        if(player.speedY > player.maxSpeed){
            player.speedY = player.maxSpeed;
        }
    }
    if(game.keys && game.keys[65]){
        player.speedX += -0.4;
        if(player.speedX > player.maxSpeed){
            player.speedX = player.maxSpeed;
        }
    }
    if(game.keys && game.keys[68]){
        player.speedX += 0.4;
        if(player.speedX > player.maxSpeed){
            player.speedX = player.maxSpeed;
        }
    }

The above is the controller code... What improvements should be made on the above code.

edit
I realize you may need to see the entity creation code

function square(width, height, color, x, y) {
  this.width = width;
  this.height = height;
  this.x = x;
  this.y = y;
  this.speedX = 0;
  this.speedY = 0;
  this.right = false;
  this.left = false;
  this.up = false;
  this.down = false;
  this.rend = function(){
    ctx = game.context;
    ctx.fillStyle = color;
    ctx.fillRect(this.x, this.y, this.width, this.height);
  }
  this.movement = function() {
    this.x += this.speedX;
    this.y += this.speedY;
  }
}

edit max speed integration.

  var now = Date.now();
  var delta = now - lastUpdate;
  lastUpdate = now;
  this.width = width;
  this.height = height;
  this.x = x;
  this.y = y;
  this.angle = 0;
  this.maxSpeed = 3;
  this.speedX = 0;
  this.speedY = 0;
  this.rend = function(){
    ctx = game.context;
    ctx.fillStyle = color;
    ctx.globalAlpha = 1;
    ctx.fillRect(this.x, this.y, this.width, this.height);
  }
  this.movement = function() {
    this.x += this.speedX;
    this.y += this.speedY;
}
}

editadded player making function.


texts: Where and how to check if game was developed with bought Unity3D licence (not cracked app)?

texts:
We hired an external team from Eastern country. They built our mobile game app using Unity3d which we paid a lot of $K. We asked them to only use the software with bought license, not cracked one, and they said they will do it.

Now, we're ready to publish apps to official stores and I read on the net that guys from unity3d can always check if the app was made via bought license or via cracked software. If they discover it's been made with cracked software, they will ban the app and probably prosecute us.

Where can we find such tool to confirm that our software was indeed made by 100% licensed unity3d piece of software?


texts: Communication between Box2D and libGDX Stage (Scene2D) running in separate threads

texts:
I'm making a physics based 2D game using libGDX and Box2D. I want to move the execution of the simulation out of render thread. I use immutable messages and the BlockingQueue to pass the information about player actions. The Box2D applies forces and runs a frame of simulation. In the next step I would like to sync back the changes and update Scene2D Actors accordingly. Making an immutable copy of the state of the game world and sending it back using Gdx.app.postRunnable() is one option but it seems inefficient.

Is there any other option?


texts: Minecraft-Style Voxel Sunlight Algorithm

texts:
I'm implementing a pure Minecraft clone, and I want to implement sunlight.
I have a basic sunlight algorithm working perfectly in 2D, and I understand how to scale it to 3D.  But how do I make it so I don't have to recompute the entire sunlight every time I place a block?

Pseudocode, because the actual algorithm is not written very well :)

FUNC propogateSunlight(x,y,z):
    IF (x,y,z) is out of bounds then RETURN
    IF light_at(x,y,z) is <= 0 then RETURN

    # PROPOGATE
    IF light_can_spread(x,y-1,z) AND light_at(x,y-1,z)<light_at(x,y,z) then:
        set_light_at(x,y-1,z) to light_at(x,y,z)
        propogateSunlight(x,y-1,z)
    IF light_can_spread(x-1,y,z) AND light_at(x-1,y,z)<light_at(x,y,z) then:
        set_light_at(x-1,y,z) to light_at(x,y,z)-1
        propogateSunlight(x-1,y,z)
    *repeat above IF statement for (x-1,y,z), (x+1,y,z), (x,y,z-1), (x,y,z+1) and (x,y+1,z)

Then it sets the top layer to 16 (the max light level) and calls propogateSunlight on the top level.

This algorithm does what I want it to PERFECTLY.  The only downside is that it is really really slow.

So what (psuedocode) algorithm is there to place / remove blocks (without transparency) that make it so I don't have to recalculate the entire world?

P.S. The coordinate system is standard 3d graphics, XZ is ground plane, +Y is up and -Y is down.


texts:
So i have this script the checks if my mouse cursor is over the block and if it is i want the block to change color

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

public class BasicBlockFunction : MonoBehaviour {

public GameObject Block;
public Color StartingColor;
public Color HighlightColor;
Color color;
Ray ray;
RaycastHit hit;

// Use this for initialization
void Start () {

}

// Update is called once per frame
void Update () {
    MouseOver();
}

void MouseOver()
{
    ray = Camera.main.ScreenPointToRay(Input.mousePosition);

    if (Physics.Raycast(ray, out hit))
    {
        print(hit.collider.name);
        Block.GetComponent<Renderer>().material.color = HighlightColor;
    }
    else
    {
        Block.GetComponent<Renderer>().material.color = StartingColor;
    }

 }

}

I want to change the color only for the gameobject i have my mouse on.


texts: What's the best practice for a progress bar in OpenGL ES 2.0?

texts:
My attempt: I make a texture (could be a single colour or otherwise), and then stretch that texture from a minimum 0 up to a maximum max value. This works, but leaves me rather dissatisfied for a number of reasons, one of which being:

If I want rounded corners as the bar progresses, the edges are squashed or stretched.

My question: What is the best practice to achieve a progress bar result.

Thoughts: Is there a way to stop openGL from drawing anything from a certain x value onwards of a texture? That way I could draw the texture as it should appear, but specify the value of x.

I have found this potentially useful link.

Update

I get the impression that using the stencil buffer might be the way to go. The stencil buffer allows to define any region you like through which other rendered geometry can be clipped. Apparently there are many other uses for the stencil buffer, e.g. reflections.

Possible Solution

I ultimately achieved what I wanted using the stencil buffer combined with my own shader, since OpenGL ES 2.0 does not support glAplhaTest and related functions. Here's an image of the result:

The texture drawn to the stencil buffer was an elongated rectangle with rounded corners. The texture drawn to the image buffer was just a stretched red rectangle, which as you can see is clipped to the stencil contents. You need to write your own shader to deal with the alpha channel since OpenGL ES 2.0 does not support the glAplhaTest and related functions.

Note - perhaps this isn't the best image example. In fact the presented solution allows you to progressively reveal the left and right caps, which I unfortunately didn't demonstrate in the above image.


texts:
I heard that X360 homebrews are not allowed to be started from DVDs; however, they can be downloaded from PC or via live and started.

The question is: it is disabled to access DVD drive at all?

I want to access data tracks, without using any (theoretically prohibited) media APIs for playbacks; also I don't want to run from disk (which is prohibited by Microsoft).


texts:
Here is my camera setting:

With this setting, when I run, game is not center of screen:

Please tell me how to fix this.

thanks :)


texts: Multiplayer synchronization and pathfinding

texts:
I have a point & click type interface on a client, which runs an A* on the server, for path-finding.

The game is controlled like an RTS, but the world is persistent, so players should be able to join/leave at any time, and there will only be 30 or so units at most on the screen.

What is the best way to synchronize the player movements between the server and client, once I've computed the path(s)?

Does the server need to sync the clients on every animation step/frame? or can it just tell the client "go to position X,Y" for each node on the path, and each moving player? Or is it best to just run the animation timers on both client and server, and have it be implicitly synchronized that way?

What would the typical data-exchange be like for path-based movement?

EDIT:

Some of you have been suggesting lockstep, because I said "RTS", but the game isn't an RTS, it just has the same kind of interface. The big difference is I need to be able to have players join and leave the game at any time. Sorry for not being more specific.


texts: How do you test player character locomotion alogorithms?

texts:
Work has been proceeding to improve the locomotive behavior of kinematic characters under player control. The problem is usually more involved than inverse kinematics with joint constraints etc. Here are few recent machine learning solutions:

2018 Mode-Adaptive Neural Networks for Quadruped Motion Control
2020 Character Controllers using Motion VAEs
2020 ALLSTEPS: Curriculum-driven Learning of Stepping Stone Skills

Q: What kind of specifications are published that define character locomotion in a given problem space (1) and when is something considered a reference implementation to test against(2)?
See reference implementation for a definition. For example, can ALLSTEPS be considered as a reference for the stepping stone skills? Requirements for GSC-IS Reference Implementations (2003) states that for each level of functionality, a reference implementation should be developed, which is an implementation of the specification to be used as a definitive interpretation. So, running and walking on uneven terrain can be described as the stepping stone problem, which I think is generic for kinematic models with legs. Unwanted behavior is typically defined in the reward weights on the ML model, but I think there is a clear consensus about foot-sliding and temporal incoherence from the motion capture research. See the 2018 paper above and for example Modeling human running on a soccer field and Locomotion-system with irregular IK.
ps: Which non-human figures with joints are popular in demonstrations for player control? You probably know the models in this list which are used to test a given implementation against a, in fluid simulation, ray-casting, 3d printing etc. But demonstrating a stepping stone solution with the Stanford bunny is not ideal.


texts:
In the documentation of MeshUtility.SetPerTriangleUV2 it is said the following:

Will insert per-triangle uv2 in mesh and handle vertex splitting etc.

What do they mean by 'vertex splitting' ?


texts: Drawing/adding shape objects with the mouse on html canvas

texts:
I've started with the canvas paint tutorial from link which worked fine with a few problems that can be fixed later. I've been checking a lot of posts on drawing shapes on the canvas but they all use draw functions in a gameloop or intervals but I do not want to use draw(); in an interval or gameloop for now, I just need to update the content on userinput.

I am trying to create a drawing software that paints objects instead of just bitmaps. I've been debugging for a while now and can't find the problem: I have problems accessing the objects in the pointsArr[]; array. I was only able to add rectangles to the screen by using contextVar.strokeRect(50,50,50,50); directly with the mouseDownVarso far.

Yes I know that the addFilledCircleFunc creats rectangles, for now I just want everything to work properly.

// to do:
// add gameloop and draw with gameloop?
// stroke line in resize  fix
// collission check + detection objects
// functions to draw detection objects
// implement resize?

// Varibale declration
var canvasVar = document.getElementById('canvasHtmlElement');
var contextVar = canvasVar.getContext('2d');
var pointRadiusVar = 10;
var mouseButtonHeld = false;
var pointsArrPosition = 0;

//Arrays
var pointsArr = [];

// Varibale declration end

//canvas setup
canvasVar.width = window.innerWidth;
canvasVar.height = window.innerHeight;

//canvas setup end

//resize fix
window.onresize = function(){
    var tempImageVar = contextVar.getImageData(0,0, canvasVar.width, canvasVar.height);
    canvasVar.width = window.innerWidth;
    canvasVar.height = window.innerHeight;
    contextVar.putImageData(tempImageVar, 0,0);
}
//resize fix end

contextVar.lineWidth = pointRadiusVar * 2; // Line Width

//functions

// Objects

 function pointObject () {
 this.x = 0;
 this.y = 0;
 this.w = 10; // default width and height?
 this.h = 10;
 this.fill = '#444444';
 this.stroke=stroke||"skyblue";
 this.strokewidth=strokewidth||2;
 }

function addFilledCircleFunc(x, y, w, h, fill){
var filledCircle = new pointObject;
    filledCircle.x = x;
    filledCircle.y = y;
    filledCircle.w = w;
    filledCircle.h = h;
    filledCircle.fill = fill;
    pointsArr.push(filledCircle);
}

//Objects end

// create circle on mouse clicked point while mousebutton is held
var addPointToCanvasVar = function (e) {
    if(mouseButtonHeld){
        addFilledCircleFunc(e.clientX, e.clientY, 10, 10, '#444444');

        /* // old drawing code
         contextVar.lineTo(e.clientX, e.clientY);
         contextVar.stroke();
         contextVar.beginPath();
         contextVar.arc(e.clientX, e.clientY, pointRadiusVar, 0, Math.PI * 2);
         contextVar.fill();
         contextVar.beginPath();
         contextVar.moveTo(e.clientX, e.clientY);
         */
    }
};

// MAKE SURE that lines work when drawn over the edge of the canvas
/*
 function clearPathIfMouseCursorLeavesCanvasFunc(e){
 //contextVar.beginPath(); // clears the path so buttonpresses dont connect the line
 //mouseButtonHeld = false;
 }
 */
// end

// mouse Up/Down Switch
var mouseDownVar = function(e){
    alert("mouseDown");
    //contextVar.strokeRect(e.clientX, e.clientY,50,50);
    draw();
    mouseButtonHeld = true;
    addPointToCanvasVar(e); // add point on first click, not just when mousebutton is held
}

var mouseUpVar = function(){
    //alert("mouseUp");
    mouseButtonHeld = false;
    contextVar.beginPath(); // clears the path so buttonpresses dont connect the line
}

// mouse Up/Down Switch end

//functions end

//listeners

canvasVar.addEventListener('mousemove', addPointToCanvasVar);
canvasVar.addEventListener('mouseup', mouseUpVar);
canvasVar.addEventListener('mousedown', mouseDownVar);
//canvasVar.addEventListener ('mouseout', clearPathIfMouseCursorLeavesCanvasFunc);

//listeners end

//draw function

function draw(){
    alert('drawing');
    contextVar.strokeRect(pointsArr[pointsArrPosition].x,pointsArr[pointsArrPosition].y,pointsArr[pointsArrPosition].w,pointsArr[pointsArrPosition].h);
    pointsArrPosition++;
}

//draw function end


texts: How can I sort a list of integer pairs in sequence?

texts:
I have a list of paired integers, every nth integer paired with every nth+1 integer. I'm trying to sort the list such that the pairs form a chain. For example:

Input:
{12,72, 38,2, 72,38, 2,12}
Output:
{38,2, 2,12, 12,72, 72,38}

The trick is that the list may contain several unconnected chains. The chains don't need to be in any sequence, just the pairs within each chain. As per the input, each chain should be a loop unless they chain has only one pair, so any pair in the chain should be a valid first pair.

What I've tried is this (C#):

int a = 0;
int b = 0;
int temp;

while (a < list.Count) {
    b = a + 2;
    while (b < list.Count) {
        if (list[b] == list[a + 1]) {
            temp = list[b];
            list.RemoveAt(b);
            list.Insert(a + 2, temp);

            temp = list[b + 1];
            list.RemoveAt(b + 1);
            list.Insert(a + 3, temp);

            a += 2;
            b = a;
        }
        b += 2;
    }
    a += 2;
}

Which is giving me mostly correct results, but is still leaving the list with some disconnected pairs that should be part of a chain.

I'm not great with sorting algorithms and this has proven to be a difficult problem to google, so I'm hoping someone can point out the flaw in my code or point me in the right direction for research.


texts: How can I normalize a vector if I am handling movment of each axis seperatley?

texts:
I am writing a 2D tile based game engine in XNA, and I've recently fine-tuned my collision detection using the answers provided here and more specifically here.

The tile based collision detection now works flawlessly and fixed all the small problems I had with my previous code. However, implementing this forced me to rewrite how movement was handled. Instead of moving the player all at once and then resolving each collision along the smallest axis of intersection depth, it now updates and resolves on the X and Y axes separately.

This is fine, but now my diagonal movement is much faster than my horizontal and vertical movement and I am unsure of how to normalize it.

I'm sure I'm just overlooking something simple, is there a straight forward way of doing this?

    public void HandleInput()
    {
        //Set horizontal and vertical values accordingly based on direction of key presses
        int horizontal = InputHelper.IsKeyDown(Keys.A) ? -1 : (InputHelper.IsKeyDown(Keys.D) ? 1 : 0);
        int vertical = InputHelper.IsKeyDown(Keys.W) ? -1 : (InputHelper.IsKeyDown(Keys.S) ? 1 : 0);

        //If there is movement update sprite position, round the position to nearest pixel and then check for collision
        if (vertical != 0)
        {
            sprite.Position += Vector2.UnitY * sprite.Speed * vertical;
            sprite.Position = new Vector2(sprite.Position.X, (float)Math.Round(sprite.Position.Y));
            HandleCollisions(Direction.Vertical);
            UpdateSpriteAnimation(Direction.Vertical, vertical);
        }
        if (horizontal != 0)
        {
            sprite.Position += Vector2.UnitX * sprite.Speed * horizontal;
            sprite.Position = new Vector2((float)Math.Round(sprite.Position.X), sprite.Position.Y);
            HandleCollisions(Direction.Horizontal);
            UpdateSpriteAnimation(Direction.Horizontal, horizontal);
        }
    }

    private void HandleCollisions(Direction direction)
    {
        // Get the player's bounding rectangle and find neighboring tiles.
        Rectangle playerBounds = sprite.spriteBounds;
        int leftTile = playerBounds.Left / Engine.TileSize;
        int topTile = playerBounds.Top / Engine.TileSize;
        int rightTile = (int)Math.Ceiling((float)playerBounds.Right / Engine.TileSize) - 1;
        int bottomTile = (int)Math.Ceiling(((float)playerBounds.Bottom / Engine.TileSize)) - 1;

        // For each potentially colliding tile,
        for (int y = topTile; y <= bottomTile; ++y)
        {
            for (int x = leftTile; x <= rightTile; ++x)
            {
                Vector2 depth;
                //If this tile is collidable, and it intersects sprite bounds
                if (tileMap.CollisionLayer.GetCellIndex(x, y) == 0 && TileIntersectsPlayer(playerBounds, GetTileBounds(y, x), direction, out depth))
                {
                    //Resolve the collision along the given axis
                    sprite.Position += depth;

                    // Perform further collisions with the new bounds.
                    playerBounds = sprite.spriteBounds;
                }
            }
        }
    }


texts: Process of getting DEJUS rating (Brazil)?

texts:
I would like to get DEJUS rating for my HTML5 game on the Firefox
Marketplace, so that I can tell Mozilla to make the game available
to users in Brazil. I want the game to be rated as: Livre (general)

Can non-Brazilian citizens request ratings from DEJUS? If so, what documents need to be provided, and in which language?

What I have found so far:

Submission form in English (note that there is no country field
in the address form, and it's necessary to specify CPF/CNPJ)
Description of procedure in Portuguese.
Process flow chart in Portuguese.
Practical guide to rating system in English.


texts:
one Thing I found out: Windows 7 produces a memory leak while using certain methods to access rendertargets. Why doesn't Windows 8 leak at this method?

public class Game : SharpDX.Toolkit.Game {
    GraphicsDeviceManager gdm;
    RenderTarget2D target;
    public Game() {
        gdm = new GraphicsDeviceManager(this);
    }
    protected override void LoadContent() {
        target = RenderTarget2D.New(GraphicsDevice, 1000, 1000, PixelFormat.R8G8B8A8.UNorm);
        base.LoadContent();
    }
    private Color GetColor(int x, int y) {
        using (Image image = target.GetDataAsImage()) {
            PixelBuffer buffer = image.PixelBuffer[0];
            Color color = buffer.GetPixel<Color>(x, y);
            buffer = null;
            return color;
        }
    }
    protected override void Update(GameTime gameTime) {
        GetColor(5, 5);
        base.Update(gameTime);
    }
}

The memory consumption with this on Windows 8 is around 25 MB, Windows 7 uses up full memory.
Any idea why Windows 8 handles memory/graphics in another way than Windows 7 (and how to fix it)?
For clarification if it was a memory leak:

The drop is caused by closing the application.


texts: Box2D object wont move until tons of force is used

texts:
Im making a game for android im using LibGDX and Jbox2D it is a space flying exploration game controlled with the accelerometer. so I have set the world to no have no gravity. the objects in Box2D don't like having forces applied to them apparently. Just to get an object moving more then a few pixels at a time I need to use over 10,000 in applyForceToCenter()

in the Game class I get the accelerometer in the update method and create a direction vector from the input and pass that to the player

    accelX = Gdx.input.getAccelerometerX();//get the various tilts
    accelY = Gdx.input.getAccelerometerY();
    accelZ = Gdx.input.getAccelerometerZ();

    //These are backwards because the game is in landscape and not portrait
    p1Direction.x = (accelY/10); //getAccelerometer comes back -10 to 10
    p1Direction.y = -(accelX/10); //reduce this to -1 to 1;

    p1.setDirection(p1Move);
    p1.update(Gdx.graphics.getDeltaTime());

Then In the player I apply a force to the object based on the direction:

    acceleration.x += (directionVector.x * SPEED)*deltaTime; //speed is set to 200
    acceleration.y += (directionVector.y * SPEED)*deltaTime;

    this.getBody().applyForceToCenter(acceleratiom, true);

to try and get it moving I had to add:

    acceleration.x += (directionVector.x * SPEED)*deltaTime*1000; //speed is set to 200
    acceleration.y += (directionVector.y * SPEED)*deltaTime*1000;

    this.getBody().applyForceToCenter(acceleratiom, true);

now it moves a little better, but once it gets moving it won't stop

Is there a way to fix this?

Update: The Mass, Friction, density, and restitution are all 1 right now here's the camera:

    camera = new OrthographicCamera(screenWidth,screenHeight);
    camera.setToOrtho(false,screenWidth,screenHeight);
    camera.position.set(0, 0, 0);

and the player is rendered with

batch.draw(playerTexture, this.getBody().getPosition().x, this.getBody().getPosition().y,
    (playerTexture.getWidth()/2), (playerTexture.getHeight()/2),
    playerTexture.getWidth(), playerTexture.getHeight(),
    1.0f, 1.0f, this.getBody().getAngle(), 0, 0,
    playerTexture.getWidth(),  playerTexture.getHeight(),
false, false);
//Texture position half width(so the texture rotates in the center), width and height of the texture, scale of 1, rotate by the angle (doesn't rotate right now) source position source width and height


texts: Why is the pixel so popular as the metric unit of a game?

texts:
I keep seeing everywhere people using pixels for resolving collisions, angles, distances. I wonder if using the pixel as the metric unit for a game is a good solution, first because you're tying your game logic with implementation, in this case squares in your monitor, second handling more elaborated effects like zoom, rotation becomes more difficult, etc. Isn't adopting integer numbers as your smallest metric unit more flexible and letting the renderer do the pixel operations?

Why the pixel unit is so much popular than integer units?
Which are the benefits and drawbacks for each strategy?


texts: MissingComponentException when using Animator

texts:
I followed some tutorials to add WASD movement to a character; I managed to set up the animator thing and it works in the bottom right corner viewport.

Next I tried adding the following C# script with basic movements:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class AppleInput : MonoBehaviour
{
    private Animator animator;
    // Start is called before the first frame update
    void Start()
    {
        animator = GetComponent<Animator>();
    }

    // Update is called once per frame
    void Update()
    {
        animator.SetFloat("Horizontal", Input.GetAxis("Horizontal"));
        animator.SetFloat("Vertical", Input.GetAxis("Vertical"));
    }
}

Configured like so:

But then I get the error message:

MissingComponentException: There is no 'Animator' attached to the "action10Prob_normalsDONEyet" game object, but a script is trying to access it.
You probably need to add a Animator to the game object "action10Prob_normalsDONEyet". Or your script needs to check if the component is attached before using it.

How do I solve this error?


texts: Unity importing Blender models with different orientations

texts: All the models apart from 'Jungle Tree' are facing right which is not a problem, because they still seem to work with my game. But how can I change the 'Jungle Tree' to face right like the other models instead of left? I haven't made the Jungle Tree drastically different to the other models so I don't see why it is doing this


texts: Changing the rendering resolution while maintaining the design layout

texts:
I would like to increase the FPS of my project.

Currently I would like to try reducing the resolution at which the scenes are rendered.

Let's say I never want to draw more than 1280*720. What ever the real resolution is. How should I proceed?

I tried pEGLView->setFrameSize(1280, 720); but only reduces the displayed size of the frame on screen (boxing).

In my activity I tried setting the size of the "surface" but this seems to completely break the layout (as defined by setDesignResolutionSize).

@Override
public Cocos2dxGLSurfaceView onCreateView() {
    Cocos2dxGLSurfaceView surfaceView = new Cocos2dxGLSurfaceView(this);
    surfaceView.getHolder().setFixedSize(1280, 720);
    return surfaceView;
}

Is there a way to simply set the scene resolution and display the result full screen?


texts: Why does the Texture placement of my CCSprite slightly shift when changing it's location?

texts:
So I've been seeing this issue for a while now. When using a delta method to change the location of a CCSprite, the placement of texture of my sprite slightly moves into the direction where I'm headed, while the physicsbody stays the same. This is really noticeable, since I'm using CCActionFollow to center this sprite in the view at all times. The code is displayed below. Is this normal behaviour, or am I perhaps overlooking something really obvious? Thanks!

- (void) move:(CCTime)delta toPosition:(CGPoint)point
{
OverworldScene * parentScene = (OverworldScene *)self.parent.parent.parent; //Go over physics node
OverworldLayer * parentLayer = (OverworldLayer *)self.parent.parent; //Go over physics node

//meewind of tegenwind?
float angleWind = parentScene.compass.rotation;
float angleShip = self.rotation;
float difference;
float windFactor;

if (angleWind > angleShip)
{difference = angleWind - angleShip;}
else{difference = angleShip - angleWind;}

if (difference > 180)
{difference = 360 - difference;}

//Incorporate wind power...
if (difference > 90)
{   //Tegenwind
    windFactor = 1-((((90- (180 - difference))/90))*(parentLayer.windPower/12));
}
else
{   //Meewind
    windFactor = 1+((((90-difference)/90))*(parentLayer.windPower/12));
}

if (windFactor < 0.4){windFactor = 0.4;}

//point is the current position of the user's sprite
//a, b and c are the right triangle sides lengths formed by the caser sprite and the user's sprite positions
float a = ABS(self.position.y - point.y);
float b = ABS(self.position.x - point.x);
float c = sqrt(pow(a, 2) + pow(b, 2));

//angle of the hypotenuse
float beta_rad = asin(b/c);

//velocity in pixels per second (used to be 60)
c = 60 * self.velocityFactor * windFactor;    //Now accounts for windfactor!
parentScene.speedLabel.string = [NSString stringWithFormat:@"Speed %.1f knots", self.velocityFactor * (60*windFactor)/8];

//x-axis velocity component
float x = c * sin(beta_rad);
//y-axis velocity component
float y = c * cos(beta_rad);

//adjustments based on position of the this (chaser) sprite and the user's sprite, if chaser is on the right or below the user's sprite it is needed to reverse the velocity vector component x and y
if (self.position.x > point.x) x *= -1;
if (self.position.y > point.y) y *= -1;

//final velocity vector
CGPoint velocityVector = CGPointMake(x, y);
CGPoint newPosition = ccpAdd(self.position, ccpMult(velocityVector, delta));

//NSLog(@"Updating position: %@", NSStringFromCGPoint(newPosition));

//Only update in case new position is in bounds
if (newPosition.x < 0 || newPosition.x > parentLayer.contentSize.width)
{
    newPosition = CGPointMake(self.position.x, newPosition.y);
}

if (newPosition.y < 0 || newPosition.y > parentLayer.contentSize.height)
{
    newPosition = CGPointMake(newPosition.x, self.position.y);
}

self.position = newPosition;

}


texts: How do I get the alpha level at a specific pixel with Slick 2D?

texts: I know that there is the Texture.getTextureData() method, and that it returns a byte[], but I have no idea how I could use this data to find the color data at a specific pixel.


texts: Good practices when optimizing HTML5/Javascript Game Developement

texts:
I'm just starting out as a game developer and have created a few crappy but playable clones of classic games like pong, and bomberman.
Being self taught (bless the internet) I do this by just stuffing in code to make the games work.

Now I feel the time has come to create something complete, for this I need to know how a game is structured. I've searched on the web but there isn't that much to be found. The only "high-level" language I know is javascript so reading a tutorial or article based on C++ doesn't help me that much.

I'm looking for good resource's pedagogically covering the theory and possibly examples (in Javascript or pseudo code that is understandable for a beginner) of how the game pieces fit together.

From the start screen to asset loading and running the game loop. I'm not looking for anything complicated like reading through a 4000 line source code.
All I want to learn is where, how and when the main parts of every game should be called.

If you know any good resources to share, or maybe even have an answer for me I would deeply appreciate it.


texts: Unity 4.5 Sprite Packer does not pack images inside Resources folder

texts:
I'm trying to use the new Sprite Packer tool, but it doesn't work if I put the imagens inside Resouces folder, but inside any other folder it works.

is it a bug?


texts: Do you think it's Possible to go from C++ Straight to 3D (skipping 2D)

texts:
Do you think it's possible to go straight from Experienced C++ programming (5 or so years) straight into learning DirectX 3d?

I mean....i'd be starting with the basics, im more interested in setting up Demos (like getting a good water demo and such) than actually doing a full fledged game.

Do you think this is possible?


texts: Why does 'SpriteRenderer.drawMode' virtually change from Tiled to Simple when 'SpriteRenderer.size' exceeds some value?

texts:
Given:

texture size = 225x225

2D sprite object;
SpriteRenderer.drawMode = SpriteDrawMode.Tiled;

Now if SpriteRenderer.size is changed to 286x286 the sprite is rendered as if its drawMode were Simple (no tiling):

If SpriteRenderer.size is reduced to 285x285 it is rendered again as expected (tiled):

Specific SpriteRenderer.size values after which it stops rendering in the Tiled mode depend on the texture size, so if you try it with a different texture the SpriteRenderer.size limit will be different from 286x286 as well.

Why it happens?
I can only guess that there some technical limitations related to the texture size that I am not aware of.


texts: Why does the debug say my assigned field "is never assigned to, and will always have its default value 'null'"?

texts:
I have an itemData class that stores the data for a couple of items. It looks something like this:

public class ItemData : MonoBehaviour
{
    public List<Item> items;

    [SerializeField] private Sprite itemOneSprite, itemTwoSprite, itemThreeSprite;

    void Awake()
    {
        items = new List<Item>();

        Item itemOne = new Item(0, "Item 1", itemOneSprite);
        items.Add(itemOne);

        Item itemTwo = new Item(1, "Item 2", itemTwoSprite);
        items.Add(itemTwo);

        Item itemThree = new Item(2, "Item 3", itemThreeSprite);
        items.Add(itemThree);
    }
}

I get an error message for itemTwoSprite and itemThreeSprite, stating that they are null and will always be null:

  Field name of field is never assigned to, and will always have its default value 'null'

Oddly, when I check the inspector, those fields are not null. I have manually attached sprites to them. When I debug, I see that they are not null. I get something like "itemTwoSprite(UnityEngine.Sprite)". I can run the game, and things seem to work normally.

The order of the declared Sprite variables seems to be important, as well. For instance, if my line of code looked like Sprite itemTwoSprite, itemOneSprite, itemThreeSprite, then itemOneSprite and itemThreeSprite would bring up error messages. The first one declared seems to be unproblematic.

What could be causing the issue, and how do I fix it? I have isolated the problem into an empty project, and it still persists. The only other script is the item class. To reiterate, the error message does not prevent the game from running, but it pops up in the console from time to time, with the yellow exclamation mark.


texts: MMORPG game map in-memory storage techniques

texts:
For 2-3 years I've been interested into MMO development.
I'm browsing some emulators source codes and open source projects.

Usually I'm checking how the game server stores data about the 2D map.
There are 2 popular solutions:

map is stored only on the server it's sent to the client in parts (eq. tiles like in OpenTibia https://github.com/opentibia/server)
map is stored in the client and on the server, server sends only coordinates and client got knowedgle of it.

I'm generally interested in this first attitude, do you know any good and bad aspects of it?

How to store this structure on the server? In memory on in database? Open Tibia uses memory storage but there is one drawback: 2000x2000x16 map uses a lot of memory - something around 2GB. Is this because of bad design? Are you able to provide me some examples of good design?


texts:
I am looking into creating a fantasy soccer league, where users can create their own virtual team of real-life soccer players. The performance the virtual team depends on how those soccer players perform in real life.

There are data providers (eg: http://www.xmlteam.com, https://fantasydata.com) targeted at fantasy leagues, their licenses are for using their data, which includes those real names, but it's obviously not the license one would need for using real names in a game. There are some articles online that state that fantasy leagues do not need licensing for showing real names and data, because it's considered the same as showing public information, similar to how the news or papers would report about sports games. Some fantasy leagues have been in court over this and succesfully defended themselves, thus not needing a license. I also contacted 2 of the biggest fantasy soccer leagues in my country, if they could inform me about how and where to obtain such a license. One didn't respond (yet), the other one replied that they have someone present at every soccer game to gather the data, so that they don't need a license to get this data from someone else - they weren't aware of other licenses regarding the usage of real names.

I also contacted the organizer of the professional soccer competition (Pro League) in my country (Belgium), on their website they advertise their licensing deal with EA, but they haven't replied (yet).

I am aware that this should be discussed with a lawyer, but for me it's more about having a reusable fantasy sports game (without the actual sports data) than having a lot of users in a functional game. In other words, if it would be OK to develop and test this game in a closed environment (on the internet, without public registration, let's call it "friends-only"), that would be sufficient for me for now.

Does this type of game need a license? At what point does or doesn't it need a license? Can I test my game online with 16 participants (registrations closed, so not open to the public) without needing a license (yet)?


texts: Coding different states in Adventure Games

texts:
I'm planning out an adventure game, and can't figure out what's the right way to implement the behaviour of a level depending on state of story progression.

My single-player game features a huge world where the player has to interact with people in a town at various points in the game. However, depending on story progression, different things would be presented to the player, for e.g. the Guild Leader will change locations from the town square to various locations around the city; Doors would only unlock at certain times of the day after finishing a particular routine; Different cut-screen/trigger events happen only after a particular milestone has been reached.

I naively thought of using a switch{} statement initially to decide what the NPC should say or which he could be found at, and making quest objectives interact-able only after checking a global game_state variable's condition. But I realised I would quickly run into a lot of different game states and switch-cases in order to change the behaviour of an object. That switch statement would also be massively hard to debug, and I guess it might also be hard to use in a level editor.

So I thought, instead of having a single object with multiple states, maybe I should have multiple instances of the same object, with a single state. That way, if I use something like a level editor, I can put an instance of the NPC at all the different locations he could ever appear at, and also an instance for each conversation state he has. But that means there'll be a lot of inactive, invisible game objects floating around the level, which might be trouble for memory, or simply hard to see in a level editor, i don't know.

Or simply, make an identical, but separate level for each game state. This feels the cleanest and bug-free way to do things, but it feels like massive manual work making sure each version of the level is really identical to each other.

All my methods feel so inefficient, so to recap my question, is there a better or standardised way to implement behaviour of a level depending on state of story progression?

PS: I don't have a level editor yet - thinking of using something like JME SDK or making my own.


texts:
My question is what is written in title. This term "vertex color" appear a lot. I am having hard time to understand this.

For example:

Isn't a vertex simple point on 3D space? If so, how can a point have a color? Or does this "color" mean something else?

There is a "Vertex Color" node in unreal engine's material editor.

Can someone shed light on my question? I couldn't find anything usefull when I googled "what is a vertex color" but the documentations that are too technical for me.


texts: Set an scaled image rectangle coordinates

texts:
I have used the Origin parameter to draw the image (the image is also scaled) in center of the screen, and created a rectangle to detect whether user tapped on that image.
The problem is that if I tap on left part of the image it doesn't happen anything but at the right part, it executes what it has to.

How can i fix this? I have tried something but any result...

ItemRectangle[ItemID] = new Rectangle((int)Position.X + (int)(Position.X * Scales), (int)Position.Y + (int)(Position.Y * Scales), ItemTexture[ItemID].Width, ItemTexture[ItemID].Height);

spriteBatch.Draw(ItemTexture[i], ItemPosition[i], null, Color.White, 0, new Vector2(ItemTexture[i].Width / 2, ItemTexture[i].Height / 2), Scale, SpriteEffects.None, 0);


texts: Get distance between two objects from an ortographic point of view

texts:
I want to be able to measure the distance from one object to another through the camera's orthographic projection.

As shown here, the objects are away from each other

When I move the camera, they "appear" to be closer together:

I want to be able to measure that blue line. How can I make this possible?


texts: class diagrams / design for an adventure game (rooms, objects, inventory)?

texts:
Any links to existing design (e.g. class diagrams, database ER diagrams) for a basic adventure game - i.e. that has the aspects of:

rooms/locations (which you move between)
objects which you collect / use (which may have behaviours)
inventory (i.e. items which you carry)
rules (e.g. if you to want to open Door X, then you need Key Y)


texts: Why is there almost never online multiplayer in indie games?

texts: There are alot of which are local but very few who have online.


texts:
I have this code below that I found on catlikecoding that generates a procedural grid that I want to apply noise to, however once I go over a certain value it does expand vertically. Can anyone see why it wouldn't?

For example, 100x100:

However, 500x500 is clearly wrong:

Code used:

using UnityEngine;

[RequireComponent(typeof(MeshFilter), typeof(MeshRenderer))]
public class Island : MonoBehaviour {

public int xSize, ySize;

    private Mesh mesh;
    private Vector3[] vertices;

    private void Awake () {
        Generate();
    }

    private void Generate () {
        GetComponent<MeshFilter>().mesh = mesh = new Mesh();
        mesh.name = "Procedural Island";

        vertices = new Vector3[(xSize + 1) * (ySize + 1)];
        Vector2[] uv = new Vector2[vertices.Length];

        for (int i = 0, y = 0; y <= ySize; y++) {
            for (int x = 0; x <= xSize; x++, i++) {
                vertices[i] = new Vector3(x, y);
                uv[i] = new Vector2((float)x / xSize, (float)y / ySize);
            }
        }

        mesh.vertices = vertices;
        mesh.uv = uv;

        int[] triangles = new int[xSize * ySize * 6];
        for (int ti = 0, vi = 0, y = 0; y < ySize; y++, vi++) {
            for (int x = 0; x < xSize; x++, ti += 6, vi++) {
                triangles[ti] = vi;
                triangles[ti + 3] = triangles[ti + 2] = vi + 1;
                triangles[ti + 4] = triangles[ti + 1] = vi + xSize + 1;
                triangles[ti + 5] = vi + xSize + 2;
            }
        }

        mesh.triangles = triangles;
        mesh.RecalculateNormals();
    }
}


texts: What's the most efficient way to deal with in-game messages in Allegro 5?

texts:
I have a little 2D game made with Allegro, and I want to introduce strings during gameplay. For example, I've just made it so a key is needed to open a door, so I'd need some tutorial text to appear when the player collides with the door that tells them they need the key first.
This is just a learning experience for me, really - the key is pretty visible but I would like to learn how to handle this sort of messages especially for tutorial purposes in a bigger, better game.

Right now, during gameplay, I have running game_loop() (which handles player movement, collisions etc) and game_render(), which obviously runs after it. To introduce these messages, what I have successfully done so far is to add a global std::vector<const char*> to which I push_back messages whenever appropriate.

My message_renderer() then goes like so:

static double t = 0, c = 0;

    if (!messages.empty())
    {

    for (unsigned int i = 0; i < messages.size(); i++)
    {

        al_draw_text(font18, al_map_rgb_f(255, 255, 255), wWidth / 2, wHeight - 50, ALLEGRO_ALIGN_CENTRE, messages[i]);
        if (t < 2)
         {
           t += get_dt();
           c += get_dt();
            if (c > 1)
                  c = 1;
          }
        else
        {
        t = 0;
        c = 0;
        messages.pop_back();
        }

    }
    }

I then call this message_renderer() in my game_render() after I've drawn everything else, to ensure that the message appears on top.

Now, again, this does work - the message displays for 2 seconds at render time once it's added to the vector. However, this solution doesn't really seem particularly neat to me, since as far as I know there are standardised ways of dealing with these sort of events - I just don't know what they are!

So my question is - is my current method efficient enough? Can it be improved, in Allegro (or generally, in logic!) and if so, how?

Thank you in advance!

EDIT: I've modified the code since posting the question, so it should now behave like expected - showing a message for 3 seconds. It does so, but when I have two strings in the vector at the same time they overlap - I thought the timer would work as "pause" between each iteration but I guess not... If someone could point me in the right direction for that too, it'd be much appreciated :)


texts: OpenGL Applications Bring computer to halt

texts:
Whenever I run any application that utilizes the OpenGL interface, my entire computer comes to a halt, but it doesn't do this when it utilizes the DirectX interface. I run both Linux (Ubuntu 15.10) and Windows 10 so this isn't exactly caused by the operating system. I'm running the latest drivers from NVidia and both OS's are completely up to date. This is happening on a Dell Precision M6300 laptop (Core 2 Dou 2.5ghz, NVidia Quadro FX 1600M, 4gb ram) and although it's a bit old it should be completely capable of rendering a blank OpenGL window using GLFW, however it slows down my entire computer (every application starts freezing to where it becomes unusable until the application is closed). This happens in games like Left4Dead, Half-life 2, etc., but also in my own OpenGL programs. The same programs and games do not have the same effect on my desktop (although much better hardware, a blank OpenGL window shouldn't matter). Any help would be greatly appreciated, thank you. Also; my apologies if I left out any vital information or made a confusing question. Just ask me to clarify or add something and I shall.

; Added the code for the blank OpenGL window in question

#include <stdio.h>
#include <stdlib.h>
#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include <glm/glm.hpp>
using namespace glm;

int main(int argc, char* argv[]) {
if ( !glfwInit() ) {
    fprintf(stderr, "Failed to initialize GLFW\n");
    return -1;
}

glfwWindowHint(GLFW_SAMPLES, 4); // 4x AA
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); // GL 3.3
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);

GLFWwindow* window;
window = glfwCreateWindow(1024, 768, "OpenGL Tutorial", NULL, NULL);
if (window == NULL) {
    fprintf(stderr, "Failed to create OpenGL Window.");
    return -1;
}
glfwMakeContextCurrent(window);
glewExperimental=true;
if (glewInit() != GLEW_OK) {
    fprintf(stderr, "Failed to initiate the glew context!");
    return -1;
}

glfwSetInputMode(window, GLFW_STICKY_KEYS, GL_TRUE);

do {

    glfwSwapBuffers(window);
    glfwPollEvents();
} while (glfwGetKey(window, GLFW_KEY_ESCAPE ) != GLFW_PRESS &&
    glfwWindowShouldClose(window) == 0);
}


texts: Running and Jumping using Box2d and libgdx

texts:
.this is my first trial on making a 2d game and currently struglling how to run and jump smoothly. My problem is when the player keep pressing on left or right botton then jump. the player won't jump, also when keep on holding left or right. the speed gets faster

if (KeyInput.isPressed(KeyInput.Button.JUMP)) {
    body.applyForceToCenter(0, playerJumpForce, true);
}

if (KeyInput.isDown(KeyInput.Button.LEFT)) {
    body.setLinearVelocity(new Vector2((body.getLinearVelocity().x - (playerSpeed * delta)), 0));
}

if (KeyInput.isDown(KeyInput.Button.RIGHT)) {
    body.setLinearVelocity(new Vector2((body.getLinearVelocity().x + (playerSpeed * delta)), 0));
}


texts:
I implemented planar shadows with the function D3DXMatrixShadow.

As you know, we need plane and light factor to calculate a shadow matrix.

The problem is that when I set the plane as D3DXPLANE p(0, -1, 0, 0.1f), the shadows by directional light are correctly rendered, but the shadows by point light are not rendered.

However, if I use D3DXPLANE p(0, 1, 0, 0.1f), the situation is reversed, shadows by directional light are not drawn, the shadows by point light are ok.

I cannot understand why it happens. Is it normal or am i missing something? Please explain to me why this happens.

Thanks in advance.

Code

//main.cpp
ID3D10EffectTechnique* oldTech = meshes[i]->technique;

D3DXPLANE groundPlane(0, -1, 0, 0.01f);
D3DXMATRIX S;//shadow matrix
D3DXVECTOR4 light;
if(lightType != 2) //2 here means point light
{
    light.x = lightDirection.x;
    light.y = lightDirection.y;
    light.z = lightDirection.z;
    light.w = 0;
}
else
{
    light.x = lightPosition.x;
    light.y = lightPosition.y;
    light.z = lightPosition.z;
    light.w = 1;
    groundPlane.b = 1;
}

D3DXMatrixShadow(&S, &light, &groundPlane);
D3DXMATRIX W = meshes[i]->GetWorldMatrix();
D3DXMATRIX matWorld = W * S;

meshes[i]->technique = shadowTechnique;
meshes[i]->render(&matWorld);
//Meshes here are drawn by ID3DX10Mesh,
//but I tested other code with LPD3DXMESH, it has the same problem.

meshes[i]->technique = oldTech;

 //shader code(.fx file)
 PS_Input VS_Shadow(VS_Input input)
 {
    PS_Input output = (PS_Input)0;
    output.pos = mul(float4(input.pos, 1), matWorld);
    output.pos.y = 0.1;
    output.pos = mul(mul(output.pos, matView), matProjection);
    output.normal = mul( input.normal, (float3x3)matWorld );
    output.color = input.color;
    output.worldPos = (float3)mul(input.pos, matWorld);
    output.tex = input.tex;
    return output;
 }

 float4 PS_Shadow( PS_Input input) : SV_Target
 {
    return float4(0,0,0,0.5f);
 }

 DepthStencilState StencilIncreaseOnce {
    DepthEnable = true;
    DepthWriteMask = ALL;
    DepthFunc = LESS_EQUAL;

    StencilEnable = true;
    FrontFaceStencilFunc = EQUAL;
        FrontFaceStencilPass = INCR;
    FrontFaceStencilFail = Keep;
 };

 BlendState BlendAlpha {
    AlphaToCoverageEnable = FALSE;
    BlendEnable[0] = TRUE;
    SrcBlend = SRC_ALPHA ;
    DestBlend = INV_SRC_ALPHA ;
    BlendOp = ADD;
    SrcBlendAlpha = ONE;
    DestBlendAlpha = ZERO;
    BlendOpAlpha = ADD;
    RenderTargetWriteMask[0] = 0x0F;
 };

 technique10 ShadowRender
 {
    pass P0
    {
        SetVertexShader( CompileShader( vs_4_0, VS_Shadow() ) );
        //SetVertexShader( CompileShader( vs_4_0, VS() ) );
        SetGeometryShader( NULL );
        SetPixelShader( CompileShader( ps_4_0, PS_Shadow() ) );

        SetDepthStencilState( StencilIncreaseOnce, 0x0 );
        SetBlendState( BlendAlpha, float4( 0.0f, 0.0f, 0.0f, 0.0f ),
                   0xFFFFFFFF ); //blendState, blendFactor, sampleMask
    }
 }


texts: How do games like Minecraft generate entire worlds from a seed number?

texts: I want to generate a completely unique world with biomes (like what Minecraft and similar games do). I don't understand how they generate these entire worlds from a single "seed" number. Can someone provide a basic overview of the technique?


texts: Fill a non rectangular grid with rectangles

texts:
I'm developing a city builder with a zoning system similar to Cities: Skylines.
What I would need is an algorithm that would find all the way to fill this grid (in red) but with some constraints:
In this case, one way to fill it would be to have a building on the left (size 4x3) and one building one the right (size 3x4).
But to have some variety, I don't want to always minimize the number of buildings, so in this case I would like also to allow 2 buildings of 2x3 on the left + 1 building of 3x4 on the right.
Someone pointed me toward the Dancing Links algorithm to solve this.


texts: How to take collision from only a gameobject and discard others?

texts:
My player in unity2D has a system to check whether it has collided with any harming substances such as fire, villains etc. When it is true that condition, it Re-Spawns to a certain position. It also decreases the amount of life that the player has. for eg:- At start my player has 15 such lives and each time any harming object as I have mentioned before, collides with my player, it decreases to 14 and so on.

But, In certain places I have fire along the way which is made up of many object as the image shows :-

And, when the player collides with this fire, it decreases the lives 4-5 more because it has collided with more than one object. So, how can I make such that my player's life will only be deducted by 1 in this condition?


texts: I want to add some nice atmospheric scattering to my 3D game engine but I am very concerned with conserving resources. I am not very familiar with how its done but can someone please give me some suggestions how to achieve this effect without using too many resources? For example, should I use precomputed or real time atmospheric scattering. Also is the effect worth it without HDR or is it practically needed.


texts: How can I map regions on a world map image?

texts: I am trying to use a map of the real world, but I need to have a way to break it down by countries and regions.  Ideally down to a province level.  I figure that I'd need to be able to define polygonal regions on the image and export the points that represent the bounding polygon, so that I could check for clicks inside, and do other things with it.  I'm having a hard time finding a tool that will let me do this, that is, load in an arbitrary image and start defining polygons on it to be exported.  Or am I going about this the hard way?  Using XNA/Monogame currently if that matters in your answer.  Thanks


texts:
I'm trying to play sounds and music with cocos2d. When I run on iPhone and .caf files the audio is perfect, but on Android it is not playing the background music and is only playing 2 sounds of 10 files. I don't know what I'm doing wrong.

#include <SimpleAudioEngine.h>
bool HelloWorld::init()
{
  const char *sound;

#if CC_TARGET_PLATFORM == CC_PLATFORM_IOS
  sound = "Fun.caf";
#else
 sound = "Fun.wav";
#endif

  auto audio = CocosDenshion::SimpleAudioEngine::getInstance();

  audio->preloadBackgroundMusic(sound);

  audio->playBackgroundMusic(sound, true);

  audio->setBackgroundMusicVolume(1.0f);
}

void HelloWorld::playSound()
{
  const char *effect;

   #if CC_TARGET_PLATFORM == CC_PLATFORM_IOS
  effect = "Bomb.caf";
#else
  effect = "Bomb.wav";
#endif

    audio->preloadEffect(effect);
    audio->playEffect(effect);
}


texts: need to make a ball travel in the angle it was hit from

texts:
self.hitBall = function (ball, x, y){

        var angle = Math.atan2((x - ball.centerX), (y - ball.centerY));
        ball.velocityY = (Math.sin(angle) * 10);
        ball.velocityX = (Math.cos(angle) * 10);

    }

So the function takes in the ball, which has a centerX variable and a centerY variabe. The x and y passed into the function is the x and y is the point the ball was hit. I want to make the ball travel in the direction it was hit from.

Not really sure why my code isn't working.. it's behaving very strangely and I'm not that good with trig so I'm not really quite sure why it isnt working.


texts: Calculating projectile path when fired at an angle, forward

texts:
I have a problem to code the path of a projectile from a gun as it moves forward and upward. This needs to be done in p5.js.

Although the Angry Birds method has been tried by me, I am looking for a more physics derived function involving the sine and cosine of angle of the gun.


texts: Getting and playing AudioClips by string name

texts: Is there anyway I can get an audioclip by the name it has in the assets folder? Or will I always have to make a reference to it by dragging and dropping the clip on a SoundClip in the inspector?


texts: How can I make a snake's tail follow the head?

texts:
Following an assignment and just getting started with libGDX by building a small Snake clone I've run into an issue that I'll probably be ashamed for in a little while.

I currently have a snake's head (a simple rectangle at this stage) moving around the game's canvas. The most straight-forward way of building the rest of the snake was to have the head own a Java Collections LinkedList of SnakeElements which would in-/decrease in size according to what the player does.

Having this list of SnakeElements follow the head however has proven to not be trivial.

The current function doing this is as follows and is called every time the head updates its position:

private void moveTail (float x, float y, int direction) {
    float tmpx, tmpy;
    int tmpdirection;
    int offset_x, offset_y;

    for (SnakeSegment snse : tail) {
        offset_x = 0;
        offset_y = 0;

        tmpx = snse.getX();
        tmpy = snse.getY();
        tmpdirection = snse.getDirection();

        switch(direction) {
            case 0:
                offset_x = 0;
                offset_y = -(2 + snse.width);
                break;
            case 1:
                offset_x = -(2 + snse.width);
                offset_y = 0;
                break;
            case 2:
                offset_x = 0;
                offset_y = (2 + snse.width);
                break;
            case 3:
                offset_x = (2 + snse.width);
                offset_y = 0;
                break;
            default:
                System.out.println("wrong direction");
        }

        snse.setX(x + offset_x);
        snse.setY(y + offset_y);
        snse.setDirection(direction);

        x = tmpx;
        y = tmpy;
        direction = tmpdirection;
    }
}

which unfortunately results in this behavior:

Any tips on how to make a correctly working snake tail would be much appreciated :)


texts: What should I be considering when designing an Event Manager System?

texts:
I have been puttering around with the fundamentals of a Java game engine, and I've reached the point where I'm ready to add in an Event Manager system.

I know, in theory, what an Event Manager should do: allow objects to "register" for certain events, and whenever the Event Manager gets notified of an event, broadcast the event to the "registered" listeners. What I'm stumped on is how to start implementing it.

I haven't been able to find anything, online, about implementing an event system from scratch, so I'm looking for input on what the best practices are in this case - what I should and should not be doing.

For instance, is it really necessary for each of my game objects to have an EventManager field? Since all of my game objects inherit from a single, abstract parent class, I think I should be able to use a static reference so that there's only one instance of the Event Manager, shared between all the game objects. I do something similar, with the Applet, that I use to render each object, already.

I suppose I'd have to maintain a collection of some sort for each possible subscribed event - adding and removing game objects from the list, as needed. I think it should be possible to make a queue of events that need to be broadcast, in which case I could simply add "EventManager.Update()" to the main game loop, and have the Update() method broadcast the events that occurred at the end of each frame. Finally, each object would have a HandleEvent(Event e) method, that they could then parse and respond to, appropriately.

Does this sound like the appropriate direction towards implementing such a system, or am I way off track and/or missing something quite obvious?


texts: How can I create a cel-shaded, comic book appearance in Unity?

texts:
I am working in Unity, I have imported the post-processing stack and I own a license to Amplify. But I'm having trouble making my models appear cel-shaded enough to make them appear as if they are from a comic book. I'd specifically like to achieve a result similar to that of Telltale's games like Wolf Among Us and Game of Thrones.

Here is a in-editor screen capture of the effect + shader values:

How can I get effects such as below?


texts:
I have made two textures in Photoshop. I applied one of the textures to the sides (one to each side, in the Unity editor) and the other one to the top and bottom sides. However when I extend the object the texture gets stretched which I don't want.

Is there any way to prevent this? The object is a cube.

I don't want the texture to get stretched if I make the cube larger and I don't want the texture to get shrunk if I were to make the quad smaller.

This is what I don't want as a result:


texts: What exactly is different between a string and an FString in Unreal C++?

texts:
Sorry, maybe a noob question, I did a quick google search and couldn't find what I was looking for.  I have two related questions about FString.

Does regular C++ Have this, or is this an Unreal term.  (I know python has a variable called FString).

What makes FString different from the String variable?

thnx.  It's not very necessary for development, but I'm just curious why Unreal uses FString instead of String.


texts:
I'm trying to compute a matrix to have object always facing the camera. For the moment, my result look pretty good, the problem is that my original billboard scale isn't preserved (Every billboard have a size of 1/1).

Here is what I've done using this post:

glm::vec3 look = glm::normalize(camera->getPosition() - objectPosition);
glm::vec3 right = glm::cross(up, look);
glm::vec3 up2 = glm::cross(look, right);
glm::mat4 transform;
transform[0] = glm::vec4(right, 0);
transform[1] = glm::vec4(up2, 0);
transform[2] = glm::vec4(look, 0);
transform[3] = glm::vec4(objectPosition, 1);

glm::quat q = glm::quat_cast(transform);
objectTransformable->setOrientationFromQuat(q);

I've tried to add something like that but the result is a bigger object with bad proportion:

transform = glm::scale( transform, objectScale );

To resume, I would like to extract orientation from result matrix to apply it on my transform object, something like Unity:

MyTransform.LookAt(Cam.transform.position, upVector);


texts: Ensuring a Recursive method completes in one update tick?

texts:
OK so I have a method that calls itself as this was the only way I could think to get the behaviour I needed. Its a tetris clone i am making and this method is for checking for full lines across X axis.

    void CheckForFullLine(int starting_Y)
{
    for (int y = starting_Y; y < frozenCells.GetLength(1); y++)
    {
        for (int x = 0; x < frozenCells.GetLength(0); x++)
        {
            if (!frozenCells[x, y].isFilled)
            {
                CheckForFullLine(starting_Y + 1);
                return;
            }

            if (x == CELL_COUNT_X - 1)
            {
                tetrisLinesThisTick++;
                Debug.Log("lines this tick: " + tetrisLinesThisTick + "on tick: " + tick);
                ClearLine(y);
            }
        }
    }
}

but when i test the game, most of the time (more than 9/10 times) when you get multiple lines, the debug log says we only got 1 line in that 'tick'.

Here is the update method where at the top I set tetrisLinesPerTick to 0 at the start of each frame.

    private void Update()
{
    tick++;
    // reset the tetris-lines this tick value:
    tetrisLinesThisTick = 0;

    ClearScreen();
    CheckForFullLine(0);
    HandleMovementAndBlockCreation();
    DrawFallingPiece();
    DrawFrozenBricks();
}

For example if I get 2 lines in one go, I get the debug log saying '...linesPerTick 1' twice in quick succession.

Strangely , occasionaly  I do get the 2 or even 3 lines and it says the correct amount, but this is rare and i don't know how i  reproduce that yet.

Another very strange thing (the relevant code might not be here for this part..) ...quite rarely one of the frozen blocks will turn grey after falling, then I can still 'use' it in game to make more lines, but it doesnt disappear like the others, then make a couple more lines using this grey block and it disappears as normal :S  (well just in case you feel like helping me with this part, he is more code :P):

    void ClearLine(int line)
{
    // TODO: Add score

    // remove complete line
    for (int x = 0; x < frozenCells.GetLength(0); x++)
    {
        frozenCells[x, line].isFilled = false;
    }

    //shift all lines down        // todo: figure out if its a multi-line tetris to give better scores...
    for (int y = line; y < frozenCells.GetLength(1); y++)
    {
        for (int x = 0; x < frozenCells.GetLength(0); x++)
        {
            if (frozenCells[x, y].isFilled)
            {
                if (y > 0)
                {
                    frozenCells[x, y].isFilled = false;
                    frozenCells[x, y - 1].isFilled = true;
                }
            }
        }
    }

}

For some reason, I feel it may be the recursive method i made  and the fact that 'linesPerTick' value is getting set back to zero prior to the other lines being removed (in the same move), is what is causing my problem but i could be completely wrong about it!

The whole project is just one .cs file and a block texture i made in GIMP, I could paste the whole script here if you want to try it please let me know. Cheers for any help!


texts: Pro's and Con's of Various 3D Game Engines

texts: I normally code my admittedly simple games by hand in either Assembly or C but I'm looking to go a little more high level. I also want to build more modern skills so I'm looking at UDK. What are the pro's and cons of it for indie 3D development. I plan to use graphics, control and physics from the engine so I'm wondering if I should also consider source engine or anything else?


texts:
i installed unity recently .and interface of unity looks like that  [see the image] in all tutorials i see on the internet.

but this is my one(I'm not in the game tab I'm in the scene tab)it's look like brown and i don't like it.i want default interface the interface in first pic which is black .how can i get black interface back ?


texts: Float-based screen coordinates, higher mouse precision

texts:
I wrote 2 weeks ago about problem with motion blur in my engine. When camera moves using keyboard, motion blur is smooth. But when I rotate camera using mouse motion blur is stepping (not sure if I used proper term). Now I rethink my problem and it brings me new questions.

To rotate camera I use mouse delta which is difference between last position and current position. But it is expressed in pixels. Furthermore WinAPI events doesn't have per-pixel precision.

I saw that engines uses it's own screen coordinates which is float-based (http://www.esenthel.com/wiki/index.php?title=Screen_Coordinates). I checked that and I see that even small movement (smaller than 1 pixel) is detected. I believe that this is the solution to my motion blur problem and also with another further problems (for example different size of GUI components on different resolutions).

And here is my question. How can I get such mouse precision? I read about WM_INPUT and dividing delta by mouse DPI, but there are two problems - we can't get mouse DPI using WinAPI and mouse event still return value in pixels.

Where can I find some informations or example of solving this problem?


texts: How to get all tiles along a straight vector path?

texts:
Let's say I have a 100x100 map of tiles where each tile is 16x16 pixels.
How would I get all tiles along a path? For example, let's say I wanted to get a list of all tiles along the shortest direct path between x: 50, y: 100 and x: 225, y: 200
To convert a coordinate to tile space, you simply divide the coordinate by the tile size and then floor it.
So with this example, the world coordinates would be converted to the following tile coordinates:
let tileStartX = Math.floor(50 / 16); // 3
let tileStartY = Math.floor(100 / 16); // 6

let tileEndX = Math.floor(225 / 16); // 14
let tileEndY = Math.floor(200 / 16); // 12

So, we'd be looking for all tiles between x: 3, y: 6 and x: 14, y: 12 like in this example image (0, 0 is top left here):

It's easy enough to convert world coordinates to tile coordinates, but what I'm having trouble with how to get all the intermediate tiles along the diagonal.
Also, I think I may have messed up the drawing slightly because I didn't fill in some white squares where the units have to briefly walk through.


texts: How can I get a cone shape of arbitrary size in an hex board?

texts:
I'm implementing engine tools for my hex board game and this one is becoming messy. I want to get a list of all the positions that a cone of size N would have, given "caster" origin X,Y and origin in X0, Y0 taking direction into account. So far I have been able to get a size one cone using a "simple pattern" approach, but it doesn't translate well for N-sized cones.

This is the original cone

and the code

public PositionArray getArcAdjacents(int originx, int originy, int targetx, int targety,
        int range) {
    final FloatPair direction = this.getDirectionVector(originx, originy, targetx, targety);
    final PositionArray highlights = new PositionArray(gameMap);
    highlights.add(new Pair(targetx, targety));
    int offset = 0;
    if ((targetx % 2) == 0) {
        offset = 1;
    }
    if (direction.x > 0) {
        if (direction.y >= 0) {
            highlights.add(new Pair(targetx - 1, (targety + 1) - offset));
            highlights.add(new Pair(targetx, targety - 1));
        } else {
            highlights.add(new Pair(targetx, targety + 1));
            highlights.add(new Pair(targetx - 1, targety - offset));
        }
    } else if (direction.x < 0) {
        if (direction.y >= 0) {
            highlights.add(new Pair(targetx + 1, (targety + 1) - offset));
            highlights.add(new Pair(targetx, targety - 1));
        } else {
            highlights.add(new Pair(targetx + 1, targety - offset));
            highlights.add(new Pair(targetx, targety + 1));
        }
    } else {
        if (direction.y > 0) {
            highlights.add(new Pair(targetx + 1, targety - offset));
            highlights.add(new Pair(targetx - 1, targety - offset));
        } else if (direction.y < 0) {
            highlights.add(new Pair(targetx + 1, (targety + 1) - offset));
            highlights.add(new Pair(targetx - 1, (targety + 1) - offset));
        }
    }
    return highlights;
}


texts:
I have a particle system. So far it worked like this: I have a dynamic vertex buffer for a system, which is created with a size that can hold for example 100 000 particles. I map/unmap this and write the new data into it every frame.

But what if the particle count gets bigger than the buffer can hold? I thought of recreating the vertex buffer with the double of its previous capacity (then map/unmap into it). Is this the right direction for this or should I solve it in a different way?

A short example:

ID3D11VertexBuffer* buffer;
ID3D11Device*       graphicsDevice;
//...
D3D11_BUFFER_DESC desc;
buffer->GetDesc(&desc);
if(dataSize>(int)desc.ByteWidth){ //data can't fit, so destroy and recreate
    buffer->Release();
    desc.ByteWidth*=2;
    graphicsDevice->CreateBuffer( &desc, nullptr, &buffer ); //returns S_OK
}

Update:

I want to use it for other things, not just particles but for example instanced meshes. If I spawn a couple of instances, I'd only like to resize a buffer, without creating an other one.


texts: How does OpenGL determine different outputs with shaders?

texts:
Lets say I have this GLSL code:

#version 330

out vec4 outputColor;

void main()
{
    float lerpValue = gl_FragCoord.y / 500.0f;

    outputColor = mix(vec4(1.0f, 1.0f, 1.0f, 1.0f),
        vec4(0.2f, 0.2f, 0.2f, 1.0f), lerpValue);
}

(taken from http://www.arcsynthesis.org/gltut/Basics/Tutorial%2002.html)

How does OpenGL determine that outputColor is in fact what color the fragment should be?


texts: How to color each letter text in Phaser.js?

texts:
I have a text created with text object (game.add.text) and I would like to color each letter differently if that is possible.
If not, how can I achieve this?


texts: Accessing archived assets - what are the options in C#?

texts:
We are looking to add an archiving system to our game, where the assets (textures, scripts, sounds, etc.) will be located and directly accessed from memory. The main requirements are:

Files must not be compressed
Archive must have an internal folder structure
Individual files must be accessed directly from the archive without the need to extract them to the hard disk
If an external API is used, it must be able to run on Windows, Mac and Linux ; optimally, it should be redistributable free of charge

Our game engine is in C#, and we are looking for a managed solution (i.e. no PhysicsFS). What could be our options in this case?

Could it make sense to implement the whole thing by ourselves, using FileStream?


texts: What is the easiest way to find a child?

texts:
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.UI;

public class SavedGamesSlots : MonoBehaviour
{
    public GameObject saveSlotPrefab;
    public float gap;

    private Transform slots;
    private string[] imagesToLoad;

    // Start is called before the first frame update
    void Start()
    {
        int counter = 0;

        imagesToLoad = Directory.GetFiles(Application.dataPath + "/screenshots", "*.png");
        slots = GameObject.FindGameObjectWithTag("Slots Content").transform;

        for (int i = 0; i < imagesToLoad.Length; i++)
        {
            var go = Instantiate(saveSlotPrefab);
            go.transform.SetParent(slots);

            Texture2D thisTexture = new Texture2D(100, 100); //NOW INSIDE THE FOR LOOP
            string fileName = imagesToLoad[i];
            byte[] bytes = File.ReadAllBytes(fileName);
            thisTexture.LoadImage(bytes);
            thisTexture.name = fileName;

            go.GetComponent<RawImage>().texture = thisTexture;

            // Here to assign the fileName to the go(saveSlotPrefab) Text child

            counter++;
        }
    }

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

    }
}

This screenshot show example of fileName content :

And this screenshot show the part of the file name I want to extract and assign to the text :

And this screenshot show how the prefab/s are built the Text I want to assign to the file name part is the second child of the prefab. This prefab is the prefabs I'm Instantiating (saveSlotPrefab)


texts: Crafty - How to get the id of the collision element?

texts:
As the topic says, I want to know how to get the ID of an active colliding entity.

My Player Entity is called with

Crafty.e("Player")

Please notice, that I do not want the ID of my Player Entity.
I want the ID of the Collision element


texts: Referencing to objects in other scripts [Unity]

texts:
Hello guys just a quick question, I'm learning from this book and I got this error where

var backgroundBounds = GameObject.Find("background")
 .renderer.bounds;

is deprecated way of doing thins instead it says do it like this:

public SpriteRenderer backgroundSprite;
backgroundSprite = (SpriteRenderer)GetComponent(typeof(SpriteRenderer));

But when I set my GameObject to it which contains SpriteRenderer, on hitting the play button it will disappear and throw null exception.


texts: Determining player.isFalling() through change of y?

texts:
I'm currently using Box2D and my character is a bunch of fixtures in Box2D. I was wondering if, to determine if a player is falling, detecting a change in Y position would be appropriate?

Are there maybe other ways that I'm not thinking of? How is this sort of thing usually detected?


texts:
I'm defining a custom/simple file format for loading textures in my game.  I narrowed my choice of file formats to two options:

Lua
protobuf

I chose Lua, because my game is already using Lua, I wouldn't need to add protobufs to the build.  Eventually, I'll use the engine to build a network game, at which point I'll add protobufs it's just that I don't need it yet and have other pressing needs in the engine.
However, I'm kinda stuck.  Most (all?) of my support tools I write in python.  I can't find a small clean Lua module for python.  That means my python tools end up parsing the Lua syntax by hand.  It's not too onerous as file format uses a very small subset of Lua, but still annoying.
So now I'm second guessing myself, Should I have picked protobuf instead?.
Then I promptly third guessed myself, Am I just afflicted with wanderlust and should stick with a solution that already kinda works?.
So which would you pick (or already did)?
And more importantly why?

My thoughts.
Lua
texture
{
   width=8;  --#256
   height=7; --#128
   format=GL_RGB;
   pixels= [=[
<binary-data-here>]=];
}

+ "plain" text format
Technically only the meta data is plain text but base64 encoding just for the sake of plain text is silly.
+ parsing is trivial as the engine already supports Lua.
-/+ easy (not trivial) to generate, and can be easily verified with luac.
- python tools have difficulty parsing

protobuf
message Texture {
   required uint32 width = 1;
   required uint32 height = 2;
   enum Format {
      GL_RGB = 0;
      GL_RGBA = 1;
      ...
      GL_LUMINANCE_ALPHA = N;
   };
   required Format format = 3;
   required bytes pixels = 4;
}

+ protobufs are well tested and optimized
+ they will be needed eventually to do network communication
- networking isn't part of the engine yet (and wont be for some time, the next few games don't need it).
+ trivial to parse
+ trivial to generate
- complex binary format, impossible to edit, or verify by inspection.


texts: What is the fastest way to get all of the points within a bounding box? If I had an ArrayList<Point>, and they weren't mapped to coordinates, would I have to loop through every point to see if it is in those bounds? Is there a faster way?


texts: Unity UI subpixel rendering/antialiasing with Image.fillAmount?

texts:
I'm using DoTween to tween the fillAmount of a UI Image. When I check the value, it changes smoothly, and in the scene view it appears to transition smooth.
However it appears jerky in the game view, and seems to step for each pixel, so it seems resolution dependent. Is there any way to have the UI render subpixels (?) or antialiased so it uses colors between green/white to have it appear to move more smoothly?
Thanks!


texts:
I know writing tests would be a good way to catch regressions. But what are some other strategies? TDD and game dev don't suit, but catching regressions is obviously something desirable. I would love to find some cheap and easier ways to catch regressions without having to invest a lot of effort or writing tests after the fact.

Strategies suggested don't have to be perfect, if they can give rough ideas or things to playtest rapidly then that would also be beneficial.

Please advise.


texts: I'm an indie developper and I'm planning to do a game based on a TV game show. I would like to know if I could have problems with the law if I do it. I know I should consult a lawyer but I can not afford to do it. For example, can I make a game called "Ninja Warrior, the game", and try to reproduce the game show? Since this isn't a copy of an existing video game, but an adaptation of a game show, I'm confused of what I can do or not. Any help is appreciated.


texts:
The default font of the GameMaker is arial, but it does not contain special characters that are present in the portuguese language.

Soon I had to add a new font, but I activated the ASCII option so that the characters I needed were included.

Hence come my doubt: Even the new font being arial I need to enable the option include in Asset Package for the game to work properly?

And if I have to enable it, where I put the file, and more. Does it need to have a specific name?


texts: How to detect collision position and that position's texture color in Unity?

texts: I have a prefab and I use Circlecollider2D for physics operations. I want to detect the color of the contact position of the collided objects ? Is is possible by using Unity's collider classes ?


texts: Decoupling the entity from whatever controls it

texts:
In a lot of games the player can choose whether an entity will be controlled by the AI or by the player. For example in the game Little Fighter 2, the player can choose how many of a maximum of 8 characters would be AI-controlled and how many of them would be human-controlled.

I was thinking how I can achieve this in my game. Currently in my game whatever controls the characters is hardcoded into them. I even have an AIAgent abstract superclass that all AI characters derive from, and a Player class that represents the player-controlled entity.

I realized that in order to be able to choose dynamically if an entity will be controlled by the player or by the AI, I need to decouple the entity itself from "it's brain", i.e. whatever controls it.

By "the entity itself" I mean the attributes and actions of the entity: it's mass, it's image, the way it implements shooting a missile, etc. By "the brain" I mean the system that decides when, and possibly how, to act.

As I said, currently "the brain" of my entities is hardcoded in their update() function. My Player class responds to player input in it's update() method, and my AIAgent subclasses usually delegate to a StateMachine of some sort in this method.

So I was thinking: how can I decouple the entities from their "brains", in order to be able to choose dynamically whether a Monster is player or AI controlled - and without a lot of ugly code duplication.

The solution that comes to mind is creating an abstract Controller class, with subclasses that can be plugged into the entities. Then the entities simply delegate to their controllers in the 'update()` function, and the controller controls the entity through it's interface.

To demonstrate:

abstract class Entity{
    // .. stuff omitted
    Controller brains;

    public void update(){
         brains.update(this);
         // .. non-behavioral physics stuff omitted
    }

    public void setController(Controller brains){
        this.brains = brains;
    }

    // methods that will be called by the controller in order to control the entity:
    public void attack(){
        ....
    }
    public void moveLeft(){
        ....
    }
    // ....
}

A PlayerController can read user input and control the entity accordingly, while an AIController would implement a state machine to control the entity. The controllers would use the entity's public interface to control it.

The only doubt I have about this approach is that it forces the entities to offer a lot of public methods to control them, such as moveLeft() and shootMissile().

Conceptually, it doesn't "feel right" that the entity would expose methods like these to the outside world, when 'conceptually' it should be it's own job to control itself. Just like it isn't possible to control a human's legs or heart from the outside. Feels like it breaks encapsulation.

So my question is: what do you think of this approach? Can you recommend a better one? How is this often done in games?


texts: What would be an efficient way to check if there is a collision in a 2d game?

texts:
As part of my final project of Algorithms and Data Structures, we have to develop an open world game in C++. I already got developed most of the game, but I haven't coded the collisions with the enemies.

First, I'll explain how the game works. It's an open world game, where there are 10 regions. The world is a big map, where only a small portion of it has to be visualized in the screen . The world is 40 screens x 40 screens, where each screen is 1900 x 1080 pixels.

In this world, there are 250 000 enemies that are distributed in all the regions, so that each region has 25 000 enemies.

Besides, there is a main character that has to travel around this world doing missions, collecting items and killing enemies.

Now, my problems raises here, what is the most efficiency way to check if the main character collides with any enemy, so that when he attacks this enemy and kill him I can eliminate the enemy from the world?

In order to solve this problem, I assigned each region a list of enemies, so that the amount of enemies to validates reduces significantly. I also have a function that returns the region where the main character is.

Then, to check for collisions I do this:

for ( Number of Enemies in the Region)

  if ( MainCharacter is colliding with an Enemy and MainCharacter kills the Enemy)
     delete Enemy from the Region

I think this way is pretty inefficient since I have to validate all the enemies in the region and I just want to validate the enemies that are closer to the main character or are visible in the screen.

How should I improve the collision detection so that it's more efficient?

I hope I made my self clear and I would really appreciate any help you can provide.


texts: Why do I have to set my Unity app to full-screen manually on my phone

texts:
When I open my unity app it doesn't go full-screen until I change it in the settings, isn't there a way to do that... it actually isn't a scaling problem or an aspect ratio.... Because you can see how in the phone settings it is turned off
Thanks in advance