texts:
I'm using Love2D and my own physics engine to create a 2D platformer. Y collision works fine, but X collision... well, it's a bit buggy. When I move off of a small platform I've created, I fall but it is a lot slower than what my gravity is set to. Here's my code for collision:

function world.collisionCheck(o)
    for k, v in pairs(world.objects) do
        if v ~= o then
            if v.Type == "Rectangle" and o.Type == "Rectangle" then
                if o.Position.Y + (o.Size.Y / 2) > v.Position.Y - (v.Size.Y / 2) then o.Velocity.Y = 0; o.onGround = true; end
                if not (o.Position.X + (o.Size.X / 2) > v.Position.X and o.Position.X - (o.Size.X / 2) < v.Position.X + (v.Size.X)) then o.onGround = false; end --right left
            end
        end
    end
end

As you can see, it's pretty bad. The code for the actual physics (gravity, movement, etc.) is a bit better:

function world.update(t)
    for k, v in pairs(world.objects) do
        if v.Static ~= true then
            v.Position.X = v.Position.X + v.Velocity.X
            if v.onGround == false then if v.Velocity.Y < world.Gravity then v.Velocity.Y = v.Velocity.Y + world.Gravity * t end end
            v.Position.X = v.Position.X + v.Velocity.X * world.Meter
            v.Position.Y = v.Position.Y + v.Velocity.Y * world.Meter
            v.Velocity.X = v.Velocity.X * world.Friction
            world.collisionCheck(v)
        end
    end
end

However, it could still use some work. Whenever I step off of a 150 pixel by 15 pixel platform, I fall a lot slower than 9.8 meters per second. My meters are set to two pixels, and I'm falling at about a meter per second, which is much slower than the expected ~20 pixels per second I get while still on the platform. Everything I've tried doesn't seem to fix it; there's no problem in the movement code, and nothing I change in the collision code seems to fix it. Is there some silly problem I've overlooked?

EDIT: Okay, so I implemented a small fix which somewhat solves my problem. I modified the collision code so that it checks if it is below what is being tested for collision, and it seems to accelerate as normal when the top of the object is below the object being collided with, and vice versa. Am I correct in assuming I just need to add something to detect if the x-value is in the correct range, too?


texts: Vector2.Distance on different resolutions

texts:
firstTouchPos = Camera.main.ScreenToWorldPoint(Input.GetTouch(0).position);

endTouchPos = Camera.main.ScreenToWorldPoint(Input.GetTouch(0).position);

                        //the height of the background(previously scaled to fit the screen) / 10
minSlidedDistance = (int)(SpriteRend.bounds.size.y / 10);

if (Vector2.Distance(firstTouchPos, endTouchPos) > minSlidedDistance)
{
  //do smth
}

This way I check if the player has slided into any direction with a slided distance longer than minSlidedDistance. It works perfectly for different size devices.

Is unity going to make the calculations itself if I simply write minSlidedDistance = 100? I.e. is it still going to work same way on all devices?

P.S. this is not the full code, there are many other IF checks, like the ones for assigning the value to firstTouchPos & endTouchPos


texts: Moving sprite from one vector to the other

texts:
I'm developing a game where enemy can shoot bullets towards the player. I'm using 2 vector that is normalized later to determine where the bullets will go.

Here is the code where enemy shoots:

private void UpdateCommonBullet(GameTime gt)
        {
            foreach (CommonEnemyBullet ceb in bulletList)
            {
                ceb.pos += ceb.direction * 1.5f * (float)gt.ElapsedGameTime.TotalSeconds;
                if (ceb.pos.Y >= 600) ceb.hasFired = false;
            }

            for (int i = 0; i < bulletList.Count; i++)
            {
                if (!bulletList[i].hasFired)
                {
                    bulletList.RemoveAt(i);
                    i--;
                }
            }
        }

And here is where i get the direction (in the constructor of the bullet):

direction = Global.currentPos - this.pos;
direction.Normalize();

Global.currentPos is a Vector2 where currently player is located, and is updated eveytime the player moves.

This all works fine except that the bullet won't go to player's location. Instead, it tends goes to the "far right" of the player's position.

I think it might be the problem where the bullet (this.pos in the direction) is created (at the position of the enemy). But I found no solution of it, please help me.


texts: Find shortest path (quickly) on the surface of a 3d model?

texts:
Imagine this scenario:
we have a 3d model, for instance a doughnut, apple or an orange (possibly something more complex). There's an insect (let's say an ant) on the surface of that food item. Now that ant wishes to reach a certain specific coordinate embedded on the surface of the 3d object in the shortest time possible (using the shortest path, ignoring physics).

Now the ant AI could use Dijkstra on the original mesh but that might be low-res so the ant will zig-zag on the surface, outlining the shapes of blocky faces. You could split the faces but the angular nature of the edges, making up the structure of the mesh will continue to drive the ant to more in ziggy-zaggy like manner (imagine a rougelike with very small squares, you can still only move in 8 directions at any given point).

What we did is split the edges (of the model) to evenly-sized pieces and embedded "navigation vertices" between these pieces, we then connected the vertices of each edge with vertices of other edges sharing a face with it (4 other edges because faces are triangular). This works pretty well cause it means the any can travel freely between faces, ignoring their shape almost completely (unless they are very small and were not split).

We also have the ant "pulled" (dragged even) by an imaginary ant that is a few steps ahead to completely eliminate the more rigid areas in the path (think sharp corners). Sounds great right?

But this is not terribly fast. Any advice about that is appreciated.


texts: Since D3DX utility library is deprecated, what can I do about this legacy code?

texts:
D3DX Structures utility library is deprecated for Windows 8 and its not supported for Windows Store apps. So my question is, Does anyone know what to replace this legacy code with..

std::vector<ID3D11Texture2D*> srcTexture(size);
for(UINT i = 0; i < size; ++i)
{
    D3DX11_IMAGE_LOAD_INFO iload;

    iload.Width  = width;
    iload.Height = height;
    iload.Depth  = D3DX11_FROM_FILE;
    iload.FirstMipLevel = 0;
    iload.MipLevels = D3DX11_FROM_FILE;
    iload.Usage = D3D11_USAGE_STAGING;
    iload.Format = format;
    iload.BindFlags = 0;
    iload.CpuAccessFlags = D3D11_CPU_ACCESS_WRITE | D3D11_CPU_ACCESS_READ;
    iload.MiscFlags = 0;
    iload.Filter = filter;
    iload.MipFilter = mipFilter;
    iload.pSrcInfo  = 0;

    HR(D3DX11CreateTextureFromFile(d3ddevice, filename[i].c_str(),
        &iload, 0, (ID3D11Resource**)&srcTexture[i], 0));
}

I have been using directXTK to try an replace them but its a difficult process, both
D3DX11CreateTextureFromFile and D3DX11_IMAGE_LOAD_INFO still need replaced and D3DX11_FROM_FILE is also a depreciated parameter, is there an alternative or effective solution available?

thx in advance


texts:
I have been working on making a platformer in Godot but can't seem to get a walk cycle to play when I press left or right.

extends KinematicBody2D

export (int) var run_speed = 300
export (int) var jump_speed = -400
export (int) var gravity = 1000

var velocity = Vector2()
var jumping = false

func get_input():
    velocity.x = 0
    var right = Input.is_action_pressed('ui_right')
    var left = Input.is_action_pressed('ui_left')
    var jump = Input.is_action_just_pressed('ui_select')

    if jump and is_on_floor():
        jumping = true
        velocity.y = jump_speed
    if right:
        velocity.x += run_speed
    if left:
        velocity.x -= run_speed

    if left or right and jumping != false:
       get_node("AnimationPlayer").play('walkcyc')

    if left or right and jumping != true:
        $AnimatedSprite.animation = 'run'
        $AnimatedSprite.flip_h = velocity.x < 0

    if is_on_floor() and velocity.x == 0 or velocity.y == 0:
        $AnimatedSprite.animation = 'stand'
        $AnimatedSprite.flip_v = false
        $AnimatedSprite.flip_h = velocity.x < 0

    if jumping != false:
        $AnimatedSprite.animation = 'jump'
        $AnimatedSprite.flip_v = false
        $AnimatedSprite.flip_h = velocity.x < 0

func _physics_process(delta):
    get_input()
    velocity.y += gravity * delta
    if jumping and is_on_floor():
        jumping = false
    velocity = move_and_slide(velocity, Vector2(0, -1))


texts: How do games deal with Z-sorting partially transparent foliage textures?

texts:
I was busy implementing basic transparency in a prototype I'm working on when something occurred to me.

In order for a given texture's transparency to work as expected, the (semi-)transparent texture must be drawn after whatever is behind it, right?

Well, if we take for example a tree or shrub in a game like Skyrim, the texture(s) that make up the foliage on that tree or shrub must include some transparency somewhere, right?  A vertex-perfect leaf model would be far too resource-intensive.  But the player can move around, and sometimes through, any plant at will, thus changing the relative position of all textures to the camera.

Doesn't this mean that the game has to constantly Z-sort all textures, both between models and even within a single plant model, whenever the player moves (so potentially every single frame)?  Isn't that very resource-intensive?  How do games with lots of partially transparent textures deal with this?


texts: Improving performance for flocking behavior?

texts:
I have a game that I am trying to make. It is a twin-stick shooter that I want to design to have a LOT (Up to 500) of enemies on the screen. The game's base design comes from that of Geometry Wars, and serves as a learning experience.

A bit about my setup: i7 quad-core CPU @ 3.5GHz, 8GB of RAM, and Intel 4000 integrated graphics. While these aren't the best specs, they are now more and more common, so this is my target system.

There is an invisible plane that acts as the playing field. I built a NavigationMesh from this plane, and sample random points from that to spawn my enemies. The enemies use DetourCrowd to implement the flocking behavior. On my moderately-powerful machine, I can get around 150 enemies before I begin to experience drastic performance drops. Accounting for other potential issues, I made my enemies invisible, so only the agents are used, and still the performance drops significantly from 150-200 enemies on my machine. It is bad enough that this difference of 50 enemies drops my framerate from a solid 60 fps to <1 fps.

I decided to instead try using Bullet physics instead. I have the linear/angular factors setup to make Bullet act on a 2D plane. All of my enemies now use a Sphere for collision, have a mass of 1 unit, and no friction. They are not affected by gravity or external forces, but instead I set a fixed impulse at the beginning of each physics step. Additionally, the collision mask is setup so that the enemies only collide with each other. Around 350-400 enemies, I begin to see performance issues. They're not nearly as severe as the performance issues that I see with DetourCrowd, however they do come with an additional downside.

I use a small sphere set as a Trigger for firing off bullets. I handle the collision events to destroy the enemies. With the DetourCrowd method, this caused no noticeable performance drop. However with the Bullet approach, it causes a much more significant performance drop.

Overall, I can comfortably use ~120-150 enemies with the DetourCrowd approach, and ~200 enemies with the Bullet approach.

Are there any solutions that would give a much cheaper flock behavior for this game? I prefer solutions targeting 2D under the assumption that it will be cheaper than a solution targeting 3D.


texts: Binding the camera to the body of the skeleton

texts:
It is necessary to design: "Only the body of the skeleton rotates with the camera"

Problem above

I'm not advanced. My hunch: Programming CapsuleComponent.h - inherit skeleton components. I could be wrong. Please help me find the right solution to the problem!


texts: IndexOutOfRangeException on array of transform prefabs in Unity

texts:
I have a public array of length 9 containing prefabs I'm using as position references for a moving object. The start function finds the transform.position of the appropriate transform in the array and makes it the target for a Vector3.MoveTowards() function that is called every update. I have an exception for the start function, but the object moves fine. If I print the length of the array on every update, It shows zero every other frame, and 9 otherwise. There's nothing in the script changing the array, how is this happening?

I'm using the Linux build of Unity.


texts: Can I use flat shading on a generated mesh?

texts:
I tried to generate a mesh from code in Unity. The problem is, that the edges are automatically smoothed. When I import a model into Unity, I can set the smoothing angle of the edges, but is something like this possible with a generated mesh?

I would like to have no smoothing at all.


texts:
I'm working on a game with an entity firing a shot. This shot could destroy other entities as well as the entity who generated the shot.
My first step was to apply a force to the rigidbody2D of the shot, but when my entity is too fast the shot destroy it (the speed does not match).

I tried adding the speed to the force but the values mismatch by far (the force is a vector of like 150 magnitude, whereas the speed as a magnitude of 1).

I wonder how one can achieve this, to add the current speed of the entity to the shot fired, and i wonder if there's any litterature concerning the way physics is actually handled in Unity, i find very little documentation on the Physics.

Thanks.


texts: Remove delay when changing axis input in the Unity Input Manager

texts:
I had a problem playing with the Input Manager, where for example:

When Horizontal (+) is pressed, it increase its value but, when Horizontal (-) is pressed, the horizontal value stays positive for a little, but keeps decreasing. This causes the character to continue playing "right" animations and still moving to right for a few seconds, instead of instantly playing 'left" animations and moving to left. The problem also makes the character movie a little after the player releases the key.

I have also used Input.GetKey(), but that means the player cannot change the setting from the game launcher, and I don't want to create player setting in-game, for now.

What I am trying to achieve is when Horizontal (+) is pressed, then the player presses Horizontal (-), it should instantly turn left without delay. When the player is not pressing any Horizontal key, it should stop moving horizontally, instantly. This problem also appears along the Vertical axis.

How do I make it so input snaps to -1 or 1, with out slowly moving back and forth?


texts: OOP architecture for Hero with many attributes

texts:
I'm about to start a simple browser text RPG, with characters that can (passively) fight other people. This involves a list of about 10 skills like strength, dexterity and so on, with additional proficiencies for different weapons.

Is there a better way to design this character class then just having those skills as class attribute? It seems easy, but I'm reluctant because it's clumsiness.

class Char(self):
    int strength
    int dexterity
    int agility
    ...
    int weaponless
    int dagger
    ...


texts: How to compute acceleration by using Kinect device joint positions

texts:
I have an application which uses the Microsoft Kinect camera device.

At each point I can obtain the position of my hand in the 3 Dimensional space ( X - Y - Z ) and I want to compute acceleration of my hand over each second on each axis.

Basically, I can obtain the coordinates at each frame(where 1 sec = 30 frames), and I want to compute the acceleration of my hand in 1 sec.

StartPoint - (x1, y1, z1)

EndPoint after 1 sec from StartPoint ( 30 frames ) - (x2, y2, z2)

Acceleration between StartPoint and EndPoint = ?

Also I can obtain all the other coordinates of my hand over time, but I want to compute the acceleration in the period of time between start point and end point.

Could you please explain or show me how?


texts:
Since I found out Box2D, I'm using it for kind of any game-like application I try to write, from very small prototypes or small programs to test something, to actual projects.

Thanks to it it's so terribly easy to handle anything from collisions, to the actual physics.

Sometimes, though, I have some doubts about it: if I only have to handle circles or AABB, and don't need advanced physics tools (joints or stuff like that), I think that a physics engine could add a sort of big, unneeded overhead.

To reassume my question: would you use Box2D (or other physics engines) in a game where physics is really simple (like Super Mario, let's say)? And, if not, why?


texts: How to manage dependencies between tile map and units

texts:
I have a 2D tile-based strategy in the works.  I'm wandering how to handle the relationship between the map and the units on the map.

Given a tile coordinate I'll need to be able to get the unit standing on it, if any.  At the same time, if given a unit I'll want to be able to get the unit's coordinate.

I've seen two solutions to this.  The first solution would be to have units store a coordinate and the map store unit references in its tiles.  This creates a cyclic dependency between the map and units.  I'd need to make sure that the map an any unit are kept in sync if the unit moves.

The second solution would be to only have the units keep track of their coordinates.  To tell if a tile contains a unit and to get that unit, I'd loop through the whole set of units unit I find one with matching coordinates.  That get rids of the cyclic dependency, but it looses the O(1) property the first solution had for looking up units from the map.  This may add up as I want to be able to scan the map regularly for things such as path finding, determining movement range, and finding valid targets for a given unit.

I also can't just store the units in the map (or can I?).  Units are associated with "armies", either player or AI.  An army should be able to easily access and iterate over all of its units.

Since this appears to be a common issue in strategy games, are there any other patterns besides the two I described for managing unit/map relationships?


texts: Does PBR mean only one, right technique to view 3D scenes?

texts:
For example if I call Unity 5's render pipeline "PBR" (Physically-Based Rendering) and also call Unreal Engine 4's render pipeline "PBR," does it mean that the same model with the same PB textures will be viewed identically in very similar or equal scene setups on both engines?

I just wondering if someone says "PBR," does it mean only one, single, right way to do "PBR," or do implementations vary from one to the other?


texts: no intellisense visual studio code in Unity windows

texts: It doesn't recognize object types and I can't use reference-finding. I have the Omnisharp plugin installed and updated.


texts: Tips and Tools for creating Spritesheet animations

texts:
I am looking for a tool that I can use to create sprite sheet easily.

Right now I am using Illustrator, but I can never get the center of the character in the exact position, so it looks like it is moving around(even though its always in one place), while being loop through the sprite sheet.  Is there any better tools that I can be using?

Also what kind of tips would you give for working with a sprite sheet?  Should I create each part of the character in individual layers (left arm, right arm, body, etc.) or everything at once?  any other tips would also be helpful! thank you


texts: Where is 'game logic' implemented in component based design?

texts:
I have been trying to get my head around using an entity component system for a game. But I am struggling to understand how I should do 'game-logic'.

What I have so far:

Components are essentially just dumb data holders, no logic beyond getters and setters.
Systems do processing on groups of components. E.g a PhysicsSystem might process all entities containing Transform and Velocity components.
Entities are just integers.

My question is, how do I add 'entity-specific' or 'game' logic? For example, I will have an entity which represents the player. How do I go about moving the player entity?

Couples ideas I had, not sure if any are good?

Create a 'MovementSystem' which uses a component (e.g PlayerMovementComponent). Then give just my player entity the PlayerMovementComponent. This is basically just a system which only ever processed the one entity... seems a big fudgey.
Create a Script or Behaviour component which holds a std::function (or maybe could reference a lua script), could then have lambdas which allow unique game logic to be given to entities. This seems to go against the data-orientated approach I’m trying to follow?
Create a Player class, have it reference the entity Id then give the player class an update method hooking into the game loop. This update method can edit its referenced entities components before the systems process. This is basically disconnecting myself entirely from the ECS for game-logic... not a fan of this idea (also will make my game loop bloat as more unique entities are required).

Hopefully, I can get some comments on the 3 ideas above and some new ideas or thoughts I can pursue.


texts:
I want to filter my shadow map generated by PSSM, but the problem is that I have a inconsistent filter size.

The problem is that the shadow map sources rotate to find the best fit for the camera frustum, and thus sampling with a constant offset (e.g. 10.0 / resolution) produces inconsistent results.

A gif shows it probably best (same shadow and sun position, just different view angles):

GIF showing the issue

My idea was to, instead of using a fixed filter offset, compute the filter offset by projecting 2 world-space points to light-space and taking the difference of both, like this:

vec4 find_filter_size(mat4 projection, vec3 light, float sample_radius) {

    // Find an arbitrary tangent and bitangent to the light vector
    vec3 v0 = abs(light.z) < 0.99 ? vec3(0, 0, 1) : vec3(1, 0, 0);
    vec3 tangent = normalize(cross(v0, light));
    vec3 binormal = normalize(cross(light, tangent));

    // Project everything
    vec2 proj_origin = project(projection, vec3(0)).xy;
    vec2 dx_proj_tangent = project(projection, tangent).xy - proj_origin;
    vec2 dx_proj_binormal = project(projection, binormal).xy - proj_origin;

    return vec4(dx_proj_tangent, dx_proj_binormal) * sample_radius;
}

However that didn't quite work out, and, in fact, produces even more artifacts.

Any suggestions how I could fix this? I just need a basic idea, then I can figure out the implementation by myself.


texts:
My 2D Unity game has tiles and layers. It creates one game object per tile, anywhere from 100 to 10,000. To create 3,000 game objects takes 68 msec, which is just fine.

But setting up the sprite and location takes 5,000 msec, or nearly 2 msec per sprite. This is a problem. Here is the code for setting up each tile.

   var sprite = _main.GetSprite(LevelIndex);  // pre-computed table of sprites
   _renderer.sprite = sprite;  // the sprite renderer for the tile
   if (sprite != null) {
     var cursize = _renderer.sprite.bounds.size;
     var scale = Math.Max(Size.x / cursize.x, Size.y / cursize.y);
     transform.localScale = new Vector3(scale, scale, 0);
   }

How can that code take 2 msec? What's going on?

The sprite size is 80x80. Is this a problem?

Once it's all set up it renders at 100 fps easily. So why is the setup so slow, and what can I do about it?

Yes, I considered using a TileMap. It's not easy to see how to create one in fully procedural code, but at the heart of it is the Tile class, which has a GameObject and a Sprite. If I implement my own Tile class it's going to have code that looks a lot like the above, and (after a lot of work) most likely perform exactly the same.

Since Tile and TileMap are just layers over standard Unity infrastructure, then if they do have a way to perform much faster, I should be able to apply the same technique to my situation and get the same performance.


texts: Why projection window is between -1 and 1

texts:
Is it a convetion ? What we achieve with this ?

I am reading about how the perspective and orthographic matrix is getting calculated and everyone is trying to normalize the homogenous coordinates to [-1,1]

Thank you !

Orthographic Projection


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

public class cameraswitch : MonoBehaviour {
 public Camera cam1;
 public Camera cam2;

void Start () {
    cam1.enabled = true;
    cam2.enabled = false;
    Button Button = gameObject.GetComponent<Button>();
    Button.onClick.AddListener(baz);
}

void baz () {
    cam1.enabled = false;
    cam2.enabled = true;
}
}

this is my code . how to switch between the cameras with one button . and Thank You.


texts: Maya Command Line - change texture applied to a model before rendering

texts:
I've written some batch scripts which automate maya through the Render application. The batch scripts are working over a series of different scenes and render all of them out.

For some of the models, I would like render the animations in the scene multiple times with different textures applied. Right now, my only solution is create another scene, apply the new texture and include the copied scene in the batch scripts.

Is there another, better way to do this? Ideally, some command line arg that said use texture X for this render would be lovely.


texts: How To Update Animation in Unity After Changing the Names of Objects in Mechanim

texts:
I have an animation clip I made with Mechanim. But when I changed the hierarchy of the objects in the children, it stopped working!

The text says ( Missing! )

Why is it breaking? How can I fix it?


texts: How to convert this physics2d raycast with ^ code to physics raycast

texts:
While searching on the net I encountered a piece of code in a tutorial I want to use in my game but don't know how to convert it to physics.raycast (https://www.youtube.com/watch?v=1i1hTLU6JTY)

it's about the following piece of code I want to convert:

RaycastHit2D maxSlopeHitLeft = Physics2D.Raycast (raycastOrigins.bottomLeft, Vector2.down, Mathf.Abs (moveAmount.y) + skinWidth, collisionMask);
RaycastHit2D maxSlopeHitRight = Physics2D.Raycast (raycastOrigins.bottomRight, Vector2.down, Mathf.Abs (moveAmount.y) + skinWidth, collisionMask);
if (maxSlopeHitLeft ^ maxSlopeHitRight) {
 SlideDownMaxSlope (maxSlopeHitLeft, ref moveAmount);
 SlideDownMaxSlope (maxSlopeHitRight, ref moveAmount);
}

I especially don't understand the use of ^, isn't it the same as saying

if((!maxSlopeHitLeft && maxSlopeHitRight) || (maxSlopeHitLeft && !maxSlopeHitRight))

I hope someone can help me with the 1st piece of code.

I tried to convert the code myself as follow

RaycastHit maxSlopeHitLeft, maxSlopeHitRight;
if(Physics.Raycast (raycastOrigins.bottomLeft, Vector2.down, out maxSlopeHitLeft, Mathf.Abs (moveAmount.y) + skinWidth, collisionMask) ^ Physics.Raycast (raycastOrigins.bottomRight, Vector2.down, out maxSlopeHitRight, Mathf.Abs (moveAmount.y) + skinWidth, collisionMask)) {
SlideDownMaxSlope (maxSlopeHitLeft, ref moveAmount);
SlideDownMaxSlope (maxSlopeHitRight, ref moveAmount);
}

when my player reaches an edge of a platform it freezes all movement, while in the source tutorial it doesn't

Here is the SlideDownMaxSlope method, it check whether the angle is high enough to slide and calculates the horizontal moving amount

void SlideDownMaxSlope(RaycastHit Hit, ref Vector3 MoveAmount){
    float SlopeAngle = Vector3.Angle (Hit.normal, Vector3.up);
    if (SlopeAngle > MaxSlopeAngle) {
        MoveAmount.x = Mathf.Sign (Hit.normal.x) * (Mathf.Abs (MoveAmount.y) - Hit.distance) / Mathf.Tan (SlopeAngle * Mathf.Deg2Rad);

        CI.SlopeAngle = SlopeAngle;
        CI.SlideDownSlope = true;
        CI.SlopeNormal = Hit.normal;
    }
}

plus in an update function of another script there is a line for calculating the vertical moving amount

if(Grounded) {
    if (PCS.CI.SlideDownSlope) {
        Velocity.y += PCS.CI.SlopeNormal.y * -Gravity * Time.deltaTime;
    } else {
        Velocity.y = 0;
    }
}


texts: Creating a large amount of sprites and animations

texts: For my AP U.S. Government and Politics class, I am making a spinoff of Mortal Kombat. Because of time constraints, I'm using an open source version of the game and want to create new characters.  I have about two weeks to do the project and can invest about 1-4 hours most days. I want it to look as nice as it can with the limited knowledge, skill, and time that I have. What programs or techniques would be best for a beginner with my time constraint?


texts: Converting cartesian geo-coordinates to isometric (real world map to game map)

texts:
I need to create an automated method to convert real cartesian, geo-coordinate data (such as roads and parks), into isometric coordinates as a game map view for use in HTML5 Canvas.

Here is an image of what I mean:

Example Image

Taking into account heavy map distortion in the process to fit they isometric layout. Is this even remotely possible?


texts: Ligdx Box2d : convert box2d coordinates into screen coordinates

texts:
I'm new in libgdx and i have a little problem. I created a body in box2d and i want to assign it a sprite; for that i need to get the position of the body,then insert into the main loop the updated position of the sprite, right ? So..i made so but the sprite doesn't align right on the body, but in a corner. What should I write in body.setPosition() and in sprite's position ?

P.S: sorry but i can't post a screenshot :(


texts: Creating Terrain of Golf Course in Unity? (use Unity Terrain or 3d software)

texts:
Hi all I wanted to create some simple, but pretty, golf courses for a Unity game.

I've not found much success with the built-in terrain maker as the painting of textures is not sharp edges).

Is it best to have only the basic layout in the terrain and then have separate meshes for the fairways and greens (and if so, how would I go about making that 'wrap' exactly onto the terrains surface to lie flat on it?)

Perhaps I can paint the textures somehow with much more definition on the edges but I can't find how to do it. If this is the case, how is it best to identify to the other gameobjects such as the ball as to what kind of surface it is on?


texts: Replacing 4 additive sprite layers with a single shader. Just can't get it right

texts:
I'm using directx9 and have 4 textures I want to draw on top of each other. if I do this:

PDevice->SetRenderState(D3DRS_SRCBLEND,D3DBLEND_SRCALPHA);
PDevice->SetRenderState(D3DRS_DESTBLEND,D3DBLEND_ONE);

SetTexture(0,texture1);
DrawSprite();

SetTexture(0,texture2);
DrawSprite();

SetTexture(0,texture3);
DrawSprite();

SetTexture(0,texture4);
DrawSprite();

I Get EXACTLY the cool effect i want. but I suspect this level of blatant overdraw is inefficient. I'm sure this can be compressed into a single draw call somehow, and run faster. The trouble is, everything I try does not look the same, whether I try a fixed-function muyltitexturing approach setting the 4 textures as different texture stages, or whether I try to implement it inside an fx file as a shader. Nothing has the same effect.

Is it even possible?
I'm guessing within a shader it could be done by just mulitplying the sampled texture at each stage with the current screen value, but tbh I'm not sure if that is accessible to the shader (or how).
My current code works, but it bugs me I'm drawing 4 huge textures separately :D


texts:
I'm writing a program that creates animated blobs in 2D, to simulate cells. In order to beautify these objects, I'd like to give them a 3D look by adding a bevel-effect. How can this be achieved?

Program as it looks now (the blobs are animated, move, change shape etc):

And this could be a potential desired outcome:

I underscore that I'm not using anything else than GDI+, so I'll have to write the implementation myself. Virtually every graphics program has some kind of beveling filter, but I've looked high and low online to find examples of such code.

Edit:

I was testing a few theories, and this one could work. However, it's not my most optimal solution (even though Gaussian blurs can be made linear using separable kernels) and I have another in the working. Anyway, this could be a first attempt at a fast beveling algorithm:

The result in the picture I created above is the direct outcome of the steps of the algorithm, but I suspect it might run too slow for 25fps.


texts: Ledge climb animation and movement (2d platformer)

texts:
Struggling to make a decision on the implementation of a ledge climb mechanic for a physics driven 2d platformer. What is the best way to go about this without it getting overly complex?

So far I understand (hobbyist here not a pro) there a few options including:

Apply controlled force to the rigid body on the y axis until the root position is just above the hand position then apply enough force on the x axis so as the character is standing on the platform. At the same time somehow sync this with the climb animation(s).

Remarks: movement is easy here and can even be controlled by a prismatic sliding joint but I'm unsure of how I would keep the animations (spine) in sync with the movement.
Root motion animation that drives the root position of the character. Teleport the rigid body when complete and hope box2d can still properly respond in time to any collision if any objects happen to fall from the sky.

Remarks: sounds easier to actually animate but not sure if I'll run into any problems with the spine runtime, box2d or later down the line moving platforms and varied height platforms.
Apply IK constraint programmatically on the hands to lock them in place and proceed to rotate the bones manually or apply small preset (few keys/frames) animations whilst applying the needed force to the rigid body at the same time.

Remarks: seems like this would give maximum control to the player but it sounds way to complicated for me to implement at my level, not exactly sure where I would start.

Thanks in advance for any input!

FYI: This is an ECS (libgdx + ashley) based engine with box2d. The ledge grab is already implemented as a separate system so we can assume here that the character is already capable of hanging from a ledge of any height.


texts: Rotate perspective camera to align screen width to procedural object's width (Unity, C#)

texts:
I give up. After much trying and searching, I have to say I was unable to achieve the following task, for which I must call for your wise advice.

In my current Unity 5 application (using C#), there is a procedurally generated object (therefore with variable shape) to which the camera should be aligned when players hit a given key. By aligned, please understand it making the width of the screen parallel to the longest part of the object. The idea is represented in the following picture, where in black one can see the irregular object, in yellow is the bounding box.

In other words, it means that I want the camera to be rotated so to align to the longest side of the object's bounding box. I tried that. Still, I was unable to properly calculate the correct angles so to rotate the camera in a way that the horizontal axis of the screen becomes parallel to the width of the objects' bounding box.

Any help would be much appreciated.


texts:
I have this code in OpenGL:

Vuforia::Matrix44F modelViewProjection;

VuforiaApplicationUtils::translatePoseMatrix(0.0f, 0.0f, self.scale, &Vuforia::modelViewMatrix.data[0]);
VuforiaApplicationUtils::scalePoseMatrix(self.scale, self.scale, self.scale, &Vuforia::modelViewMatrix.data[0]);
VuforiaApplicationUtils::multiplyMatrix(&projectionMatrix.data[0], &Vuforia::modelViewMatrix.data[0], &modelViewProjection.data[0]);

And the modelViewProjection gets used like this:

glUniformMatrix4fv(mvpMatrixHandle, 1, GL_FALSE, (const GLfloat*)&modelViewProjection.data[0]);

With mvpMatrixHandle being a piece of code in the shader:

mvpMatrixHandle = glGetUniformLocation(shaderProgramID, "modelViewProjectionMatrix");

And in the shader itself:

gl_Position = modelViewProjectionMatrix * vertexPosition;

Now I try to convert this to SceneKit code (never used it before, so I might miss a big part of my SceneKit code)

// Setup
let plane = SCNNode(mdlObject: MDLAsset(url: Bundle.main.url(forResource: "Bubble", withExtension: "obj")!).object(at: 0))
scene.rootNode.addChildNode(plane)

let camera = SCNCamera()
plane.camera = camera

// Each frame
modelViewMatrix = SCNMatrix4Translate(modelViewMatrix, 0, 0, scale)
modelViewMatrix = SCNMatrix4Scale(modelViewMatrix, scale, scale, scale)
let modelViewProjection = SCNMatrix4Mult(arrayToMatrix(pose: projectionMatrix), modelViewMatrix)

//camera.projectionTransform = modelViewProjection
scene.rootNode.childNodes[0].transform = modelViewProjection

As you can see, I have also tried to set this as the projectionTransform of the camera, but that did not work either.

My result is the most annoying to debug: nothing gets rendered using the SceneKit code, while the OpenGL code works.


texts: How do I gain access to objects in order to change their properties in Unity?

texts:
I have created a GUI text object named "GUIText" in the Unity editor, and I want to change what the text says via code (I'm using C#). How do I access GUIText1 to change its string properties?

I want to be able to write code like this:

GUIText1.Text = "";

In general, I'm not sure how to get access to any sort of object created in the editor (a mesh or a light for example). How do you access them in code?

I already know how to write the scripts and trigger them.


texts:
I'm a beginner at making games, and my eBook that I learnt Python from just made a 2D game and simple game like snake in Nokia because I want to know more Python in correlation with game development.

Can someone tell and explain to me what the Python language can do to make a game?


texts:
After reading This SO post on Vectors, I'm still pretty confused on how to use vectors to move my entities at any angle. The SO post assumes only 90 degree angles:

if up pressed:
    direction = direction + Vector(0, -1)
if down pressed:
    direction = direction + Vector(0, 1)
if left pressed:
    direction = direction + Vector(-1, 0)
if right pressed:
    direction = direction + Vector(1, 0)

Once I have the vector length (are "length", "speed" and "magnitude" all the same thing?), and vector direction (angle), how do I actually move the entity towards the player target at the specified angle and speed?

So, for example:

Point a (Player x, y): is at (2, 3)
Point b (Target x, y): is at (6, 8)

Vector between a and b is:

x2 - x1 =  6-2 = 4
y2 - y1 =  8-3 = 5

Vector x,y = (4, 5)

Vector length = sqrt (x^2 + y^2) = 6.4 "units"

Vector direction = atan(5/4) = 51 degrees down and to the left

So I know the speed/length/magnitude is 6.4 "units", and the angle is 51 degrees, but now how do I apply this data to make point B actually move towards point A at that angle and correct speed?


texts: How can I design loot to be enjoyable to acquire and neither a chore nor frustrating?

texts:
I am currently working on an ARPG and I am trying to figure out which elements of the game influence each other and one example is that endgame activities inherently influence loot drops/handling and the other way round. The more classical loot systems we usually get in touch with are following:

Classic MMORPG loot where enemy bodies have to be clicked which open up a window which displays the loot that can be clicked one item at a time. Sometimes it is possible to enable auto-loot in order to skip the clicking of each item.
ARPG loot where slain enemies die in a explosion of loot which can occasionally get extreme up to a point where loot filters are necessary otherwise the screen will be cluttered. In this case players usually pick up uncapped currency like gold automatically while everything else from gear to crafting parts has to be looted manually if the player so desires. Diablo, Path of Exile and the likes to handle it with cliackable labels on-screen while Borderlands for example spreads the loot all around the place and has visual light beams indicating rarities that allows players to filter quickly and go grab the items they might be interested in.
"Loot chests" is what I call the system of Destiny. During a strike or adventure players do participate in combat and are not distracted by random loot on the ground which would require consideration as to whether picking it up is a good choice. After the event has ended, typically after defeating the final boss a chest appears that contains loot.
"Vacuum loot" which was used for Guild Wars 2 and Wildstar where the loot physically drops on the ground and players can loot everything from currencies to gear with one click of a button. In an ARPG this would never work out since inventory space is even more restricted than anything else.

My naive first thoughts are based on how the endgame of Diablo 3 is designed. In classic endgame rifts players can slay enemies and are usually busy picking up materials and some "useless" items that may be used to disassemble them for even more materials. Furthermore they are looking for chests and hoping for some random drops. In contrast to that game mode there are greater rifts which, similiar to Destiny, drop no loot at all except when you kill the final boss that appears after progressing far enough.

In greater rifts there are no distractions just the challenge to finish those at higher difficulties and farming them with specific speed builds while on the other hand the classic rift slow down gameplay when you have to stop every few meters just to click and pick up those items.

I have reached an impasse since I understand players might want to blaze through content and I don't want to make them slow down constantly (with a system like classic rifts in Diablo or Path of Exile in general) but when I stick to "loot chests" at the end of an activity it might happen that less loot drops in general and that there is less gratification when collecting things since the is nothing on the way. Take a long dungeon for example, a "loot chest" system might incentivize just skipping all enemies and do the bare minimum to tackle the final boss. In such a scenario I basically invalidated almost the entire content I am presenting!

Comparing this to (current) legendary items in WoW: if one legendary drops I might be relieved to finally get one (and be angry about it since it's a shitty one...) but I missed the reward stimulus up to the drop itself. Applied to my scenario, the player sees a dungeon as an annoying chore to finally get the chance of acquiring something. If the drops are not satisfying it could possibly be more demotivating thinking that that only chance to get something after such a chore was a waste of time.

So my question is the following: Even though loot explosions may be enojoyable at first they can degenerate into an annoyance (e.g. clicking a bazillion items on the floor). When thinking about making them less boring I end up with something that can be as frustrating in the end. How can I balance this?


texts: Explain Reciprocal Velocity Objects to me

texts:
This is follow-up on this question (Unit collision avoidance for RTS)

I'm developing an RTS. I'm having difficulty with collision detection... I looked up RVO and it seems like the correct solution, but I'm having difficulty understanding how it exactly works. Can someone explain the math behind RVO in comprehensible terms?

I tried compiling the RVO sample program but it won't compile in the latest version of Visual Studio. I'm stumped.


texts: How to detect collision in C# script not attached to any game object

texts:
I have public variables which I populate through the inspector. One script is attached to a single object and the other script has a gameObject array property. Please see below:

public class GamePlayScript : MonoBehaviour {

public BallScript ballScript;
public BrickGroupsScript brickGroupsScript;

// Use this for initialization
void Start () {

}

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

}
}

BrickGroupsScript contains an array of bricks which has a isBroken bool property. Also the above code is attached to an empty game object.
How can I detect when the ball game object is in contact/collided with a brick with isBroken = true?


texts: How can I create borders in an open-world game that don't feel artificial?

texts:
When creating open-world maps, a big issue to take into consideration is how "borders" of sorts are implemented. Obviously, in an open-world game, there shouldn't be invisible-wall borders, as it ruins immersion, and makes the game feel more "artificial".

I've done a little bit of research online and I've found the following methods:

Have the map be an island, surrounded by water that will kill you if you venture out too far.
Have the map be surrounded by mountains that are much too steep to climb over.
A combination of the above; mountains plus a body of water. The Elder Scrolls V: Skyrim does something like this but does have places where paths lead out of the world. (Thanks @Pharap)

These seem like the best methods but I'm wondering if there are any other methods that can be used to create borders in an open world without ruining immersion.


texts: Why is my variable seems to be non-existent in GameMaker?

texts:
I find myself stuck again with a peculiar issue that I don't really understand.

I'm currently trying to implement a "weapon" into a shooter game (using it as a learning project), as I was (and still am) a total noob in programming since two month ago.

Here is the code pointed by the error message. I'll explain what I'm trying to do right after.

  if instance_exists(Player)
  {
    nbtarget=instance_number(ENEMY);
    var i;
    for (i=0;i<nbtarget;i++)
    {
      Target= instance_find(ENEMMY,i)

      if Target != noone
      {
        if Target.size <3 {hit=Target}
      }
      if hit != noone
      {
       if point_distance(x,y,hit.x,hit.y)<startradius
        {
          repeat(2)
          {draw_lightning(x, y, hit.x, hit.y,and other parameters)}

          if damageTik = true
          {
            DMG = instance_create(hit.x,hit.y,Obj_dmg)
            DMG.dmg = Current_dmg
          }
        }
      }
    }
  }
  damageTik= false;
}
else
{
  instance_destroy()
}

So, the behavior I was looking for is a lightning that targets every enemy within a radius around the player, only if the enemy size is smaller than 3. Also, the targeted enemy takes a certain damage per second.
Everything is working fine.

But, since I implemented that, when I test it, it works fine for a certain amount of time, and then I get this error:

FATAL ERROR in
action number 2
of Draw Event
for object lightning_weapon:
Unable to find any instance for object index '103752' name '<undefined>' at gml_Object_lightning_weapon_DrawEvent_2 (line 15) -if point_distance(x,y,hit.x,hit.y)<startradius

From what I understand, it looks like the instance referred to in the variable hit has been destroyed before running the code at line 15. But I'm checking if such instance exists just before (hit != noone), so how can this be? Any pointer will be appreciated.

I try to move the "instance_destroy()" part of the enemy code out from the Step Event (of the enemy parent object), I tried to move it in the End Step Event, then in the Begin Step Event, I even tried to make a variable to tell the enemy he is dead and destroy it in the next step... Nothing fixed my issue.

Maybe the problem is not with that part of the code, but after half a day looking at this I can't find any new thing to try.

I also try to do the same with a ds_list, but failed to make it work (only one enemy is hit by the lightning):

var target = ds_list_create();
with(ENEMY)
{
  if (point_distance(PLAYER.x,PLAYER.y,ENEMY.x,ENEMY.y) < other.radius)
  ds_list_add(target,ENEMY.id);
}

nbtarget = ds_list_size(target)
var i;
for (i=0;i<nbtarget;i++)
{
  hit = ds_list_find_value(target,i)
  if hit != noone
  {
    {draw_lightning(x, y, hit.x, hit.y,other parameters...)}
    if fire = true
    {
      DMG = instance_create(hit.x,hit.y,ODamage)
      DMG.dmg = dmg
    }
  }
}
fire = false;

If I manage to make one or the other to work, it's perfect.


texts: How can set vibration option with my game in android?

texts:
I am using AndEngine to develop an Android game and I want vibration to be triggered when an enemy hits a player.

How can I implement this into my game?


texts: How to sync client and server at the first frame

texts:
I'm making a game where an authoritative server sends information to all clients about states and positions for objects in a 3d world. The player can control his character by clicking on the screen to set a destination for the character, much like in the Diablo series.

I've read most information I can find online about interpolation, reconciliation,  and general networking architecture (Valve's for instance). I think I understand everything but one thing seems to be missing in every article I read. Let say we have an interpolation delay of 100ms, server tickrate=50ms, latency=200ms; How do I know when 100ms has past on the client? If the server sends the first update on t=0, can I assume it arrives at t=200, therefore assuming that all packets takes the same amount of time to reach the client? What if the first packet arrives a little quick, for instance at t=150. I would then be starting the client with t=150 and at t=250 it will think it has past 100ms since its connect to the server when it in fact only 50ms has past.

Hopefully the above paragraph is understandable. The summarized question would be: How do I know at what tick to start simulating the client?

EDIT: This is how I ended up doing it: The client keeps a clock (approximately) in sync with the server. The client then simulates the world at

simulationTime = syncedTime - avg(RTT)/2 - interpolationTime

The round-trip time can fluctuate so therefore I average it out over time. By only keeping the most recent values when calculating the average I hope to adapt to more permanent changes in latency. It's still to early to draw any conclusion. I'm currently simulating bad network connections, but it's looking good so far.

Anyone see any possible problems?


texts:
I am looking for some advice on what would be a good way for users to play Asteroids over the network.

Its my first game and so far I have it working in 2D using polygons across a scrolling world in single player mode. Zoom in and out is also supported. Its not bad. I really want to develop it as a networked game as a learning vehicle. However, given all the work involved I want it to be a game people will enjoy playing.

My plan is that each player gets their own ship, exists in the same world and can shoot the same asteroids. The world can be big enough for ships to avoid each other. I want the players to also be able to attack other players ships.

Normally when playing in scrolling mode your ship stays in the middle of the viewport. This will limit the distance apart that ships can be if you are to see/shoot your opponent. Will this be a problem for the players or do these 2D multi player shooting games work well?


texts: How to handle global Data within a state machine setup? (C#)

texts:
I am currently building a turn-based framework (Unity,C#)

I was tired of my former tight-coupled systems and opted for a state machine this time, basically all components subscribe to the state-Enter and state-Exit event. I am aiming for scalability and structure.

But I ran into a problem. If the components cannot communicate directly, how to store and forward data in between states?

Example: The game starts with unit placement. The player has the option to select a unit in his pool via the ui and place it on the board.
The Unit-creation logic is and should(?) be handled inside the level script. How does it know where to create which unit?
Ive done a workaround with a static container class, with is basically my clipboard. The player assigns a grid cell for his selected unit and the game leaves the state.
While leaving the state the level scripts scans the clipboard and creates any assigned units.

But I feel like a cheated my attempt to really work strictly within a firm structure this time to guide the design process.

Is there a better way?


texts: Cascading Shadow Maps - Spotlight Projection

texts:
In all the cascading shadow map explanations I have read, the final projection into the shadow-map is done using an orthographic projection.
This makes sense for a directional light because a directional light "sees" things orthographically.

Spot lights on the other hand "see" things with a perspective transformation. Once we have our light space bounding volume, should we be performing the final projection into the shadow-map using the spotlight's projection matrix, rather than an orthographic projection matrix?

Perhaps I am missing the point here. Cascading shadow maps are necessary to provide shadow maps over large areas, thus because spotlights tend to have a very limited area of effect, perhaps cascading shadow maps are not necessary for spotlights.


texts: Why does my depth test fail on Nvidia cards?

texts:
I sent a test version of my in-development game to some friends, and they found out that the Depth Test in OpenGL does not work on Nvidia cards. I'm using LWJGL.

I use my own matrices and send them to the shader, and at the start of evey game loop I use

glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT ); // clear the display

On an Nvidia card, you can see mountains through other mountains and stuff. On my Radeon HD 6650M it works perfectly fine. Any ideas?

I don't have anything special in the shaders—just some basic lighting calculations. I dont touch the gl_FragDepth.

Here's a screenshot (with placeholder textures):

I use these calculations for the Projection Matrix:

public Matrix4f getProjectionMatrix() {
    // Setup projection matrix
    Matrix4f projectionMatrix = new Matrix4f();
    float fieldOfView = 40.0f;
    float aspectRatio = (float)Display.getWidth() / (float)Display.getHeight();
    float near_plane = 0.1f;
    float far_plane = 1000f;

    float y_scale = coTangent((float) Math.toRadians(fieldOfView / 2f));
    float x_scale = y_scale / aspectRatio;
    float frustum_length = far_plane - near_plane;

    projectionMatrix.m00 = x_scale;
    projectionMatrix.m11 = y_scale;
    projectionMatrix.m22 = -((far_plane + near_plane) / frustum_length);
    projectionMatrix.m23 = -1;
    projectionMatrix.m32 = -((2 * near_plane * far_plane) / frustum_length);
    projectionMatrix.m33 = 0;
    return projectionMatrix;
}


texts: Why Can't I duck reverb on the mix bus in Unity?

texts:
i'm surprised there is so little documentation on this issue. But i'm trying to duck the audio on all the mix buses in Unity so that you can clearly hear the VO of the game.

Now it works great except that I have some reverb zones in the game and any sound that plays in these reverb zones, the actual reverb itself is NOT DUCKED.

So the VO is accompanied with a huge wall of wishy washy muddy noise.

Anyone deal with this before? How can we deal with this?


texts:
I'm stumped trying to create a matching algorithm for my game.

I have a 2D grid like this for example:

0, 0, 0, 0, 0, 0

0, 1, 2, 2, 1, 0

0, 1, 1, 0, 0, 0

0, 0, 2, 0, 1, 0

0, 0, 0, 2, 1, 0

0, 0, 0, 0, 0, 0

Along with a list of patterns:

1, 2, 1

1, 1, 1

Where I am trying to find instances of the patterns in the grid, and the higher listed pattern has the higher priority if multiple patterns are found.
That would normally not be a problem if I were searching for them appearing purely horizontally or vertically. But I want to implement the search for them appearing in more than just straight lines like this (an "L shaped" example for the first pattern):

1, 2

0, 1

Some implementations I've tried included picking a grid element and trying to crawl from it to neighboring elements, but this has been problematic since each element has 4 neighbors and when you go to a neighboring element it has 4 more possible neighbors, and sometimes the crawling path curls in on itself resulting in duplicates. I feel like there is an easier and more efficient way to implement this that I am missing.

Is there any already well known algorithm that would fit this criteria? I have not been able to find something that fits these criteria on google. Any help would be appreciated.


texts: Calculate object coordinates from window coordinates using inverse projection matrix

texts:
What I am trying to to is placing 3D Objects (A Sphere) in the world when I click there.

I am using a perspective projection so the first step after calculating the canonical clip coordinates from window coordinates is to reverse the perspective transformation:

    void addSphere(int screenX, int screenY) {
    // invert y axis
    screenY = screenHeight - screenY;

    // determine depth of the pixel
    GLfloat z;
    glReadPixels(screenX, screenY, 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &z);

    // transform x and y to canonical clipping space
    GLfloat x = -1 + (screenX / (float)screenWidt) * 2;
    GLfloat y = -1 + (screenY / (float)screenHeight) * 2;
    std::cout << "<" << x << "," << y << "," << z << ">" << std::endl;

    // now we reverse the projection which means we have object coordinates
    // given the MODELVIEW Matrix is identity
    glm::vec4 center = glm::vec4(x, y, z, 1);
    center = inverseProjection * center;
    std::cout << glm::to_string(center) << std::endl;

    // add the sphere centered at the calculated position
    Sphere *sp = new Sphere(center);
    sphereList->push_front(sp);
}

The big question is what do I insert for the forth value for the center vector? As far as I see there is no method to get the transformed w value from the framebuffer.


texts: Bullet hits the object not in the center of the screen

texts:
When player shoot, the bullet fly to the center of the screen. But if player stay too close to some object, then bullet hits it not in the center, because it flies from the gun on the right side of the screen. How can I fix this?

 public Rigidbody projectile;
 public int speed = 50;
 public Transform startBulletPosition;

 void Update()
 {
     if (Input.GetButtonDown("Fire1"))
     {
         Rigidbody clone;
         clone = Instantiate(projectile, startBulletPosition.position, transform.rotation) as Rigidbody;
         var centre = new Vector3(0.5f, 0.5f, 0f);
         var ray = Camera.main.ViewportPointToRay(centre);
         clone.velocity = ray.direction * speed;
     }
 }

Edit 1


texts: In rendering pipeline，is there any order between depth test/alpha test and stencil test？

texts: So the order between them is important？Or the order just depends on hardware？I have no idea which one needs to come first.


texts: Image looks GOOD on the editor but BAD (blurry) on the HTML5 export

texts:
I have a red bar that looks good inside Unity editor, but when I export the build it looks very strange.
Any idea on how to fix this?

The image on the left is the one with the strange/bad looking red bar...


texts: How to place text centered on the player? XNA

texts:
As I can make a text of the size of this, it is centered taking reference of the player?

Right now the following happens:

I want:

code:

spriteBatch.DrawString(Font, player.Name, new Vector2(player.position.X, player.position.Y - 12), Color.White);

PS: Sorry for my English.


texts:
This seems like a simple question, but i'm having trouble searching the internet for it.

In XNA, during a collision detecting method, I would determin the minimum of some vectors.

// Get the minimum top point
Vector2 minTopPoint1 = Vector2.Min(topLeft1, topRight1);
// Get the minimum bottom point
Vector2 minBottomPoint1 = Vector2.Min(bottomLeft1, bottomRight1);
// Get the minimum of both the top and bottom points.
Vector2 minPoint1 = Vector2.Min(minTopPoint1, minBottomPoint1);

I switched over to making a C++ engine, and am trying to replicate the collision formula (Honestly, it's confusing enough, I just need to replicate it from XNA)
I made my own Vector2, and now I need to make this Min function.

So, what is the minimum or maximum of two vectors?
Is it just the magnitude of the two vectors measured against eatchother?
Is it the x and y values min/maxed somehow?


texts:
i was able to compile and link V8 against my game and code interpretation works fine. However I want to divide my code and the game loop should exist in one thread and the scripting engine should run in a second thread alongside my game loop. I am using SDL and therefore tried this code to spawn a new thread

SDL_CreateThread(ScriptingEngine::SpawnMain, NULL);

where the following code is my test scripting engine:

namespace ScriptingEngine {
    v8::HandleScope handleScope;
    v8::Handle<v8::ObjectTemplate> global = v8::ObjectTemplate::New();
    v8::Persistent<v8::Context> context;

    void Setup() {
            // TODO: bind functions to global
            // ...
            context = v8::Context::New(NULL, global);
    }

    int SpawnMain(void *arguments) {
            v8::Context::Scope scope(context);
            v8::Handle<v8::Script> script = v8::Script::Compile(
                    v8::String::New("'Hello World'")
            );
            v8::Handle<v8::Value> result = script->Run();
            context.Dispose();
            return EXIT_SUCCESS;
    }
}

However I get an error like Access violation reading location 0x00000000. in api.cc line 716: i::Isolate* isolate = env->GetIsolate();.

Has anyone a clue how I can fix this or what the exact problem is?


texts: I am trying to use Clojure to create an opengl window under Linux. Is there a tutorial on how to use GLX and X Window directly. I'd rather learn how to do this directly, which I already know how under Windows with win32 sdk, instead of relying on a wrapper.


texts: Parabolic Jump Libgdx Without Box2D and With Vectors

texts:
I have tried to write a jump method that sketches out a parabolic jump but it results in either no movement, or a jerky upward movement when I try to scale up dt. I have the following things defined:

    x = 0;
    y = 250;
    pos.set(x, y); // position of player
    velocity.set(2, 12); // player velocity
    gravity.set(0, -2); // player gravity

Then I have the key input processor:

private void handleInput(float dt)
{
    if(Gdx.input.isKeyPressed(Keys.D))
        x += velocity.x;

    if(Gdx.input.isKeyPressed(Keys.A))
        x -= velocity.x;

    if(Gdx.input.isKeyJustPressed(Keys.W))
        jump(dt);

    pos.set(x, y);
    bound.setPosition(pos);
}

This is the jump method which takes in a Gdx delta time method:

private void jump(float dt)
{
    y += velocity.y * dt;
    velocity.set(velocity.x, velocity.y + gravity.y);

    pos.set(x, y);
    bound.setPosition(pos);
}

This is all called in the update method which is called once per frame in the render method:

public void update(float dt)
{
    handleInput(dt);
    movement(dt);
    collision(dt);
}


texts: What are efficient strategies to support alternate spritesheets in Unity

texts:
Context

Let's suppose a classic card game, designed in Unity (say the latest release as of now, so 2018.2.16). Visible cards are GameObjects with SpriteRenderers (probably a Card prefab). One or several script objects are responsible of instantiating card objects as required, and inform each card of its current value; the card then does whatever is needed to display the correct image. Now, here is the twist: we would like to offer alternate sets of images for the cards (let say 10 designs); these alternate images would be included in the application itself (that is, on-demand content is outside the scope of this question).

Stating the obvious

This is clearly a case for spritesheets. So at design time, pictures of each card of a set (52 regular faces, 2 jokers and card's back) are layout in a single image file (that is, one image file per card-set design). So we have 10 spritesheets, each containing 55 sprites, and only one spritesheet (and therefore only one version of each of those 55 sprites) is to be in use at any given time. We want to avoid having unused images in RAM and/or on the GPU. Therefore, only the currently selected spritesheet should actually be loaded.

Question

So the question is: how to efficiently load, manage and use sprites in such situation?

Envisioned strategies

My first intuition would be to go for something along the line of Resources.loadAll<Sprite>("CardSets/CardSetName"). That is, each card set would be split in 55 sprites, stored in a directory specific to that card set. However, many sources, including some official documentation from Unity, discuss Resources as an old and undesirable subsystem, and recommend moving away from it. So let's consider other options...

Suppose I am very patient and would not bother manually linking (or scripting in the editor...) every single sprites of every card sets, that is all 55 * 10 sprites, to some GameObject(s) inside the editor... Would it be reasonable? Would spritesheets for non-selected card sets be loaded in RAM and/or on GPU from the moment we open the scene, or only the spritesheet of the currently selected spritesheet? What if each card set is associated with a specific prefab instead, and I only instantiate the prefab corresponding to the currently selected card set?

Alternatively, assuming that all spritesheets is packed using exactly the same layout, would it be possible/make sense to reuse the sprite objects themselves, and instead swap their texture image? Would that be any better? How would one get access to these textures without having all textures be preloaded at scene creation, and yet avoid Resources.loadAll()?

At last, what about sprite atlas? They seem a very good candidate for this problem, but the same questions goes as for texture replacements: how would one get access to these textures without having all textures be preloaded at scene creation, and yet avoid Resources.loadAll()?

And there might also be other strategies I am not aware of...

Question (again)

Now, this is a lot of subquestions, and I don't expect answers to all of these. Simply put, what would be a correct and efficient strategy to load, manage and use sprites in this example situation, based on current Unity's technology?

Note 1: I know that this question is similar to How can I dynamically load the correct sprite from a sprite sheet? . I however think that is is significantly different in that 1) Unity's technology has evolved a lot since 2014 (official recommendations are now to avoid Resources.LoadAll(), and Sprite Atlas have been recently added) and 2) that other question considered only one card set, so it doesn't posed the extra issue of reducing memory usage.

Note 2: I am not really making a card game; this is only an example that make it easier to explain and present the core concepts that I want to clarify here (that is, proper strategies regarding management of alternate spritesheets). Please do not suggest that I draw text labels instead of having several sprites, that is not an applicable solution.


texts: Same image in both eyes of VR HMD results in wrong 3D effect

texts:
I am trying to mod in VR support for a game without VR support via OpenVR as it proved to be the easiest one to implement with the least amount of issues, i don't think my issue is related to OpenVR but i am just asking for help.
The code i use for rendering the images to the HMD can be found below, i use ReShade for now as a base that has all DirectX functions hooked already so i can test things more easily.
_backbuffer variable is just a regular ID3D11Texture2D buffer received from the swap chain by using _swapchain->GetBuffer function.
vr::Texture_t leftEyeTexture = { _backbuffer.get(), vr::TextureType_DirectX, vr::ColorSpace_Auto };
vr::EVRCompositorError error1 = vr::VRCompositor()->Submit(vr::Eye_Left, &leftEyeTexture);

vr::Texture_t rightEyeTexture = { _backbuffer.get(), vr::TextureType_DirectX, vr::ColorSpace_Auto };
vr::EVRCompositorError error2 = vr::VRCompositor()->Submit(vr::Eye_Right, &rightEyeTexture);

if (error1)
{
std::cout << "[TF2VR] [ERROR] IInterfaces::IVR texture error: " << error1 << std::endl;
}

if (error2)
{
std::cout << "[TF2VR] [ERROR] IInterfaces::IVR texture error: " << error2 << std::endl;
}

So does anyone have any ideas on how do i solve this problem, some things i can think of are settings custom texture bounds with vr::VRTextureBounds_t in vr::VRCompositor()->Submit or/and settings vr::EVRSubmitFlags in the same function.
Normally you would just create two cameras, set their respective render targets, get their textures and use vr::VRCompositor()->Submit to render each frame independently, but i can't figure a way to do it in my case so i just submit same back buffer to both eyes.
Also, i have concerns that if i keep doing it that way and somehow fix the double-image effect the depth effect won't work properly (Although i hope i can fix that by applying some ReShade effects as i am using it as a framework)
And before someone will offer Depth3D effect for ReShade, i obviously tried that before, all it does in my case is just renders image 4 times instead of 2 (I tried tweaking parameters for that shader but with no success), it almost works without any effects in ReShade so i think i just have to tweak it on DirectX/OpenVR level, not with a custom shader.


texts: Unity yield WaitForSeconds() not working

texts:
I am new to Unity development. I started learning Unity by reading tutorials, demos, examples, and watching videos. And I am having some trouble with using this timer. Here is my code:

 void OnCollisionEnter(Collision colli){

    if (colli.collider.name == "Car") {
        Debug.Log("On Collision naz ~.~");
        Destroy(Car);
        Destroy(this.gameObject);
        GameObject clone = (GameObject) Instantiate(Bum, transform.position, Quaternion.identity);
        StartCoroutine(deleteObject(clone));
        // Just want to delete "clone" object after 1 second
    }
}
    IEnumerator deleteObject(GameObject bum){
        Debug.Log("chuan bi destroy naz ~.~"); // <-- run normally
        yield return new  WaitForSeconds(1.0F);
        Debug.Log("Destroy rui naz =,='");    //  <-- not display
        Destroy (bum);
    }

Why won't this object be destroyed after 1 second?


texts: Importing a windows project into android using cocos2d-x

texts:
What I am trying to do today is to import a full project to Android, but no tutorials are available for that that I have seen. My approach was to create a new android project, copy all the classes and resources in the folders and calling ./build_native.sh but I get an error because most of the files are not being included in the project. I tried opening the Android.mk and I can see why "LOCAL_SRC_FILES := AppDelegate.cpp \ HelloWorldScene.cpp" are the only files linked.

Should I manually modify the make file or can it be automated by some way I don't know?

Thank you.

UPDATE:

I manually added all files and headers to the make file and I get errors linking Box2D or cocosdenshion libraries.


texts: How to match user click and the sprite object position in libGDX framework

texts:
I am using libGDX Java framework for developing a practice game in Eclipse.

My game is in landscape mode and I am using sprite image for game assets. Actually I am trying to follow the Kilobolt Zombie Bird tutorial.

I have set orthographic camera like this:

cam = new OrthographicCamera();
cam.setToOrtho(true, 250, 120);

I have done this because my background texture region is of 250 x 120 px in the sprite image.

So basically my sprite image is small in size and it is getting scaled according to the device but all the computing is done relative to 250 x 140 px like for changing the position of the object I have defined Vector2 position = new Vector2(x, y); and if I write position.x = 260; the sprite will go outside the screen even if my device width is 500px.

Problem:

Now I have to make the moving sprite vanish when someone clicks on it (just imagine zombies moving around and if I click on them they die). So I am using the following code for matching user click coords with the object coords:

int x1 = Gdx.input.getX();
int y1 = Gdx.input.getY();
if(position.x == x1 && position.y == y1){
    // do something that vanish the object clicked
}

The problem is position.x and position.y returns the coords relative to the ortho cam width and height which is 250 x 120 px and the click coords are relative to the device width and height which maybe anything according to the device. Because of this even if I click right on the object the click coords and the object position coords have a huge difference in their values. So I would never get matching values.

Is there any solution for this or am I doing it wrong?


texts: How can non-indie devs stop reinventing the wheel?

texts: It seems like the status quo in the games industry is to write most software in-house, maybe excluding the engine if you use one of the dozen or so big ones. Before working here I was mostly an open-source developer, so this mindset seems downright crazy to me. Is there any good way we can all stop building things like log viewers, network diagnostics, and patching systems?


texts:
I had issues finding information about decals, so maybe this question will help others. The implementation is for a forward renderer.

Could somebody confirm if i got decal implementation right?

You define a cube of any dimension that'll define the projection
volume in common space. You check for triangle intersection with the
defined cube to recieve triangles that the projection will affect.
You clip these triangles and save them.
You then use matrix tricks to calculate UV coordinates for the saved
triangles that'll reference the texture you're projecting.
To do this you take the vectors representing height, width and depth
of the cube in common space, so that f.e. the bottom left corner is
the origin.
You put that in a matrix as the i, j, k unit vectors, set the
translation for the cube, then you inverse this matrix.
You multiply the vertices of the saved triangles by this matrix, that way you get
their coordinates inside of a 0 to 1 size cube that you use as the UV
coordinates.
This way you have the original triangles you're projecting onto and
you have UV coordinates for them (the UV coordinates are referencing
the texture you're projecting).
Then you rerender the saved triangles onto the scene and they
overwrite the area of projection with the projected image.

Now the questions that i couldn't find answers for. Is the last point right? I've never done software clipping, but it seems error prone enough, due to limited precision, that the'll be some z fighting occuring for the projected texture. Also is the way of getting UV coordinates correct?


texts: Getting player cube to move left or right in relation to camera based on camera's rotation

texts:
Right now I'm trying to make the player cube move left, right, up and down in relation to the camera's rotation and position. I figured what I could do is create an empty game object, make the main camera the parent, and then get the vector pointing from the camera's child to another game object that follows the cube's exact position, and that would give me the direction the cube should roll towards.

I have my example in profile view, but in 3D view the camera should be facing the cube with the cube at the center.

So I have the following line of code code:

Vector3 forwardVector = (position1.transform.position - position2.transform.position).normalized;

If you look at the image on the right hand side, I Debug.GetLine'd the resulting vector from the cube's position and ended up with a vector pointing down. In theory though, it should be pushing off to the right hand side. Here's the rest of the code:

Vector3 perpendicularVector = Vector3.Cross (Vector3.up, resultant).normalized;

if (Input.GetKey (KeyCode.UpArrow))
{
    cube.rigidbody.AddForce ( forwardVector * moveSpeed);
}
if (Input.GetKey(KeyCode.DownArrow))
{
    cube.rigidbody.AddForce ( forwardVector * -moveSpeed);
}
if (Input.GetKey (KeyCode.LeftArrow))
{
    cube.rigidbody.AddForce ( perpendicularVector * -moveSpeed);
}
if (Input.GetKey (KeyCode.RightArrow))
{
    cube.rigidbody.AddForce ( perpendicularVector * moveSpeed);
}

As a result, when I press the up arrow key, I end up with the cube flying upwards toward the sky, and the down key brings it back down towards the plane, but my intention is for the vector to move along the XZ plane.

Also, with this line of code, I was hoping to get the line perpendicular to my intended vector and Vector3.up, but I naturally get wonky results from that.

Vector3 perpendicularVector = Vector3.Cross (Vector3.up, resultant).normalized;

If there's an easier method to achieving my goals, that's fine, but it would be nice too to figure out why the vector is pointing down instead of to the right.

It's also might be worth noting that the camera already successfully rotates around the player cube.


texts: SDL_Image setup problems on windows / mingw 64 / eclipse

texts:
I've been a software developer for a while, but I haven't done C++ in a long time and I thought I'd try it out with some game developement.  I'm following the tutorial on youtube for Remaking Cavestory in C++ (great tutorial so far).  I'm on Episode 4.  I liked the sound of doing some 64 bit dev, so after a bunch of struggling I got SDL2 to work, scouring the internet and some trial & error I got it set up using the x86_64 libraries with a MinGW-w64 installation.  I opted not to copy lib and include files into mingw as suggested by some guides.  Instead, I figured I could "point" eclipse at the proper folders and everything should work.  This was true up until trying to integrate the SDL_Image library.  I have everything set up such that SDL.h is found by the compiler, and SDL_image.h is found by the compiler.  That is, the SDL.h and SDL_image.h as referenced by my project code are fine.  The problem is the compiler fails on SDL_image.h because IT references SDL.h and that reference is apparently bad.

Windows 10 64 bit (pro I think, though I doubt it matters)
eclipse Neon.2 (4.6.2)
MinGW-w64 (I think 4.3.0)
SDL2 (2.0.5)
SDL_image (2.0.1)

Here's where all of my files are:

C:\MinGW-w64\mingw64
C:\MinGW-w64\mingw64\bin
C:\MinGW-w64\mingw64\include
C:\MinGW-w64\mingw64\lib
C:\MinGW-w64\mingw64\x86_64-w64-mingw32
C:\MinGW-w64\mingw64\x86_64-w64-mingw32\bin
C:\MinGW-w64\mingw64\x86_64-w64-mingw32\include
C:\MinGW-w64\mingw64\x86_64-w64-mingw32\lib

F:\Dev\SDL2-2.0.5\x86_64-w64-mingw32
F:\Dev\SDL2-2.0.5\x86_64-w64-mingw32\bin
F:\Dev\SDL2-2.0.5\x86_64-w64-mingw32\include
F:\Dev\SDL2-2.0.5\x86_64-w64-mingw32\lib

F:\Dev\SDL2_image-2.0.1\x86_64-w64-mingw32
F:\Dev\SDL2_image-2.0.1\x86_64-w64-mingw32\bin
F:\Dev\SDL2_image-2.0.1\x86_64-w64-mingw32\include
F:\Dev\SDL2_image-2.0.1\x86_64-w64-mingw32\lib

In eclipse I have the following configured:

Project -> Properties -> C/C++ Build -> Settings -> Tool Settings -> GCC C++ Compiler -> Includes:

"${workspace_loc:/cavestory-development/source/headers}"
"F:\Dev\SDL2-2.0.5\x86_64-w64-mingw32\include"
"F:\Dev\SDL2_image-2.0.1\x86_64-w64-mingw32\include"

Project -> Properties -> C/C++ Build -> Settings -> Tool Settings -> MinGW C++ Linker -> Libraries:

(top box: Libraries (-l))

SDL2
SDL2main
SDL2_image

(bottom box: Library search path (-L)

"F:\Dev\SDL2-2.0.5\x86_64-w64-mingw32\lib"
"F:\Dev\SDL2_image-2.0.1\x86_64-w64-mingw32\lib"

Project -> Properties -> C/C++ General -> Paths and Symbols -> Includes -> GNU C++:

/cavestorye-development/source/headers
F:\Dev\SDL2-2.0.5\x86_64-w64-mingw32\include
F:\Dev\SDL2_image-2.0.1\x86_64-w64-mingw32\include

Project -> Properties -> C/C++ General -> Paths and Symbols -> Libraries:

SDL2
SDL2main
SDL2_image

Project -> Properties -> C/C++ General -> Paths and Symbols -> Library Paths:

F:\Dev\SDL2-2.0.5\x86_64-w64-mingw32\lib
F:\Dev\SDL2_image-2.0.1\x86_64-w64-mingw32\lib

I've also copied all of the DLLs from these two folders into my Debug (where my .exe is created)

F:\Dev\SDL2-2.0.5\x86_64-w64-mingw32\bin
F:\Dev\SDL2_image-2.0.1\x86_64-w64-mingw32\bin

When I build the project, I get the following error:

F:\Dev\SDL2_image-2.0.1\x86_64-w64-mingw32\include/SDL2/SDL_image.h:27:17: fatal error: SDL.h: No such file or directory

It seems that when the compiler looks at SDL_image.h, it sees that THAT file includes SDL.h, which it can't find.  Again, this worked when I was only including SDL2, and broke when I tried to include SDL2_image because the image library references the normal library in a way that can't be reconciled.

Has anyone dealt with this before?  Let me know if I've left out any pertinent information.


texts: Loading texture from Resources folder not working C#

texts:
So I want to load different textures for my game object when different conditions are met. There are no errors when I compile this code. The colours change according to the condition, that part does work. The textures do not load though. The textures are stores in a Resources folder in Unity. The first code works but the second does not. Why is this the case?
Below is my code:

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

public class Level4 : MonoBehaviour
{

    Material _mat;
    GameObject Sphere;

    // Use this for initialization
    void Start()
    {
        Sphere = GameObject.FindWithTag("Player");
        //Material _mat = GameObject.FindWithTag("Player").GetComponent<Renderer>().material;

    }

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

            if (Input.GetKeyDown(KeyCode.UpArrow))
            {
                Renderer _rend = GetComponent<Renderer>();
                Material _mat = _rend.material;
                _rend.material.mainTexture = Resources.Load("face1") as Texture;
                _mat.color = Color.red;
            }
        }
        catch (System.Exception)
        {
        }
    }
}

this is the second code that does not work:

    using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO.Ports;
public class arduino : MonoBehaviour
{

    SerialPort sp = new SerialPort("//.////COM6", 9600);// Com port and the baud rate of the arduino
    Material m_Material;
    GameObject Sphere;

    void Awake()
    {
        Sphere = GameObject.FindWithTag("Player");
        m_Material = GameObject.FindWithTag("Player").GetComponent<Renderer>().material;
    }
    void Start()
    {
        if (!sp.IsOpen)
        { // If the erial port is not open
            sp.Open(); // Open
        }
        sp.ReadTimeout = 250; // Timeout for reading
    }

    // Update is called once per frame
    void Update()
    {
        if (sp.IsOpen)
        { // Check to see if the serial port is open
            try
            {

                string portreading = sp.ReadLine(); // get the string output of the serial port
                float amount = int.Parse(portreading);

               if ((amount > 251f))
                {

                    Renderer _rend = GetComponent<Renderer>();
                    m_Material = _rend.material;
                    _rend.material.mainTexture = Resources.Load("face1") as Texture;
                    m_Material.color = Color.red;

                }
            }
            catch (System.Exception)
            {

            }

        }

    }
}


texts: Is permission needed to use a living famous person as a character in a game?

texts: If I wanted to sell an iphone game in which you play as a famous person, would that require permission from the famous person?


texts: OpenGL - must I always preserve data that is uploaded to a VBO?

texts: If I load my vertex data from a file into a buffer in RAM, and then upload this to the GPU (say, to a static VBO so no need to modify the data), do I need to keep that buffer around? If not, how do I know that the upload is complete?


texts: What is the purpose of indices in 3D rendering?

texts:
Suppose you were creating a 3D cube in OpenGL. You implement the necessary vertex data for the object (cube). What would be the point of using indices?

 void CreateCube()
        {
            const Vertex VERTICES[8] =
            {
                { { -.5f, -.5f,  .5f, 1 }, { 0, 0, 1, 1 } },
                { { -.5f,  .5f,  .5f, 1 }, { 1, 0, 0, 1 } },
                { {  .5f,  .5f,  .5f, 1 }, { 0, 1, 0, 1 } },
                { {  .5f, -.5f,  .5f, 1 }, { 1, 1, 0, 1 } },
                { { -.5f, -.5f, -.5f, 1 }, { 1, 1, 1, 1 } },
                { { -.5f,  .5f, -.5f, 1 }, { 1, 0, 0, 1 } },
                { {  .5f,  .5f, -.5f, 1 }, { 1, 0, 1, 1 } },
                { {  .5f, -.5f, -.5f, 1 }, { 0, 0, 1, 1 } }
            };

            const GLuint INDICES[36] =
            {
                0,2,1,  0,3,2,
                4,3,0,  4,7,3,
                4,1,5,  4,0,1,
                3,6,2,  3,7,6,
                1,6,5,  1,2,6,
                7,5,6,  7,4,5
            };

    //....

    glBufferData(GL_ARRAY_BUFFER, sizeof(VERTICES), VERTICES, GL_STATIC_DRAW);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(INDICES), INDICES, GL_STATIC_DRAW);

In the above example, a cube is created with the necessary vertices in world space. What is the relevance for the indices?


texts: How to handle player actions in a multithreaded gameserver

texts:
I'm working on a multiplayer game, and today I implemented basic "spatial hashing" in my entity-component-system.

Before implementing that algorithm, I was sending players actions to all connected players :

public void onPlayerMovement()(auto ref PlayerMovementMessage message, ClientSocket socket)
{
    this.m_gameServer.sendToAll(message);
}

My code is now :

public void onPlayerMovement()(auto ref PlayerMovementMessage message, ClientSocket socket)
{
    auto entity = this.m_gameServer.findEntity(socket);

    auto nearbyEntities = this.m_gameServer.world.getNearbyEntities(entity.get!PositionComponent().bucket)
        .filter!(e => e.hasComponent!PlayerComponent()).array();

    if(nearbyEntities.length)
    {
        this.m_gameServer.sendTo(nearbyEntities, message);
    }
}

As you can see im now calling this.m_gameServer.world.getNearbyEntities() from SpatialHashingSystem.d to get nearby players.

onPlayerMovement function is called by class GameServer.d in a new thread, so it might be called before SpatialHashingSystem.d executes his algorithm,
therefore calling getNearbyEntities() directly returns invalid data.

What can I do at this point ? Event system ? isnt that bad for a real time game ?

Thanks


texts: How to Change default Mouse pointer on emulator in Android?

texts: I want to change default mouse pointer in Android emulator. I want to change it for my game to use different type of cursor.I am using AndEngine for my game development. Is there nay way to change default mouse cursor for my Application. Thanks in Advance


texts: How to make player stay on a moving object

texts:
I've made an obstacle course with various moving parts to test out movement of a player. In the obstacle course there is a section where there are multiple cubes moves from side to side, and you have to jump from one to the other. But regardless of their speed, I can't seem to get the player to stay on top of any of the moving cubes. I have no clue how to fix this my only guess would be to use materials, but I can't apply any to the character controller. I appreciate any suggestion that you can give. Also the movement is done as an animation that I created in unity in the animation window.

Thanks, Nova


texts: XNA HLSL - what happens if I grab a pixel outside a texture?

texts: I'm using the tex2D function of HLSL, and I am wondering what will happen if I try to grab a pixel from a pixel coordinate outside of my texture (as an example 1.1). Will it clamp? Will it repeat the texture and grab something else? Will it return transparent?


texts: Game states affecting each other's objects

texts:
If I had given this question any other title it would have immediately looked like a dupe of this one. Although that has some nice ideas none of the answers actually address what I need.

I'm refactoring my game state system a bit. I already have a stack system, not to share data, but so you can leave a pause menu and return to gameplay as it was. There is also a transition type that clears the stack completely, so you can go from the title, to a menu, to in game, and those aren't stacked on each other.

I have three big state types (handlers) right now: gameplay, menus, and cutscenes. The latter two have a lot in common so they share a base class. I'm stuck right now because of how they handle entities (gameplay objects), which all three can use.

Many games have cutscenes that don't leave gameplay, they just take control and start puppeteering the characters currently on the screen. My handlers currently have their entities separate from each other, and there's no data sharing. The only affect they can have on each other is deciding whether the previous one should keep updating / drawing or not. I need to refactor things so that I can support that kind of cutscene when it's pushed on top of the gameplay state.

How should I organize my states so that they can share entities?
I'm considering splitting my handlers in half, one side to hold objects, the other for logic to manipulate those. Then I could mix and match them, or just swap one logic for another without changing out the data. Will this work? Maybe another approach is better.

Again, I know this sounds a lot like the other question but those answers were either things I'm already doing or didn't match my situation.


texts:
In my resources folder structure I have myself a file, now in the unity editor this file is a Texture Type Sprite (2D and UI), now when I attempt to run this code in one of my scripts

var icons = Resources.LoadAll<Sprite>("Images/BuffIcons");

My icons variable is empty, now if I change the line above to

var icons = Resources.LoadAll("Images/BuffIcons");

It comes back with an array which has a Texture2D and then multiple Sprite objects. Now why can't I cast the objects to a Sprite?

Also just for your information the Sprite (2D and UI) is a Multiple sprite so this sprite in total has like 42 different sprites. It seems to me the sprite which holds all the other sprites is classed as a Texture2D and then all the sprites inside of the Texture2D are Sprites. How can I just tell the Resources.LoadAll to load the sprites?

Basically the same problem as this user http://answers.unity3d.com/questions/900990/assetdatabaseloadallassetsatpath-not-loading-asset.html however the answers provided don't work for me either :(


texts: How to deal with "Scrooge McDucks" in my fixed-currency-amount game?

texts:
I'm currently working on a very small scale MMO game planned to support approximately hundred players per server, but we're having trouble with our economical model.

For various reasons we have decided to go with a fixed-currency-amount system; meaning that there is only a certain amount of "gold" that can ever exist in the game at the same time. In this early play-testing version (9 players) that amount is 9000 gold but we are planing to have around 1 million gold per server (100 players).

A brief example how this system works:

At a certain point in time this is how the gold amounts may look in the game.

| Max Gold | Bank | Shopkeeper | Player A | Player B |
| 100      | 90   | 0          | 5        | 5        |

Player A sells 2 gold worth of loot to the Shopkeeper.
The Shopkeeper has 0 gold and so he "borrows" 2 gold from the bank (only NPCs can).
Player A sells 3 gold worth of loot to Player B.
Player B pays from their wallet.
Player A buys a sword for 5 gold from the Shopkeeper.
Player A pays from their wallet.
Now we have:

| Max Gold | Bank | Shopkeeper | Player A | Player B |
| 100      | 88   | 5          | 5        | 2        |

Repeat the above loot-and-sell step a few times and you may end up here:

| Max Gold | Bank | Shopkeeper | Player A | Player B |
| 100      | 0    | 27         | 59       | 14       |

Player A tries to sell a 30-gold item to the shopkeeper, but cannot because the Shopkeeper only has 27 gold and cannot borrow from the (now empty) bank.
Player A have to lower their selling price, trade wares in return, or wait until the Shopkeeper gains money in other ways.

This system is working fine – for the most part. Recently one of our testers did something that completely broke our system; they sold, traded, and haggled their way into owning about 60% of the total currency amount available in the game then refused to use it (becoming the RPG equivalent of Scrooge McDuck). This caused a big problem because suddenly approximately 5500 gold out of our 9000 total was unusable.

Of course in the release of the game one player owning 60% of all money is unlikely, but 60 players each owning 1% of all money can cause the same effect. We have considered deleting old characters and returning their money to the "bank" but decided against it since if a player comes back and his character is deleted I would imagine they would be quite sad (especially if it was super rich!).

So on to the actual question; how can we avoid this happening and how can we limit the damages caused by this?


texts:
I wasn't sure what to call this question I might update it with a more suitable title.
The issue I have here is more conceptual than in-depth code, and as such this might be subject to debate. However it is something I have trouble within my design and architecture so I hope that you will be able to help me :)
Let me set the scene:
In my game I have two sets of AI types:

Player controlled AI (classic RTS controlling your units around the game world)
Computer AI (lack of better name) which means the computer enemy controlling his units around the map

These two share a lot of similarities such as:

Navigation
Animation controllers
Being in a group (explanation below)

Groups
All AI units (both player and enemy) are added to a group that "orders" the units to do something collectively
Now, this is where some of the differences appear. The player will control the unit movement and goals by using inputs (click on the screen)
But the enemy AI is using a Goal system that I have created:

The basics of this system are that throughout the map there will be certain points of interest (Goals) each of these goals will have a priority and a Condition method when the Group is choosing a new goal it asks the Planner and it returns the highest priority goal where the condition is met
Using a state machine I can control each individual unit to "obey" the goal of the group usually it looks something like this:

Now the Player controlled units state machine looks really similar:

Because of the different values and the nature of their input, these cannot share the same state machine states as the data a certain state/action is expecting will differ
So my question is: Should Iseparate these types of AI from each other hereby resulting in making code that seems similar but will differ slightly, or should I somehow ensure that actions can be used across the different AI types?
Is there something in my design that I have overlooked? (Is there a better way of doing this)


texts:
I have been looking for the advantages and disadvantages of both overlap testing and intersection testing, but I was only able to find a few disadvantages; overlap testing may fail for objects moving very fast, and intersection testing makes assumptions that may lead to wrong predictions, such as a constant speed and zero accelerations.

What are the advantages and disadvantages of overlap testing and intersection testing?


texts: In unreal engine, what's the difference among "set global time dilation" and "set current time dilation" and "set custom time dilation"?

texts: what's the different effect of these three functions, thanks!


texts: How to resolve OBB collision penetration?

texts:
I would think this is a common issue, but I couldn't find an answer that helped me. Help would be appreciated.

In my game I have rectangular objects. They have rotating bounding box, aka not AABB but boxes that rotate with the entity and always match it's exact shape (I think it's called OBB).

When two objects collide, they often penetrate each other a little:

My question is, how can I move the objects out of each other? (Before performing the 'actual' collision handling, i.e. setting velocities etc).


texts: How to centralize stat/feat/equipment related changes in an RPG?

texts:
I have a game with an RPG system where derived stats, like HP,armor, etc depend on a variety of components: armor, stats and feats. I'm running into an issue where the code to change derived metrics gets spread throughout the game - some is in the inventory module, another in stats module, another in buffs module.

How can I centralize and ensure accuracy of all my stat/equipment related changes to the character?

I thought that I can just create a "mega method" within the character class that would recalculate everything any time I change anything within the formula, but I don't know if this recalculate everything is a good practice, or if there are potential pitfalls with this approach down the road.

One of the complications with the complete rebuild that I see is that I will have to keep track of the player's HP and properly restore it after rebuild is complete.


texts: How to make platforms spawn without touching other platforms

texts: So I am making a doodle jump like game where there are platforms scrolling by but right now how I have platforms spawning is completely random. I would like the platforms to be spread apart so they weren't touching but don't have much of an idea to implement it. I was thinking of using the distance formula to check to make sure that they were apart but I was thinking that as I was creating those object I would have to check with all the previous objects before to see if they weren't colliding. Does anyone have any ideas on how to make this work efficiently?