texts:
I am having trouble with the basic logic of this solution:
Xna: Splitting one large texture into an array of smaller textures
in respect to my specific problem (specifically, I'm looking at the second answer.)

How can I use my source rectangle that I already use for drawing to create a new Texture2D?

spriteBatch.Draw(CurrentMap.CollisionSet, currentMap.CellScreenRectangle(x, y),
      CurrentMap.TileSourceRectangle(currentMap.MapCells[x, y].TileDepths[4]),
      Color.FromNonPremultiplied(0,0,0, 45), 0.0f, Vector2.Zero, SpriteEffects.None, 0.91f);

I know I want a method that I started so:

//In Update Method of say the player's character.

Texture2D CollisionTexture = ExtractTexture(MapManager.CurrentMap.CollisionSet, MapManager.TileWidth, MapManager.TileHeight);

// In MapManager Class who knows everything about tiles that make up a level.
    public Texture2D ExtractTexture(Texture2D original, int partWidth, int partheight, MapTile mapCell)
            {
                var dataPerPart = partWidth * partheight;
                Color[] originalPixelData = new Color[original.Width * original.Height];
                original.GetData<Color>(originalPixelData);
                Color[] newTextureData = new Color[dataPerPart];
                original.GetData<Color>(0, CurrentMap.TileSourceRectangle(mapCell.TileDepths[4]), originalPixelData,  0, originalPixelData.Count());
                Texture2D outTexture = new Texture2D(original.GraphicsDevice, partWidth, partheight);
            }

I think the problem is I'm just not understanding the overload of Texture2D.GetData<>

Part of my concern is creating an array of the whole texture in the first place.  Can I target the original texture and create an array of colors for copying based on what I already get from the method TileSourceRecatangle(int)?


texts: Error X3650 when compiling shader in XNA

texts:
I'm attempting to convert the XBDEV.NET Mosaic Shader for use in my XNA project and having trouble.  The compiler errors out because of the half globals.

At first I tried replacing the globals and just writing the variables explicitly in the code, but that garbles the Output. Next I tried replacing all the half with float vars, but that still garbles the resulting Image.

I call the effect file from SpriteBatch.Begin().

Is there a way to convert this shader to the new pixel shader conventions? Are there any good tutorials for this topic?

Here is the shader file for reference:

/*****************************************************************************/
/*
File: tiles.fx
Details: Modified version of the NVIDIA Composer FX Demo Program 2004
Produces a tiled mosaic effect on the output.

Requires:  Vertex Shader 1.1
           Pixel Shader 2.0

Modified by: bkenwright@xbdev.net (www.xbdev.net)

*/
/*****************************************************************************/

float4 ClearColor : DIFFUSE = { 0.0f, 0.0f, 0.0f, 1.0f};
float ClearDepth = 1.0f;

/******************************** TWEAKABLES *********************************/
half NumTiles = 40.0;

half Threshhold = 0.15;

half3 EdgeColor = {0.7f, 0.7f, 0.7f};

/*****************************************************************************/

texture SceneMap : RENDERCOLORTARGET <
float2 ViewportRatio = { 1.0f, 1.0f };
int MIPLEVELS = 1;
string format = "X8R8G8B8";
string UIWidget = "None";
>;

sampler SceneSampler = sampler_state {
texture = <SceneMap>;
AddressU  = CLAMP;
AddressV  = CLAMP;
MIPFILTER = NONE;
MINFILTER = LINEAR;
MAGFILTER = LINEAR;
};

/***************************** DATA STRUCTS **********************************/

struct vertexInput {
half3 Position : POSITION;
half3 TexCoord : TEXCOORD0;
};

/* data passed from vertex shader to pixel shader */
struct vertexOutput {
half4 HPosition : POSITION;
half2 UV        : TEXCOORD0;
};

 /******************************* Vertex shader *******************************/

vertexOutput VS_Quad( vertexInput IN)
{
vertexOutput OUT = (vertexOutput)0;
OUT.HPosition = half4(IN.Position, 1);
OUT.UV = IN.TexCoord.xy;
return OUT;
}

/********************************** pixel shader *****************************/

half4 tilesPS(vertexOutput IN) : COLOR {
half size = 1.0/NumTiles;
half2 Pbase = IN.UV - fmod(IN.UV,size.xx);
half2 PCenter = Pbase + (size/2.0).xx;

half2 st = (IN.UV - Pbase)/size;
half4 c1 = (half4)0;
half4 c2 = (half4)0;
half4 invOff = half4((1-EdgeColor),1);
if (st.x > st.y) { c1 = invOff; }
half threshholdB =  1.0 - Threshhold;
if (st.x > threshholdB) { c2 = c1; }
if (st.y > threshholdB) { c2 = c1; }
half4 cBottom = c2;
c1 = (half4)0;
c2 = (half4)0;
if (st.x > st.y) { c1 = invOff; }
if (st.x < Threshhold) { c2 = c1; }
if (st.y < Threshhold) { c2 = c1; }
half4 cTop = c2;

half4 tileColor = tex2D(SceneSampler,PCenter);
half4 result = tileColor + cTop - cBottom;
return result;
}

/*****************************************************************************/

technique tiles
{
pass p0
{
    VertexShader = compile vs_1_1 VS_Quad();
    ZEnable = false;
    ZWriteEnable = false;
    CullMode = None;
    PixelShader = compile ps_2_0 tilesPS();
}
}


texts: Create a physics body with hole : bullet physics

texts:
I am writing an iOS game, using bullet for physics, blender to create models, cocos3d as the game engine.

I have a model like this

Basically there is a plane, with a hole, and a UVSphere. Both were created in blender. What I am trying is to create a physics body along the vertices of the plane. So that when the UVSphere goes over the hole, it should fall through.

I am using btBvhTriangleMeshShape to create physics body along the vertices of this plane. code is given below

//GPlane stands for groundPlane :)
CC3MeshNode* gPlaneNode  = (CC3MeshNode*)[self getNodeNamed:@"GPlane"];

/*Get Vertex and indices data out from the .pod*/
float *gVertexData       = (float*)((CC3VertexArrayMesh*)gPlaneNode.mesh)
                                .vertexLocations.vertices;
GLushort* gIndices       = (GLushort*)((CC3VertexArrayMesh*)gPlaneNode.mesh)
                                .vertexIndices.vertices;
int gIndiceCount         = ((CC3VertexArrayMesh*)gPlaneNode.mesh)
                                .vertexIndices.vertexCount;

/*Create triangle mesh*/
btTriangleMesh* gTriangleMesh = new btTriangleMesh();
for (int i = 0; i < gIndiceCount; i+=3)
{
   unsigned int index1 = gIndices[i] * 6;
   unsigned int index2 = gIndices[i+1] * 6;
   unsigned int index3 = gIndices[i+2] * 6;
   gTriangleMesh->addTriangle(
      btVector3(gVertexData[index1] , gVertexData[index1+1], gVertexData[index1+2]),
      btVector3(gVertexData[index2] , gVertexData[index2+1], gVertexData[index2+2] ),
      btVector3(gVertexData[index3] , gVertexData[index3+1], gVertexData[index3+2]));
}

/*Create  a rigid body using this triangle mesh*/
btBvhTriangleMeshShape *gTriMeshShape   =   new
                          btBvhTriangleMeshShape(gTriangleMesh,true);
gTriMeshShape->setMargin(0.1);
btDefaultMotionState *groundMotionState =
                new btDefaultMotionState(btTransform(btQuaternion(0,0,0,1)
                                           ,btVector3(0,0.0,0)));
btRigidBody::btRigidBodyConstructionInfo groundRigidBodyCI(0
                   ,groundMotionState,gTriMeshShape,btVector3(0,0,0.0));
groundRigidBodyCI.m_restitution = 0.3;
btRigidBody *groundRigidBody = new btRigidBody(groundRigidBodyCI);
dynamicsWorld->addRigidBody(groundRigidBody);

And I am adding the sphere to the scene like this

sphereNode    =   (CC3MeshNode*)[self getNodeNamed:@"Sphere"];
btCollisionShape *fallShape = new btSphereShape(1);
btDefaultMotionState *fallMotionState = new btDefaultMotionState(btTransform(
           btQuaternion(sphereNode.location.x,sphereNode.location.y
              ,sphereNode.location.z,1), btVector3(0,0,0)));
btScalar mass = 1.0;
btVector3 fallInertia(0,0,0);
fallShape->calculateLocalInertia(mass, fallInertia);
btRigidBody::btRigidBodyConstructionInfo fallRigidBodyCI(mass
                      ,fallMotionState,fallShape,fallInertia);
fallRigidBodyCI.m_restitution = 1.0;
fallRigidBody = new btRigidBody(fallRigidBodyCI);
fallRigidBody->setDamping(0.3,0.8);
dynamicsWorld->addRigidBody(fallRigidBody);

To view the physics body, I use bullet physics debug drawing method and this is how it is drawn

As far as I can tell, physics body looks fine, the hole is there alright.

My problem

It is simple. My ball just slide over the hold instead of falling through it. I expect with a mass and negative Y gravity, the ball to fall through the hole.

Ball is falling of the edge of the plane alright. So gravity is there.

Any idea?


texts: How to store references to scene objects in prefabs?

texts:
i am instantiating a few game objects in my scene using prefabs and i would like to attach a script to some of them to do something at a certain time but for that i need to reference to scene objects and its not allowing me. anyone know why? and whats the workaround?

i can pull those prefabs into my scene and use them as game objects but that would destroy the idea of prefabs isn't?


texts: Unity 5.x Network Synchronization Concepts

texts:
Bear with me, It will be long read^^

I am working on the new Unity Networking system. I was using Photon and old (legacy) unity network API's before. But as it seems there are some good benefits of the new system than the previous ones, so I want to stick with it. (Despite of it being uncompleted)

But there are some points that doesn't make sense to me with the API. Data Sync for example.
So, in the old systems (both in Photon and legacy unet) we had functions called OnPhotonSerializeView or OnSerializeNetworkView depending on which API we use. Both API's are very similar as you may know. So in these functions we could send and recieve data between clients and server. Which makes sense, and was really usefull.

But aperantly they changed this concept, (or it still exists, and i couldn't find it)

There is a new thing called [SyncVar], which syncs the data "ONLY" from server to client automatically. (Which really, literally doesn't make sense, I mean why not sync both server to client AND client to server? That would make everything much easier)

According to the documents, you can ONLY send data from client to server by using [Command]'s. Which is basically (as far as I understand), "one way" version of old good [RPC] calls. Instead of calling function in all other clients, it calls it in the server.

So, you can send data to server with function parameters like the way we did it with the old [RPC]'s before. Which is usefull on point but If this is the only way to send data to server, then it doesn't make any sense to me..

I mean there are variables that needs to be kept synced all the time, back and forth, like position or rotation vectors. And sending them with [Command] calls, contradicts with the concept of network framework in my mind. We used to avoid this kind of situation before, right? Why make it the obligation now?

Or are there simply any other ways to send data from client to server that I couldn't find yet?
There is a custom serialization with the [SyncVar], with OnSerialization and OnDeserializaton functions. Which really looks like the good old OnSerialize functions but apperantly it's diffrent as it does what the [SyncVar] does.
OnSerialization is only called on server, and Deserialization is only called on client. So we can only send from server to client even with it.

If [Command] is the only way to send data to server, please say so. And clarification about why this concept is reasonable would be really nice.

Please enlighten me more with the new concepts of the new UNET framework. Thanks in advance for any help.


texts:
I'm trying to create pixel perfect collision detection but I don't know how to handle collisions when there is a jump. Here I have one image of a sample map:

But maybe I had a bad supposition assuming that all the pixels are little collision points.

I mean , there is no differences between y-axis collision and x-axis collision in my collision map.

I have been treating each axis collision split, but that is bad done when diagonal jump have been made, cause you'll get an error in x or in y while correcting the position.

Then I thought that maybe I was wrong in my supposition that I didn't need to split for pixel collision type.

I will resume it in 2 questions:

how can I handle pixel perfect collisions for a platformer?
if I'm doing it well, How to manage the x-axis, y-axis problem?

P.S: My 'player' uses a box collider.


texts:
I am creating a simple program in Unity C# that will generate a 2d grid using a 2d sprite prefab. I am stuck here, I don't know what to do. When ran, I receive an error.

Assets/Generator.cs(22,75): error CS0165: Use of unassigned local variable `grid_object'

I am a beginner, so I'm not sure what to do. This is most likely a rookie mistake, so thanks in advance.

using UnityEngine;
using System.Collections;
public class Generator : MonoBehaviour {

public float Width = 20;
public float Height = 20;
public Transform grid_object;
private GameObject [,] grid = new GameObject[20,20];

void Start () {
    CreateGrid();
}

private void CreateGrid() {

    for (int x = 0; x < Width; x++) {
        for (int y = 0; y < Height; y++) {
            GameObject grid_object = (GameObject)Instantiate(grid_object);
            grid_object.transform.position = new Vector2(
                grid_object.transform.position.x+x,
                grid_object.transform.position.y+y);
            grid[x,y] = grid_object;
        }
    }
 }
}


texts: Fastest visibility calculation towards all possible directions

texts:
I am searching for your advice. I have a massive voxelized model, like the one in the picture (but with a few million voxels more..). To reduce the total number of the model’s triangulations, I can remove the shared faces among the voxels, nevertheless, the triangles will indeed remain MANY. What I need to do is create an index that will hold a boolean list (of visible/not visible) information, coming from the following procedure:

Define a set of points, like the centroids of the 3 yellow voxels in the picture (but, this set might again contain millions of points) and for each point calculate which voxels (except their corresponding containers) can be seen (direct and unblocked line of site) towards ALL directions (something like a global illumination concept). If the ray-source (coming from a given point) can reach even at the minimum a target voxel, it means we have a "true" condition for that voxel. For example, if we assume that the ray-source point in the picture is the light source, then all voxels in the blue circle are "true" for the specific point.

This has nothing to do with game development, so I am sorry if my post should be somewhere else. I just felt I should better ask here, because most of my searches conclude to ray-casting, hard shadows, visible surface determination, OpenGL, etc which are quite relevant here.  I do not need to see any graphics (or have high fps :D), just store the results for future usage into a 3rd simulation process.

I get the feeling that if I go with implementing simply geometric calculations this indexing will run for too long (even though this can be parallelized quite easily I believe). Nonetheless, can I take advantage somehow of OpenGL and GPU maybe? Will this boost significantly my task? How should I approach the problem?
 I am working on an ASUS ROG-G752VY.

I only have to construct and store this index (which I would not be surprised if it would turn out to be tens of GBytes). The rest of the simulation runs on a cluster continuously. This indexing calculation operation will run more or less only once.

I just don't know what execution time to expect (days/weeks/years) with this amount of ray-source points that I am mentioning along with a "brute" check towards all directions and voxels (with or without the use of OpenGL and GPU). Yet, I can predict that the max number of visible voxels every time will be just a few thousand.

That, because (sorry for not mentioning it) there is a life-termination logic of this ray when the distance of its travel exceeds "x" units ("x" will be much much smaller than the size of the total model). Hence, for a ray further than "x" the searching process should break every time.

Thank you so much already for your time!!!


texts:
I have two coordinate frames, A and B. I want to create the rotation matrix RAB which takes you from A to B. A is a right-handed system, and B is a left-handed system. Furthermore, after moving from a right- to a left-handed system, there is a further rotation. These two coordinate frames are illustrated in the image below.

As can be seen, it appears that the axes in B are simply the negative of the axes in A. So, my first attempt was to simply make these negative in the rotation matrix:

RAB = [-1 0 0, 0 -1 0, 0 0 -1]

(sorry -- I don't know how to write matrices properly here...)

However, after working through some examples, this did not work out.

Please could somebody answer either (or both!) these questions?

(a) Why does my above solution not hold?
(b) what is the correct rotation matrix RAB?


texts:
I want to use sql database in my server.exe.

lets say 1000 users online. And players will change their data when they play. And server need to save these updates.

But how ?

i think there two way:

1) server will save in ram at run time and sometime or hourly server will write data (update) to sql database from ram. But if electricity goes or somehow the server shuts down , updates won't save. of course i don't want lose updates.

2) server will save updates in database at run time. but what will happen to speed ? I thought of a method. i will show you below with image. Can i get enough speed for 1000 online players with this method ?


texts: I have problems for export from Blender to Ogre3D

texts:
I don't speak good english, but I will try..
I need to make a game for my University.
Exists lot of models in blendswap but, I have problem for export.

Many of these models have extra objects, such as a floor, I need to remove those extra objects and export the weapon and hand.

My idea is:

Import a weapon model with hand with 2 actions, reload and shoot.
How can I do it?

I love this models:

http://www.blendswap.com/blends/view/85257 or 67870 or 70607 (change number in link, because I don't can put more 1 link, because I'm level noob)


texts: Do larger sprite sheets improve performance in html 5 games?

texts:
I know when I did some game development with XNA they recommended that we try to group are sprites into fewer sheets because the graphic card could process it faster. Does this also apply to web based games?

Note: Not sure if this makes a difference but most of my artwork is pretty defined by separate levels. In other words I'm not really reusing artwork across levels, which kind of made me wonder if I should be loading sprites that never get used just for the sake of grouping them into a spritesheet.


texts: Make a 2D character stop moving and going back when encounter an obstacle

texts:
I am using a 2d character who is sliding infinite ( huge incrementation of the X or Y value ) when moving.
He can only move up, down, left, right inside a virtual grid, made of multiple squares.

Now I want to add obstacle to stop his sliding and make him go back to the center of the previous square

The obstacles can be of different size and are located in the center of a square, so the collision occurs with the obstacle and NOT when the character enter the square containing this object !

How can I manage to stop the incrementation of X or Y when colliding ? And get the previous value of X or Y for which the character was on the center of the square just before the one containing the obstacle.

Thank you everybody !

I am not certain to have the good reasoning.
Actually I was thinking about something like that :

Lets say each square is 5 * 5 and each square center is at X + 5 from the previous square center and X - 5 from the next.
I was thinking about a loop which is moving the character from + 5 on the X axis and checking if there is a collision. If yes, the character goes back to the previous square center, if not, the loop keep going.

So assuming that my character is in ( 0 ; 0 ) coordinates and the obstacle is in ( 20 ; 0 ) coordinates ( but not filling the square ), my character will be in ( 5 ; 0), then ( 10 ; 0 ), then ( 15 ; 0 ), then it will collide with the object in ( 18 ; 0 ) ( because the object dont match exactly with the square size, considering the fact that on object can be 3*3 and just drop on a 5*5 square ), and the character will go back to ( 15 ; 0 ).

With this reasoning :

is the movement of my character going to be smooth ( like a slide ) or is it going to be square by square ?
if checking the collision BEFORE moving, is my character going to move from ( 15 ; 0 ) to ( 18 ; 0 ) and bounce back to ( 15 ; 0 ) or is it just going to  stay in ( 15 ; 0 ) ?

because I would like to have my character to move smoothly AND bouncing back when colliding !

Thank you


texts: How can I implement an asset update/download in a libgdx application?

texts:
I am building a game based on libGdx and I want to be able to check for and download updated assets at some point before the player starts playing. The game is being built for PC and for Android.

I haven't been able to find much on downloading assets. It seems libGdx assumes all assets will be packaged with the game or already on "external" storage and available for the AssetManager.

So far, the best option I've found is setting up updating code prior to starting the libGdx application.

How can I have my assets download while the libGdx application is running? Possibly to allow some interaction while waiting, or progressive asset downloads allowing limited game play. My goal is to allow for dynamic updates to assets, and to allow users to get into the game quicker. Especially new players, I don't want them waiting on a download screen before they see anything of the actual game.


texts: Is Google's Protocol Buffer viable for the serialisation of game data?

texts: Simple yes it is suitable, no it is not suitable for communications between game clients and/or server clients.  Also is it suitable for serialising and storing game data or is a more customisable, minimisable solution recommended.


texts:
I'm building a game with unity where a lot of scenes take place in an airplane as a passenger seated near the window, the airplane has to do a take off and a landing.

I can't find any examples of similar scenes anywhere on Internet.
So I was wondering which would be the best approach to do this :

Simulate the airplane physics, "checkpoints" system where the airplane travels through each checkpoints (current solution)
Animate the airplane with the unity animator system (tried it but it feels really cheap)
Static plane but make things move around him (possibility to have better lightings inside the plane as it is static)
360° Videos

The current solution works ok but I'm looking for improvements. I found the intro scene from The Forest pretty similar to what I'm trying to acheive here and I was wondering how they did it.

The current system works like this :

The plane has two engines script who control the speed of the plane. Another script controls the yoke, roll and pitch of the plane. And the last script is the 'Autopilot', each checkpoint tells the plane where to go and at whitch speed. You have to tweak the values until you have a good result which can be really time consuming.

Thank you !


texts: The difference between shading and data interpolation

texts:
Using methods like Phong you can make mesh look smooth and real. However you can do the same interpolation at the data level creating a surface (for example B-Spline surface).

What is the difference and when would you use shading over data interpolation?


texts:
I am working on building a HTML5 RTS game, and my current state is that I am building the Campaign mode of the game, and want to define the gameplay (The Scoring, Unit Behaviors/Attributes).

I am searching for links/articles/books about how to define the gameplay, for me this:

The scoring
Figuring out levels of control (in any RTS game, there is units, individuals and squads)
Unit action/attributes/properties
point timing (how long it will take to play?)
Achievements
..etc

I want to see how they usually define these areas in RTS games, I expect to see general document discussing this concept that I can use to build the gameplay.

Any idea? Is my question clear or I need to provide more details?


texts: object smooth orbital limit around another object depending on mouse drag

texts:
I am working in Unity.

I have special objects that can each be dragged freely around in 2d.

The objects cannot get too close to other objects (minimal Vector3.distance allowed is 1.5f).

I also have special connectors, which I can apply freely between 2 of any of these special objects. once 2 objects are connected, dragging them is further restricted.

The 2 objects cannot get too far between each other (max Vector3.distance allowed is 5f).

Both of these restrictions work, my issue is that once these restrictions occur, the objects are pretty much just stuck in place until dragged away from the restriction they tried to pass.

I want the object being dragged to orbit smoothly around the object it's connected to, once they reach any of the 2 restrictions.

The best example I can think of is the angry birds slingshot,

that once it reaches it's maximum pullback, you can just orbit along this max distance smoothly up or down depending on where you are trying to drag, this same smooth effect needs to occur both when too close and too far.

Hope I explained myself thoroughly I tried to find answers and try myself but could not reach any working solution.

The closest I think I got to a solution is with rays and the on point of ray function like in the video I provided below but I have no idea how could that be implemented in my sort of game.

thanks,

Remember the BBQ.

link to the sort of angry birds pulling mechanics I am talking about:
https://unity3d.com/learn/tutorials/topics/physics/making-angry-birds-style-game-part-1

Image provided is very inaccurate to the boundaries of each restriction, just to make it seem more clear.


texts: Common way of animating 'motion' for walk cycle animations

texts:
I've just posted this at the Blender artists' forums before realising I would probably get a better response from a more game development-specific audience, so apologies for cross-posting! It's for the right reasons :)

I'm a programmer trying to animate a character walking for a game project, using Ogre. I've made a very simple walk cycle in Blender and exported it to Ogre, and it plays just fine. By fine, I mean it works, but there's terrible foot sliding. This is because I just animated the walk in-place (at the origin) in Blender, and of course I don't know what "speed of walk" that corresponds to, so when I move the character in-game the motion doesn't necessarily match up with the movement of the feet in the animation.

So my question is: what's the normal approach for this kind of thing? At work we use Maya, and the animators either animate a special 'moveTrans' node that represents the "position" of the character (or have the exporter generate it for them from the movement of the root node), then the game can read this to know how fast the animation moves the character. So in the Maya file, the character will walk forward for one cycle and this extra node will follow along with them by their feet. I've not seen anything like this in open-source land, and there's certainly no provision for that in the Ogre Exporter script. What do you chaps normally do for this?


texts: Networking and movement in MMORPG's UNITY

texts:
I'm programming a dedicated server in C# using BeamServer2 DLL's.
At first I wanted to be able to see other players move on our already made Omuni map.
This I did by just sending your position to the server each frame.
This worked out and I was able to play with a few friends but the movement wasn't laggfree.
So I started trying to add movement smoothing and also some security so they can't just send a false position to the server without the server stopping it from reaching the other clients.

What I than did, I made a masterClient that has a movementController on the remotePlayer.
When a client wants to move he moves localy and sends a message to the server with hes direction to move. The server than takes hes speed and sends it to the masterClient.
The masterClient than moves the remotePlayer just like the remotePlayer moves himself.
When he stopes moving he sends a message with hes position in it. The masterclient than checkes if the position that he has come to is as close as the position he has from the client, if it is realistic according to the ping of the client the server puts him on the client's position.

This works, but I still have a lagg problem and I'm not sure how to fix this.
I must make movement smoothing on the client but I found out myself that I can just lerp (x/2,y/2,z/2) to the position and put him on the real position next frame, I failed at that and I will try again soon. Even if that is added I'm not sure if the lagg is fixed.

Any other techniques, suggestions, questions, ... ?
Thanks, Diede.


texts: I need to find intersection point of a vector in an axis aligned rectangle

texts:
I need some help, I have one vector in a rectangle like following

(Ops, first A2 point on the top should be A1, assume it is A1)

Let's say the vector is like above It doesn't have intersection point actually, Basically, I need to find the point A1 and A2

I'm using cocos2d-x but framework specific solutions are not mandatory
Thanks


texts:
I want to make a strategy game like Risk. I want to use C# for the mechanics and Unity for the graphics.

My problem is that I don't know how to create the map itself and integrate it with C#. I don't want a tile map but instead I want to create a customized world map, with different provinces defined by me.

The map would be something like Imperial Glory, where you see it top down and then move your generals like chess pieces. I'm not implementing any real time battles at this point, it's just something really simple, like a board game. Could anyone please help me?

I'll try to explain it a bit better: I need to create a map of the Mediterranean basin that would cover all the land occupied by the Romans at the height of their empire.

Next, I'll divide the map into 20 provinces (Italy, Gaul, Germania, etc), each one producing a set ammount of resources and population. I also want them to have their own wheather and buildings (for example, you can only train soldiers in provinces that have a barracks). I guess I'll need a text box popup that appears when you click on a province to display it's information.

I'll also need some buttons to open dropdown menus or perhaps whole windows, for other purposes such as diplomacy, statistics, tech trees, etc.

I wanted the map to be in 3d because I think it would be much more interesting to look at it in perspective instead of flatten 2d.

I'm fairly new into Unity so I really admit that I have no idea where to start. Please, have patience with my ignorance. Thank you very much for all your help. If there are any doubts about my question, please let me know and I'll try to explain it better.

PS: I think I'll make it a turn based game since I think this would make it simpler to code and faster to run.


texts: Map file format for Real-time strategy game

texts:
I am planing to create a 2D RTS game on iPhone using cocos2d, besides the tile map, any other suggestion for storing the map details for the game?

Would be nice if a GUI editor is also provided.


texts: Splitting profit - Equal share vs equity investment (work & money spent = share)

texts:
Coming up with an appropriate one-liner question was so hard I wrote the body before the header...

So we're a team of 4 developers; two designers, two coders to put it simply (naturally we don't tie ourselves up with labels). We've come up with a great game design together, and we're prepared to spend a great bulk of our time making a prototype.

Problem is, there's a major difference of opinion when it comes to sharing potential revenue made by the game.

Investment = Share

Two of us would like to have everyone keep a rough log of hours spent. Converting that to a previously agreed upon per-hour salary, we could add it up with real money invested, and from that determine each developer's 'stake' in the game, i.e. their share.

Equal Share

The other two do not agree with that, among other reasons because they think some pieces of work are worth more than others, like a really great idea for a feature. Because of such immeasurables, they think an equal share for all would be the easiest.

Another argument said: (paraphrasing) "logging hours would take away the fun. I'm serious about this project, but I want to work with it on hobbyist terms, not like a second job."

We need to formalize an agreement before development has gone too far, but how can we get past these core differences of opinion? Is this a common problem among first-time startups?


texts:
I was reading an Arduino code regarding counter http://www.toddholoubek.com/classes/pcomp/?page_id=58 . Since I do not own a Arduino microcontroller and would like to know the result, I test the concept of the code by using a game object in unity, the void loop() in Arduino function like the void Update in unity. The scale of game object function as if a counter and I tried generate the state 1 or 0 depend on the value of transform.position.y so I can check is it the increment of object scale happen one time only for each transition from state 0 to state 1. For the code below, it worked as intended but when if I transfer this line "PreviousState = CurrentState;" into the if statement " if (_birdWasLaunched &&
GetComponent().velocity.magnitude > 0.1 && transform.position.y > 1 && CurrentState != PreviousState)" , it still working? Been thinking for sometime couldn't see the sense why it still working. As
Initially value of previous state = current state = 0 when transform.position.y < 1 since the object is launch from a position.y < 1 upward. After y>1 ,value of current state switch from 0 to 1, which made the equality CurrentState!=PreviousState become true, then the scale gain 1 increment to its original value. Which is followed by the command line PreviousState=CurrentState to made the equality of CurrentState!=PreviousState become false in next frame update otherwise object scale increase according to fps. After the object drop to position. y<1 due to gravity, the value of CurrentState =0 and PreviousState=1 , I then launch it again upward in y axis direction until position.y>1 which the current state become 1 at this time the equality of PreviousState == CurrentState at this moment but the scale still get one increment? This is the part where I don't understand.
  using UnityEngine;
  using UnityEngine.Assertions.Must;
  using UnityEngine.SceneManagement;

  public class Bird : MonoBehaviour

{
int CurrentState = 0 ;
int PreviousState = 0;
Vector3 OldPosition;
Vector3 DistanceDifference;
float TotalDistance = 0;
Vector3 _initialPosition;
private bool _birdWasLaunched;
[SerializeField] private float _launchPower = 500;

void start()
{
    OldPosition = transform.position;

}

private void Awake()
{
    _initialPosition = transform.position;

}

void Update()
{

    if (_birdWasLaunched &&
             GetComponent<Rigidbody2D>().velocity.magnitude > 0.1 && transform.position.y > 1 && CurrentState != PreviousState)
    {

        transform.localScale = new Vector3(transform.localScale.x + 1, transform.localScale.y + 1, transform.localScale.z + 1);

    }

    PreviousState = CurrentState;

    if (_birdWasLaunched &&
  GetComponent<Rigidbody2D>().velocity.magnitude > 0.1 && transform.position.y > 1)
    {
        CurrentState = 1;
    }

    if (_birdWasLaunched &&
            GetComponent<Rigidbody2D>().velocity.magnitude > 0.1 && transform.position.y < 1)
    {
        CurrentState = 0;
    }


texts: Is it possible to get object rotation in a shader for dynamically batched objects?

texts:
All the batched objects have the same rotation. To simulate the effect of directional light I need to determine the object sides actual (world) directions. Normally I would use unity_ObjectToWorld & unity_ObjectToWorld for that, which is not possible when the objects are batched.
Is it possible to pass the object rotation to the shader in one action (since it's the same for all of them) without breaking the batching?

This is a simplified shader example (here I use colors instead of light/shadow effect and only 2 sides instead of 4):
Shader "Test/UnlitTest"
{
    Properties
    {
        _MainTex ("Texture", 2D) = "white" {}
        _TopColor ("TopColor", Color) = (1, 0, 0, 1)
        _BottomColor ("_BottomColor", Color) = (0, 0, 1, 1)
    }
    SubShader
    {
        Tags { "RenderType"="Opaque" }
        ZTest Off
        ZWrite Off
        Lighting Off
        Cull Off
        Fog { Mode Off }

        Pass
        {
            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag
            #include "UnityCG.cginc"

            sampler2D _MainTex;
            float4 _MainTex_ST;
            float4 _MainTex_TexelSize;
            fixed4 _TopColor, _BottomColor;

            struct vertData
            {
                float4 vertex : POSITION;
                float2 uv : TEXCOORD0;
            };

            struct fragData
            {
                float2 uv : TEXCOORD0;
                float2 uvW : TEXCOORD1;
                float4 vertex : SV_POSITION;
            };

            fragData vert (vertData v)
            {
                fragData f;
                f.vertex = UnityObjectToClipPos(v.vertex);
                f.uv = TRANSFORM_TEX(v.uv, _MainTex);
                f.uvW = mul(unity_ObjectToWorld, f.uv);
                return f;
            }

            fixed isTransparentPixel(fixed2 uv)
            {
                return step(tex2D(_MainTex, uv).a, 0.0);
            }

            fixed isEdgePixel(fixed2 uv)
            {
                uv = mul(unity_WorldToObject, uv); // back to object space
                return isTransparentPixel(uv);
            }

            fixed4 frag (fragData f) : SV_Target
            {
                fixed isTransparent = isTransparentPixel(f.uv);
                clip(-isTransparent);

                fixed4 c = tex2D(_MainTex, f.uv);
                float2 borderSize = float2(3, 3); // border size in tex pixels
                float dy = borderSize.y * _MainTex_TexelSize.y;
                fixed3 borderColor = fixed3(0, 0, 0);
                float borderColorsCount = 0;
                float2 uvW = f.uvW; // UV in the world space

                // Top edge:
                fixed isEdge = isEdgePixel(uvW + float2(0, dy));
                borderColor += isEdge * _TopColor.rgb;
                borderColorsCount += isEdge;

                // Bottom edge:
                isEdge = isEdgePixel(uvW + float2(0, -dy));
                borderColor += isEdge * _BottomColor.rgb;
                borderColorsCount += isEdge;

                fixed noBorderColor = step(length(borderColor), 0);
                fixed hasBorderColor = 1 - noBorderColor;
                c.rgb = c.rgb * noBorderColor + hasBorderColor * borderColor / max(borderColorsCount, 1);
                return c;
            }
            ENDCG
        }
    }
}

It gets a semi-transparent image as a texture. The image is completely transparent at the edges and contains an opaque shape in the center.

The shader colors the top edges of the non-transparent shape in red and the bottom ones in yellow. It uses unity_WorldToObject & unity_ObjectToWorld to check the edges facing directions in the world space.


texts: How to apply a visual filter to what I am drawing?

texts:
I'm looking to apply a sepia filter to what I'm rendering. Perhaps we could just apply the filter to the view or pass it to the draw method to draw everything with the filter (I'm using one draw method, everything that is visible gets drawn by one draw system).

Would I use a shader for this? I honestly don't know how to implement shaders or how to learn.

I'm using sfml.

How would you apply other filters, not just sepia? For example greyscale, moonlight (I would love this one), or the other filter styles you commonly see on the photo editing section of your (i)phone?

I've done some research into it and didn't really find anything useful. However, I assume you use shaders - but I don't really know how to program a shader, so I'll have to learn that if that's the case.

Thanks :)


texts:
I wish to be able to render any Plane (Defined by a Normal and a distance from the origin).

The closest answer state to use 'Direction' (4D vectors with w = 0) with the Lengyel infinite matrix, but unfortunately it does not render anything with my implementation:

const float FOV = glm::radians(55.0f);
const float e   = 1.0f / std::tan(FOV / 2.0f);
const float a   = height / width;
const float n   = 0.1f;

this->projection = glm::mat4{
  e, 0, 0, 0,
  0, e / a, 0, 0,
  0, 0, -1.0f, -2.0f * n,
  0, 0, -1, 0
};

std::vector<Vertex> vertices =
  {
   Vertex{glm::vec4( 0.0f,  0.0f,  0.0f, 1.0f), Vector::Up()},
   Vertex{glm::vec4( 1.0f,  0.0f,  0.0f, 0.0f), Vector::Up()},
   Vertex{glm::vec4( 0.0f,  1.0f,  0.0f, 0.0f), Vector::Up()},
   Vertex{glm::vec4(-1.0f,  0.0f,  0.0f, 0.0f), Vector::Up()},
   Vertex{glm::vec4( 0.0f, -1.0f,  0.0f, 0.0f), Vector::Up()}
  };

std::vector<GLuint> indices = {0, 1, 2,   0, 2, 3,   0, 3, 4,   0, 4, 1};
// Render by indices
...


texts: How to accurately score moving averages (indepenent of sampling window)

texts:
I'm developing a puzzle game, and coming up with a little trouble how to accurately create the 'score' for a particular player's solution.

In this game a player creates a machine which generates 'events'. The 'score' should be the number of events per second that a particular machine performs.

I.E. if my machine performs 6 events per second, and yours produces 8 per second, your score should be higher than mine.

I initially thought to use a moving average for this, but I've discovered it's trivially easy to manipulate this mechanic, such that solutions with an equal long-term performace don't generate the same score.

So in this case if my machine generates 1 event per second, and yours generates 3 every third second, they should have the same score. But if I use a running average to calculate the score, then the latter solution is likely to generate either a higher or lower score depending on the sampling window.

Case A:

   time    | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 |
solution A | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1  |   = 10 / 10 = 1 event per second
solution B | 3 | 0 | 0 | 3 | 0 | 0 | 3 | 0 | 0 | 3  |   = 12 / 10 = 1.2 events per second

Case B:

   time    | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 |
solution A | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1  |   = 10 / 10 = 1 event per second
solution B | 0 | 0 | 3 | 0 | 0 | 3 | 0 | 0 | 3 | 0  |   = 9 / 10 = 0.9 events per second

I'm wondering if theres some other metric possible to use other than 'average' that wouldn't be subject to this kind of inconsistency? The only way to make this works would seem to run the simulation for infinite time, at which point the two solutions would converge on 1 score / second, but that's not possible to do.

I'm somewhat doubtful that there's any solution to this problem, but just wanted to throw it out to see if there are any ideas.


texts: Declaring controls in multi form/usercontroll game

texts:
In my game I have 2+ forms and 4+ usercontrols.
Where should I declare, lets say a textbox that I use in form2, but I need to modify it in form1.

Should I make them public in their own form/usercontrol or should I make a static class with all the controls?

(Edited to clarify my question)
I want to know the most used and flexible way.


texts: Best way to create defence(withdraw) algorthim libgdx?

texts:
I have created user body and enemy body. Enemy body uses the steering behavior created by gdx AI. User body have it own control inputprocessor. World doesnt have gravity.

Enemy body arrives the user body and collision happens by linearvelocity.  So enemy body only attacks even if it is getting more damage. I just want to declare a way to withdraw and find a safe place when it get more damage  then again attacks when it get enough distinct.

So What do you suggest for My game ?

I already got some idea as Path finder but i am not sure how to use it.

Which algorithm I need to user ?


texts: How can a variable have two values at the same time?

texts:
Just to clarify, I do not want to know how to make a variable display 2 values at the same time.

I want to know how this is happening in my project.

In the Level Blueprint I have a timer that every 5 seconds generates 2 warriors in different places. This in order to distinguish them. One is from the blue team and the other from the red team:

The team of each one I can define correctly, the problem happens with the whole variable.

The value of the blue warrior variable should be 5. The value of the red warrior variable should be 1.

I have a Text Render that displays the time and value of the variable I have quoted:

In the Event BeginPlay I have a loop that prints the value of this integer variable I have quoted:

Game picture:

Game picture:

How can one place show that the variable is 0 and in the other show that it is 1/5?

EDIT 1 (verification of some information)

Some time after posting this question, I wondered about the value of the warrior team being correct or not, and through an impression I noticed that there was also an error.

On printing right after the event I was able to confirm the error:

In game:

Default value of the string variable:

Default value of the integer variable:

From what I've noticed, I can not change the default value of the variables in the warrior generation. Even with the pin coming out of the spawn.


texts: Running subsystems at difference update intervals

texts:
I want to update the rendering at 60fps, but the logic at some lower rate, say 15Hz. But if an object only moves when the game logic updates, then it would appear to stutter badly especially for lower frequencies. I guess the rendering system could interpolate an entity's vector and draw the model moving at a lower dt, but if the game logic causes the entity to change direction it will appear to teleport back, and so on. I can imagine many more problems.

How is this usually solved in games? Surely most engines want to decouple rendering from game logic, so there must have been some though put into this. Or does everyone just update all systems that have graphical effects at the same rate?


texts:
I thought that if you wanted to make games using DirectX, you had to know C++. But I recently found out that that is not actually true. It looks like some parts of Direct3D can be used from C#. This MSDN document, for example, which has C# examples.

Am I understanding this incorrectly? Have I waited all these years for nothing?


texts:
I've started down a line of art asset development that will allow me to (hopefully) reuse and improve assets for several games.

But how do I go about storing and finding them?

Let's say for example I decide to focus on RPGs for ~2 years. I would create items, monsters, etc. and store them somewhere. How would I categorize them and make them easier to search later on?

Is the best solution "use directories with broad categories like landscape/items/monsters/etc.?"


texts: C++ - How to create an engine editor without frameworks like qt and wxWidgets?

texts:
Basically sometimes I like to try to venture into the world of graphics computing, sometimes I have a project or another that uses opengl plus all the "blind" with opengl, I wanted to be able to create an editor like unreal editor or cry editor, basic functionality like dock widgets, buttons etc, and if it can be integrated with the engine, I've tried to create a windows program with WINAPI but God, that's a torture, a lot of code and in the end it's all blind, you end up having to to guess where each element should be, is usually quite limited having practically no legal content about it, on the other hand it was a hand in the wheel for me, very simple indeed, just the way I wanted it, but it does not give me the freedom that I wanted when it comes to computer graphics, I wanted to do something that was my own, without third-party codes (other than libraries like opengl, vulkan and directx of course).

I've been looking at the banshee code but I'm not sure how they did it to create that WINAPI editor, if companies like capcom and others can, then it should not be difficult.


texts:
I have a 3D Model under 3ds Max and I'm trying to integrate a biped skeleton. But when I start to adjust the pelvis or any other bone I can't scale it.

I don't know why, and this is driving me crazy. If someone can help it would be much appreciated.


texts: What is faster - loop in shader vs draw-call

texts:
I am doing some program, that can be written in two ways.

render full screen quad and send some additional info to fragment
shader. But in fragment shader I need to perform for-loop
Move the loop to the CPU side of program and call draw-call on
fullscreen quad repeatedly. Output will be rendered to texture. I
will have two of them and swap active (write) and inactive (last
output, read-only).

What can be faster ? I think, that number 1, but on the other side, loops are not very efficient in GLES shaders. And I need to calculate texture coordinates on the fly, which according to Apple doc is slower than if they goes directly from vertex shader and are not changed.

Edit:

Point two can be improved by this:

I can put all quads to single buffer and draw them with one draw call
(each quad will have different depth, but will be still fulscreen),
where depth will be "loop" variable. In shader I take this "depth"
and use blending (which can be used on iOS 6 via gl_LastFragData[0])


texts: Why is an engine like Unity3D emphasized over a native library like OpenGL for beginners?

texts: I am just a beginner in 3D games, my preferred platform is Android. I posted a question in some other forum about "What to use: OpenGL or Unity3d?" They all emphasized Unity3D and using its built-in features and tools, which I would have to code myself if I were to use OpenGL. But then someone says most of the complex games require custom engines. Why would I use an engine like Unity3D over OpenGL?


texts: Unity 4 mecanim; 'Quaternion to Matrix conversion failed, input quaternion is invalid'

texts:
I'm trying to animate a stick figure in Unity, with placeholder animations. Character is built/animated in Blender, exported to FBX. When imported to Unity, everything appears correct in the editor. All animations are imported, and i can preview them normally.

I set up the "rig" section of the model import to use generic rigging. This creates the avatar which is used in mecanim.

I set up a simple "walkForward" animation, and setup mecanim parameters to get it called when the player moved forward; all that works. The animation is called at the right times.

However, during play, as soon as any animation is started on the avatar, the model disappears, and a flood of error messages appear in the console, stating

Quaternion to Matrix conversion failed because input Quaternion is invalid {-1.#IND00, -1.#IND00, -1.#IND00, -1.#IND00} |=-1#IND00

I'm not altering the animation with any scripts of my own, it's all mecanim. Is there a setting i'm missing?

I'm using Unity 4.3.0.0f4, building/exporting my mesh with Blender (latest).


texts: Cant set up ANDENGINE GLES2-AnchorCenter Examples & Extensions

texts:
I am trying to setup the GLES2-AnchorCenter in my eclipse
Downloaded andengine , extension and examples listed in Anchor center branch .But not yet succed .

Andengine examples missing an extension named

  andengine cocosbuilder extension CC Rotating Sprite extension

But i am not able to find it anywhere.If i am missing the extension please give me a link to get the extension.

In extensions Multitouch extension shows some error with import statement

import org.anddev.andengine.util.SystemUtils;

Actually i am not able to find org.anddev package it self in andegine,

in andengine scripting extensuion it shows error with the statement

import org.andengine.util.color.Color;
What are the things I am missing.
Do i need to install all thse extensions to get the eample get working?

Please Help me ..........


texts: Steam web API won't work with new domain

texts:
Following code works perfect on localhost (even using LightOpenID('localhost')). "mysite.com" is replaced with current site in real script. But for some reason this doesn't work on an external domain, but on localhost. Anyone knows why?

Seems like $openid->validate() returns false once on a server with a domain name, but on localhost it works fine.

<?php
require "lightopenid/openid.php";

$_STEAMAPI = "XXX";

try{
    $openid = new LightOpenID('mysite.com');
    if(!$openid->mode){
        if(isset($_GET["login"])){
            $openid->identity = "http://steamcommunity.com/openid/?l=english";
            header("Location: " . $openid->authUrl());
        }else{
            $notloggedin = 1;
        }
    }elseif($openid->mode == "cancel"){
        die("cancel");
    }else{
        if($openid->validate()){
            $id = $openid->identity;
            $ptn = "/^http:\/\/steamcommunity\.com\/openid\/id\/(7[0-9]{15,25}+)$/";
            preg_match($ptn, $id, $matches);

            $url = "http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key=" . $_STEAMAPI . "&steamids=" . $matches[1];
            $json_object = file_get_contents($url);
            $json_decoded = json_decode($json_object);

            foreach($json_decoded->response->players as $player){
                // now login, etc.
            }
        }
    }
}catch(ErrorException $e){
    echo $e->getMessage();
}
?>


texts: How do I set horizonal Field of View by code as in Inspector?

texts:
I have a camera that I have set to
RenderType = Base
Projection = Perspective
FOV Axis = Horizontal
Field of View = 75
Physical Camera = False
Clipping Planes Near = 0.3, Far  = 1000

If I set Field of View values during gameplay in the Inspector, it works as expected.
For example, I type 75, and the camera behaves as I think it should. I'm comparing with Resident Evil 4. It has a camera cheat, and if I select FOV 75 in this cheat, the Resident Evil 4 camera behaves like my Unity game camera.
However, when I set the camera.fieldOfView to a 75 by code, the Inspector shows 104, and the code does not look as it looks when I type 75 in the Inspector.
_camera.fieldOfView however returns 75.
What is going on here, and how do I fix it?
Thank you!


texts: How can I handle rendering on multiple monitors with differing refresh rates?

texts:
What's the best way to deal with a situation that may arise, where a user has two or more monitors with different resolutions and vertical sync intervals?

This would apply when a game has a fixed timestep, and is running in windowed mode: if one monitor has a frame rate of 60.056, and the other has a frame rate of 59.94, vertical sync will ultimately fail to do its job, if the game window is moved from the primary screen to another.

Temporal aliasing will also occur, as the timestep is not properly attuned to the other sync rate. How do games typically deal with this issue, if at all?


texts: Using a JS Query to work as an HTML Anticheat?

texts:
So, I have a project, its a "cookie clicker" by definition, and I wish to work out how I can protect the game from users being able to edit <button id="cooker" onclick="cookieClick(1)"></button> and setting (1) to like (123129).

I tried a few things first:
JQuery:
I tried using an old on() function with a dom searching function, and then to run an alert saying "Dumb Hacker! Im corrupting your save data" and then of course it would run Function clearDat() then function corrupt() which clears the localstorage data and sets it to an invalid value (usually wounds up as NaN) which prevents them from Playing.

Unfortunately the cookieclicker was editing the program so hastily, that it was "changing" the button above, and I wound up getting a million alerts
(And because I was using a windows based HTML editor, I was getting WINDOW alerts, which i had to spam esc and try to delete the alert function and rerun the whole game, it was a pain)

I also tried a similar method using an old JS function, but it wound up not working.

I think you may see where im getting at, I'm really stuck in a pickle.

Heres the current code: https://hatebin.com/tgsdqzhzlc


texts: Required initial velocity (fixed launch angle) for projectile to hit a target

texts:
The scenario:

I have an enemy tank (AI) chasing my friendly tank (player). When the enemy gets close enough he tries to shoot the player. Now the enemy prefab has an empty game object attached as a child which is used as the projectile (shell) spawn point. It's tilted 10 degrees up (X axis, the actual value in inspector is 350).

Example:

Now I'm trying to figure out what velocity or force must I apply to the projectile in order to hit the player. The angle is fixed (10 degrees) and is always the same. I have tried using the equation (from wikipedia):

Which I solved for v and got:

and translated into code which looks like this:

private float requiredForceToHit(Transform target)
{
    float turretAngle = 360.0f - this.turretTransform.eulerAngles.x; //Turret is 10 deg tilted up (350 in inspector)
    float g = Physics.gravity.magnitude; //G force
    float y = 0.0f; //Height of the target
    float x = Vector3.Distance(target.transform.position, this.turretTransform.position); //distance to hit, slight off because turret is lifted up

    float tanG = Mathf.Tan(turretAngle);
    float upper = Mathf.Sqrt(g) * Mathf.Sqrt(x) * Mathf.Sqrt(tanG * tanG + 1.0f);
    float lower = Mathf.Sqrt(2 * tanG - ((2 * y) / x));

    float velocity = upper / lower;

    return velocity;
}

But the projectile falls short from the target. It does launch farther when farther away but the farther away the target the more distance between the point of shell impact and the actual target. What I'm trying to say is that it is pushing with greater velocity the farther away I am but it falls short.

What is wrong and how do I fix it?

Appendix:

The actual shooting code:

private void fire(float force)
{
    Rigidbody shellInstance = Instantiate(this.shell, this.turretTransform.position, this.turretTransform.rotation) as Rigidbody;
    shellInstance.velocity = this.turretTransform.forward * force;
}


texts:
From my understanding, there are several different ways to implement decals, from screen space, to copying geometry, but I can never find an explination of it's math.

So what exactly is the math about Decal geometrical projection? I understand that it's dependent on some set of UVs to be projected, which is generated by clipped triangle coordinates, and meant to only be used on statics.

How does the Screen Space projection work exactly?

And I understand that the two previous methods do not work on dynamic geometry, (say you want a bullet wound on a character), how is that solved?


texts: Moving A Sprite In The Direction Its Facing XNA

texts:
There are many questions on this site that explain this except they seem to all be in Java.
I want to move a sprite in the direction it's facing, in XNA. I know you must use Radians and lots of complicated maths which I am not too familiar with. I tried doing this:

position.X += RotationAngle * 5;

This code obviously makes no sense whatsoever, and that's why I need help with it. How can I accomplish the rotation?


texts: Using behavior tree with custom pawn and movement component

texts:
I am trying to have a custom APawn along with its custom UPawnMovementComponent and AIController, to move to a location using the MoveTo node of a behavior tree.

I've followed the code in the engine from the MoveTo node in the behavior tree up to the navigation classes in order to understand how this work. What I tried so far is to have my movement component inherit from UPawnMovementComponent and use it to consume the input vector from its pawn (input vector that should be updated by RequestPathMove in UPawnMovementComponent).

I must have missed something as this solution isn't working and my pawn does not move at all.
Is there anything more that I should have done? Any other solution to achieve this?

EDIT:
A few things I checked:

I have a navmesh, it displays a green area where the pawn stands
The goal position is always in range
There is no physical constraints on any of the component of the pawn


texts: Camera movement constrained to pixel boundaries

texts:
So a friend and me, we are currently making a game in C# using XNA. We are trying to get the camera to move in full pixel motion, but we just don't get it right. This concept is hard to explain, but i'll try to make it as clear as possible with this gif.

As you can see, on the left hand side the black pixel moving in full pixel motion, while the right pixel is moving in free motion. Full pixel motion is basic motion in native resolution, but when we scale things up, the second case occurs. We are trying to avoid this, while making the camera as smooth as possible, with acceleration, deceleration, etc. The Cave Story cameras is the perfect example for this. Any ideas? Thanks for the help in advance.

P.D: please forgive any spelling or gramatical errors, English is not my native language.


texts: Disable autorotation if Android has it disabled

texts:
I'm making a game for Android in Unity. I wanted the game to handle screen rotations, so I set "Default Orientation" to "Auto Rotation. This works well, except for one issue:

If you disable auto-rotation in the device's settings, the game ignores this and keeps autorotation.

How would I go about making it disable autorotate when the Android device is set to disable autorotate?


texts: Using Actionscript 3's Graphics API in Flixel

texts:
My question sounds pretty simple but awfully, I couldn't find much information on the internet.

How can I draw a circle in my FlxSprite?

I couldn't find much information about drawing geometric objects or the usage of classic graphics API in Flixel.


texts:
In my Java class, we're creating a connect 4 game. For now, we're just setting up the GUI. I am receiving the error on lines 13 and 14
      " private ArrayListplayer;
        private Connect4Ui frame;"

and I'm receiving an error in the UI class on the GameListener line as well as the Panel line. I'm sure it's something simple, but this is our first few weeks of the intro course. Thanks a lot!

package connectfour;

import java.util.ArrayList;
import javax.swing.*;

/**
 *
 * @author j_ortiz9688
 */

// connect 4 main
public class ConnectFour {

    private ArrayList<Player>player;
    private Connect4Ui frame;

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {

    }

}

Ui Class

package userInterface;
import javax.swing.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

/**
 *
 * @author j_ortiz9688
 */
public class Connect4Ui extends JFrame {

    JMenuBar menuBar;
    JMenu gameMenu;
    JMenuItem playerPlayer;
    JMenuItem playerComputer;
    JMenuItem computerComputer;
    JMenuItem exit;
    GameListener gameListener;
    Connect4Panel boardPanel;

}


texts: What would be the best approach to creating a pressure plate in a 2D game?

texts:
I've just really gotten started in Unity and while documentation has been helpful I haven't figure out how to detect collisions with 2 or more objects. I was able to get a script working that plays a sound when I touch the pressure plate with the player but I don't know how I would do something when 2 objects are within the collider but undo it when one of them leaves the area.

void OnTriggerEnter2D(Collider2D other)
{
    if(other.tag == "Player")
    {

        AudioSource.PlayClipAtPoint(Sound, transform.position);
    }

}
}

Am I going about this the wrong way by using OnTriggerEnter2D? I see that there is a mass component on Rigidbodies but I don't know if I should be using it because I am still a novice in Unity. I'm also aware of OnCollisionExit but I don't think that works in this case because I'm currently only detecting 1 object but I need to detect 2. I was able to find videos that somewhat helped but all of them only worked with one object and were in a 3D space rather than a 2d one.


texts: How do I create a custom collision map for clickable areas on a map?

texts: Say I had a map like the one displayed above. What would be the best method of creating a collision map for each individual state where I can click individually?


texts: Facebook's strategy has been to Grow First, include Ads Later. For mobile games, is there any evidence that ads hinder popularity, or that people are more likely to share games without ads?  Or as mentioned by angarg12, is there evidence that introducing ads part-way through a game's life cycle affects how people feel toward your game?


texts: Unity 5 - how to toggle realtime global illumination

texts:
I am using Unity 5.5. Is there a way to enable and disable precomputed realtime GI at runtime? and if so, how can I do it?

The idea is that I want to set dynamic lights as a graphics quality option that the player can choose to toggle.


texts: How can I extract the Geometry from a j3o file?

texts:
I created a blender file and then converted it into the j3o file.
The only way to load the 3d structure in the game is through a Spacial object:

Spatial towerModel = assetManager.loadModel("Textures/tower.j3o");

Initially the tower in the scene was composed by a simple Geometry:

new Geometry("Tower." + index, new Box(X_SIZE, Y_SIZE, Z_SIZE));

To substitute this implementation with a proper 3d tower I need to use the Gemetry object from the 3jo.

How can I extract the Geometry from the j3o file?


texts: How to avoid lots of ugly math code and constants-hoarding?

texts:
In a lot of the games I've (tried) making in the past, I often run into the problem of the code getting really heavy on ugly mathematical code. This happens especially frequently in setting up user-interfaces such as choosing the positions of things on screen. Just to get an idea of what I mean, here is some code from the setup for the level selection screen in a recent project:

It gets really verbose, as you can probably tell. I try to mitigate it with descriptive variable names and detailed explanations of the purposes of constants such as INITIAL_LEVEL_SELECT_Y_OFFSET, but then it becomes verbose just in a different way.

I considered making everything, rowNum, totalWidth, totalHeight, etc., constants, but to me it looked really weird to have 30+ constants attached to every class. I also tried using local variables with smaller names, such as xOffset and yOffset, but then it defeats the purpose of having descriptive variable names (as you can see I use INITIAL_LEVEL_SELECT_Y_OFFSET anyways 5 lines after declaring yOffset).

Another problem this causes is that some constants are used by multiple classes, but aren't really general enough to be included in some static "Constants" class. For example, the constructor for LevelSelectButton uses INITIAL_LEVEL_SELECT_X_OFFSET, and the class in the picture above does the reverse and uses a constant defined in LevelSelectButton.

I originally placed the constants according to "what they were most attached to" if that makes any sense. For example, BUTTON_WIDTH makes most sense in the LevelSelectButton class since it describes a level select button's width.

Another problem is that some of these constants refer to the width and height of images that haven't been loaded statically. For example, LevelSelectButton.BUTTON_WIDTH is supposed to be the same as the width of the button sprite that class uses, but my current setup requires that the sprite for LevelSelectButton be loaded in the constructor for that class (I can think of ways to remedy this based on my current system however).

Any tips on how to avoid these problems? More comments? More constants? Less constants? A static Constants class?


texts:
I have a problem where i have a ballon which i need to continuously inflate and defalte in update method, I have tried to used setScaleCenter but it is not giving desired result.
Below is a code i am trying to make work

    scale += (float) ((dist-lastDist)/lastDist);
    Log.d("pinch","scale is "+scale);
    Log.d("pinch","change in scale is "+(float) ((lastDist-dist)/lastDist));
    player.setScaleCenter(scale, scale);
    player.setScale(scale);


texts: Unity: Blender's Armature messes up Faces

texts:
The Model itself is fine when imported but when I activate the Animation all Normals and lighting get Inverted from the Bones.

Result:

Import Settings:

Import Settings:

Blender Armature Settings:

Blender Export Settings:


texts: How should I access frame buttons from a controller in an MVC approach?

texts:
I'm developing an italian card game using the mvc pattern. I have the class GameFrame that contains the view. The user's card are buttons (JButton objects). I have 3 controllers:

GameController: to control the game in general. Contains the game loop.
HumanPlayerController: to control the user input
ComputerPlayerController: contains the AI of the computer
PlayerController: is an interface with the makeTurn() method. It's implemented by HumanP.C. and ComputerP.C.

HumanPlayerController implements ActionListener too. But what is the right way to access to the GameFrame buttons? I need it for understand which card was chosen.

GameFrame and HumanPlayerController are in different packages. Should i make the JButtons public?


texts: How to check if a pipe placed on a fixed grid size is connected correctly to a neighbor pipe?

texts:
Am looking for a solution (algorithm) to check if an object in a neighbor tile can be connected (i.e transfer power).  Best example I could come up with to make this more clear, is pipes.

I am using a fixed 1 x 1 grid size.  So only one object can occupy that space.  I do not store where objects are in the world, as there could be a lot of them placed down by the player.

Let's say you can place down 4 different types of pipe connectors.  Straight, Right angle, Cross, and T.  These can all be rotated by 90 degrees each rotation on the Y (up) axis.

Like in this example I put together quickly:

In that case above, they all connect correctly, but how do I check that when a pipe is placed down in its final position, it is a valid connection?

So in this image, the Straight pipe is not connected correctly to the T pipe to the right or the Straight pipe above it.  So in a pipe example that might be transferring power, the Straight pipe would not be powered.

If it helps because it's Unity.  I added the directions (I tested by drawing a ray to the direction that it can connect).

Spent some time playing with the "pipe" prototype a bit more.

Each pipe has 4 booleans.  Forward, Back, Left, Right.  These indicate which side the pipe can be connected too.  So for example, a straight pipe that hasn't been rotated can connect left and right.  If the straight pipe gets rotated, then forward and back becomes true, and left and right become false.  This is applied to all pipe types.

When placing a pipe down, a raycast is done in all 4 directions to see if there is another pipe nearby.  So I have access to the neighbor pipes to see which side they can be connected on.  My problem now, is the logic to do the check.

Note:  The 4 raycasts are a one time deal.  It's just to check the neighbors on placement.


texts: Unity - Scripting Runtime Version Option Missing

texts: I have been trying to open and run my couple-months old project in Unity3D, and I'm getting about 500 errors. So idecided to reinstall Unity. On the tutorial for the project, it tells us to make sure the "Scripting Runtime Version" is set to 4.x equivalent. Only problem for me is I cannot see such an option in Unity5.5.4p4. How can I set .NET 4.x in Unity for good?


texts: How do I get an attribute of a function?

texts:
function randArray(arrayName) {
    arln = arrayName.length;
    arst = arrayName[Math.floor(Math.random() * arln)];
    return arst;

}

    create: function(){
        //starts physics engine
        game.physics.startSystem(Phaser.Physics.ARCADE);
        player = game.add.sprite(width/2, height/2, 'player');
        randSpawnItem = game.add.sprite(10, 10, randArray(randItem));
        randSpawnItem2 = game.add.sprite(50, 50, randArray(randItem));

So the randArray function works, and there is nothing wrong with the create. I'm using Phaser, and I'm trying to spawn items randomly (kind of like in Binding of Issac.) I forsee a problem in the future, when I'm detecting for collison, I need to know what item spawned to give the right kind of item to the player. How would I get that third attribute of randSpawnItem or randSpawnItem2, or is there another way to go at this completely? Sorry if that's a noobie question! Didn't know how to word it and didn't find it anywhere else. Thanks in advance for your time.


texts:
Hi I am trying to create a mushroom cloud animation for my strategy game. Something like this. I have been looking at info for creating explosions in general, and the way to go seems to be using 2D sprites and billboarding. However, I don't think this will work in my case as mushroom clouds have a specific orientation, and I am using an arcball camera as my game takes place on a globe.

I've thought about using some kind of particle system, but it seems pretty complicated to make as opposed to using a sprite sheet.

What would be the best way to create a nice looking mushroom cloud?


texts:
I created "main script" and in Start() created simple cube:

GameObject cube = GameObject.CreatePrimitive(PrimitiveType.Cube);
cube.transform.localScale = new Vector3 (1,2,1);
cube.GetComponent<Renderer>().material.color = new Color(0,0,255);
cube.AddComponent<CubeScript>();

and then in CubeScript I have empty Start() and Update() but in onMouseDown() just Debug.Log("click detected");

and I can never see log despite clicking on cube.. Any advice? did I missed something?


texts:
I just finished developing a 2D side scroll game for the IPad using Cocos2d and Box2d.
Now we want to make an IPhone 4 version of the game, but I'm still not sure what is the best way to do it.

I was thinking to just create a new target on my project, remove all the current resources from the Build Phases and create a new Resources folder with all the assets of the game scaled to the new resolution.

Of course this approach would take a lot of work, specially from the designer, since there are a lot of images on the game, 30 levels with 3 layers of parallax, and over 100  animations between all the elements, plus the SVG levels that map physics world (we are using level SVG parser).

I would also have to check all the touch functions and the sprites with a hard coded position (mostly Hud and the Menu). I did tried to use the win Size for this, but I'm pretty sure there are sprites with fixed positions.

I know that checking the Menu and Hud position should not take much time, but I'm worried about the time it could take to scale all the images, and specially the SVG files that map the physics of the game.

I would like to know if I'm in the right path regarding the porting of the game or if there if someone have though of a better easy solution.

I tried modifying the gluLookAt eye z parameter, but this didn't work really well. I haven't work with OpenGL since college around 3 years ago, and I don't remember very well   the math behind the low level pipeline of it. Anyway, I don't think that modifying the Cocos2d rendering steps could work for my problem.


texts: Gun clipping through arm during third-person animation

texts:
I have been setting up a Blend Tree for motion animation in Unity. I'm using Root Motion for now. I parented the gun to the root of the player and then I use OnAnimatorIK to lock the two hands in position.
The overall looks and feel is great by my standards. The only thing I am disappointed about is the butt of the gun clips through the character's upper arm when running.

Is there a way to crop this in the game? I'd like to avoid going into a 3d Editor and making it two separate meshes which I could then I guess somehow disable. I'm hoping there is a better way to handle this situation.
Also I wonder if the gun being parented to the Root player object is wise. I had tried parenting to the 'right-hand' bone but this made the gun point upwards about 45° and looked silly.


texts:
Does such a thing exist or do I have to code one?

My project needs textboxes, buttons, input capture, timings for "press and hold keys" and so on. These are quite standard for a GUI library but hard to code from scratch.

What options do I have?


texts: Where to store polygons and polygon animation?

texts:
I thought about making something with ApeOut graphics long before it came out and its release motivated me to try - I'm having tons of fun but I stumbled upon a pickle.
I can imagine storing polygons is a very common task in game development. I'm prototyping with pygame and currently store each polygon as a list of Vector2 coordinates/vertices on a 10x10 field and keep these lists in a Python dict. This can't be a good practice.

Is there an established format to store list of vertices (preferably supported by some free editor)? I was thinking about SVG but it works with curves and I only need straight edges. Or is SVG still the better option?
What's a sensible way to store frames of an animation for such polygon (e.g. "deer" lowering its head when eating or moving its shoulders while walking, etc.; legs will be driven by invert kinematics)? Right now I'm thinking about each animation being a list of frames where each frame is list of vertices but it'll become unmanageable if I don't separate animations to different files.

What I have so far:
shapes = {
    # I edit this in my head, was fun, slowly becomes a nightmare
    'deer': [(5,0), (4,1), (2,0), (3,1), (2,1), (1,0), (1,1), (4,2), (3,3), (4,5), (3,7), (3,8), (5,10), (7,8), (7,7), (6,5), (7,3), (6,2), (9,1), (9,0), (8,1), (7,1), (8,0), (6,1)],
}

def loadShape(name, size):
    resolution = 10 # 10x10
    verts = shapes.get(name)
    scaled = [tuple((point[0]/resolution*size, point[1]/resolution*size)) for point in verts]
    surface = pygame.Surface((size, size), pygame.SRCALPHA)
    pygame.draw.polygon(surface, colors.get(name), scaled)
    return surface


texts:
i am building a game with 100 levels and these levels are creatable by me and by the player with the level editor.
For example there are some spikes and all their details are in a array of spike_struct.. (i hope you mean how i organize it)
I just want to save the data to a file so

ofstream ofs("data.dat", ios::binary);
ofs.write((char*)&data, sizeof(data));

data is a struct containing

struct datastruct
{
    int spikes[100];
    // number of spikes in 100 levels
    int blocks[100];
    // number of blocks in 100 levels
    spike_struct spike[100][1000];
    //Data of spikes (1000 is the max of spikes in a level and 100 is the max number of levels
    block_struct block[100][1000];
    //same as above
}

This causes an error: SIGSEGV, Segmentation Fault.
I got this in debug mode.

How can i avoid this?


texts:
I'm trying to draw an Earth, as I've found the textures in this site: http://planetpixelemporium.com/earth.html

I loaded the diffuse, specular and bump maps:

let earthGeometry = SCNSphere(radius: radius)

let earthMap = UIImage(named: "Earth_map")
let earthBump = UIImage(named: "Earth_bump")
let earthSpec = UIImage(named: "Earth_specular")

earthGeometry.firstMaterial!.diffuse.contents = earthMap
earthGeometry.firstMaterial!.specular.contents = earthSpec

let earth = SCNNode(geometry: earthGeometry)

But there is no property for the bump map. The only way that comes to my mind is to use a MDLMaterial but I see no way to convert the material back to a SCNMaterial. The method:

+ (instancetype)materialWithMDLMaterial:(MDLMaterial *)mdlMaterial

Runs just in Objective-C and not in Swift. Does anyone know how to convert it to a SCNMaterial, or alternatively to use another way to apply a bump map in a SCNMaterial?


texts: Stretching a texture over multiple faces

texts:
I have a grid of vertices that I'm using as the ground for my game in XNA. I have a effect file / shader which handles texturing and lighting. Right now I have it so the texture tiles across each face of the grid, but the texture i'm using is 4096x4096 and i'd like to have it completely stretched across all the faces of this grid instead of repeating itself over each face. How would I go about doing this?

Thanks


texts: How can I avoid jitter when working with a 2D movement system?

texts:
How can I avoid jitter in Unity?

Let's suppose that I want to create a 2D movement system using a Rigidbody 2D(Dynamic), and I want make the camera follow the character (which is a pixel art sprite).

How can I create a "jitter proof" 2D movement system for 2D pixel art games in Unity?


texts:
I'm trying to control a 3D object (just a box for the moment) moving over a spherical 3D planet, I'm using a Ray to find the triangle in the sphere under the object.
I'm calculating the surface normal and it's working this far but now I want the object to be rotated or just forced to be align according to the surface normal of the triangle from the sphere so that the object's down vector will be in the same angle as the surface normal vector so that it has the right angle against the surface.

I've searched the Internet but haven't succeeded yet after a couple of weeks.
How on earth can I make my object align to the surface normal while moving freely around the planet/sphere?

I'm trying to make like a car driving around on the surface of a sphere.

The question is, how can I align the object to the surface normal?
The code I have this far is to find the triangle under the box, now I would like to align the object to it.

I'm using Monogame in C# VS Studio 2017


texts: How to handle forward/backward movement in an oblique top-down view

texts:
I'm making a pseudo-2D top-down game, where my assets are actually 3d but I use an orthographic projection to introduce more depth.

I saw a picture of how the game "Enter the Gungeon" was actually made in unity 3d.

When I tried doing something likes this I put the camera in orthographic view and after some adjusting I got it to look kind of like this.

The problem is that movement in the z-axis (away / toward the viewpoint, or up and down on the screen) feels very slow because of the whole orthographic thing. You can notice this when moving a player for example.

When I simply increased the speed of the player in the z-axis it felt pretty normal, but I am wondering if that would introduce some unforeseen consequences?

I couldn't find any guides, posts or videos about this. How should I solve this movement problem?


texts: How to skip comparing if one of the value is null?

texts:
I am using libGDX - Ashley as entity-system framework. My problem is I don't know how do I avoid having a java.lang.NullPointerException when using Comparator<Entity> entity comparison. There is a situation where Entity is removed from the engine, but the Comparator is still continuing. Now how do I skip the comparing if one of the nearby is null?

@Override
public int compare(Entity nearby1, Entity nearby2) {
    Vector2 ownerPos = Mapper.transform.get(owner).position;
    Vector2 nearbyPos1 = Mapper.transform.get(nearby1).position; // possible null
    Vector2 nearbyPos2 = Mapper.transform.get(nearby2).position; // possible null
    return ...
}

When I sort the Array<Entity> for example, using my custom comparator, it returns an error because one of the entity is null or one of the component entity is null. I don't know what to return to make the comparison skip.

boolean skip = ownerPos == null || nearbyPos1 == null || nearbyPos2 == null;

if(skip) {
   return ???
}

I'm thinking of using try-catch statement to skip the sorting. But is this performance safe?

try {
   array.sort(comparator);
} catch(Exception e) {

}


texts: Collision Detection Failing at faster Speed?

texts:
I am new to programming so thought I would make a Pac-Man clone to teach myself. I am doing it in C++ using SFML. Anyway, I use a bunch of collision tests. Everything works great.. but if I am going to fast then the collisions simply fail and nothing happens.

Pac-Man is moving though a factor  = velocity * frametime;

I am using SFML rectangles to do the tests... eg...

sf::FloatRect.contains(pacman.getPostion);

This tests a point in space to see if it is inside the rectangle. The point being the centre of pac-man.

So yeah.. I would love to hear any ideas on this!

Thanks in advance
--Jynks

if ( _rectSwitch.getGlobalBounds().contains( PacMan.getPosition().x, PacMan.getPosition().y )


texts: How do I implement a flashlight in SDL2?

texts:
I'm a beginner trying to implement a flashlight in SDL2, but can't figure out a good way to do it.

I've found a way to manipulate the background's color; changed it to dark and back to its normal colors, but this isn't the whole solution.

My main goal is a flashlight that follows the player around the map.

I thought about per-pixel drawing, but I think it will result in poor performance. Drawing a black pixel for every pixel on screen, then changing back the to the normal color to all of the pixels surrounding the player.

How do I do this correctly?(BTW, I'm using a 'SDL_Renderer', not 'SDL_Surface', i realized this can be a problem when dealing with pixels.)


texts:
So I'm trying to make a camera zoom in, but Thread.Sleep doesn't work.
Here is the code:
    void Start() {
    for (int a = 0; a > 1000; a = a + 1)
    {
        Debug.Log("Done!");
        Thread.Sleep(100);
    }
}

The error code is this:
Assets\StartScene\CamScript.cs(12,13): error CS0103: The name 'Thread' does not exist in the current context


texts: Unity 3D error when compiling to WebGL: Destination directory not found

texts:
When I try to compile my Unity project to WebGL in Development mode on Windows 8.1 (and with the latest version of Unity), I receive the following errors (the first one is truncated because it's really long; I can post it upon request).

DirectoryNotFoundException: Destination directory not found: Temp/StagingArea/Data/ResourcesSystem.IO.File.Copy (System.String sourceFileName, System.String destFileName, Boolean overwrite)...
Error building Player: DirectoryNotFoundException: Destination directory not found: Temp/StagingArea/Data/Resources

There's no output; the directory I'm attempting to build my project in is empty.  A forum post somewhere suggested I run Unity in Administrator mode, but if that had worked I wouldn't be posting here for help.


texts: How to stop several coroutines running on array of game objects

texts:
In the code below, I am running a coroutine on each element of an array of game objects. How can I stop running the FadeToForEnemy coroutine on each game object?

    IEnumerator EnemyCycle()    {
    while (isRepeating)
    {

        for (int j = 0; j < enemies.Length; j++) {

            Enemy currentEnemy = enemies [j];
            var _myMaterial = currentEnemy.GetComponent<Renderer>().material;
            var _currentFade = StartCoroutine(FadeToForEnemy(_myMaterial, 0f, 1f, currentEnemy.gameObject, false));

        }

        yield return new WaitForSeconds (hdTime);

        for (int j = 0; j < enemies.Length; j++) {

            Enemy currentEnemy = enemies [j];
            var _myMaterial = currentEnemy.GetComponent<Renderer>().material;
            var _currentFade = StartCoroutine(FadeToForEnemy(_myMaterial, 1f, 1f, currentEnemy.gameObject, true));

        yield return new WaitForSeconds (srTime);

        }
    }
}

UPDATE

I tried stopping the coroutines in the following but the cycle of fading in and out just continued.

public void StopEnemyCycles ()  {
    for (int i = 0; i < enemies.Length; i++) {
        enemies [i].StopAllCoroutines ();
    }
    StopCoroutine ("EnemyCycle");

}

Also below is FadeToForEnemy:

    IEnumerator FadeToForEnemy(Material material, float targetOpacity, float duration, GameObject gameObj, bool isEnabled) {

    // Cache the current color of the material, and its initiql opacity.
    Color color = material.color;
    float startOpacity = color.a;

    // Track how many seconds we've been fading.
    float t = 0;
    if (isEnabled) {
        gameObj.GetComponent<BoxCollider2D> ().enabled = isEnabled;

    }

    while(t < duration) {
        // Step the fade forward one frame.
        t += Time.deltaTime;
        // Turn the time into an interpolation factor between 0 and 1.
        float blend = Mathf.Clamp01(t / duration);

        // Blend to the corresponding opacity between start & target.
        color.a = Mathf.Lerp(startOpacity, targetOpacity, blend);

        // Apply the resulting color to the material.
        material.color = color;

        // Wait one frame, and repeat.
        yield return null;

    }

    if (!isEnabled) {
        gameObj.GetComponent<BoxCollider2D> ().enabled = isEnabled;

    }
}

I have several groups of enemies, each group fades in and out at the same time.


texts:
I have been working on some simple XNA proof of concept for a game idea I have as well as just to further my learning in XNA. However, i seem to be stuck on these dreaded normals, and using the BasicEffect with default lighting i can't seem to tell if my normals are being calculated correctly, hence the question.

I'm mainly drawing cubes at the moment, I'm using a triangle list and a VertexBuffer to get the job done. The north face of my cube has two polygons and 6 vectors:

Vector3 startPosition = new Vector3(0,0,0);
corners[0] = startPosition; // This is the start position. Block size is 5.
            corners[1] = new Vector3(startPosition.X, startPosition.Y + BLOCK_SIZE, startPosition.Z);
            corners[2] = new Vector3(startPosition.X + BLOCK_SIZE, startPosition.Y, startPosition.Z);
            corners[3] = new Vector3(startPosition.X + BLOCK_SIZE, startPosition.Y + BLOCK_SIZE, startPosition.Z);

            verts[0] = new VertexPositionNormalTexture(corners[0], normals[0], textCoordBR);
            verts[1] = new VertexPositionNormalTexture(corners[1], normals[0], textCoordTR);
            verts[2] = new VertexPositionNormalTexture(corners[2], normals[0], textCoordBL);
            verts[3] = new VertexPositionNormalTexture(corners[3], normals[0], textCoordTL);
            verts[4] = new VertexPositionNormalTexture(corners[2], normals[0], textCoordBL);
            verts[5] = new VertexPositionNormalTexture(corners[1], normals[0], textCoordTR);

Using those coordinates I want to generate the normal for the north face, I have no clue how to get the average of all those vectors and create a normal for the two polygons that it makes.

Here is what i tried:

            normals[0] = Vector3.Cross(corners[1], corners[2]);
            normals[0].Normalize();

It seems like its correct, but then using the same thing for other sides of the cube the lighting effect seems weird, and not cohesive with where i think the light source is coming from, not really sure with the BasicEffect.

Am I doing this right? Can anyone explain in lay mans terms how normals are calculated. Any help is much appreciated.

Note: I tried going through Riemers and such to figure it out with no luck, it seems no one really goes over the math well enough. Thanks!


texts: Which elements make some maps in multiplayer FPS games more fun than others?

texts:
I'm working on a sci-fi multiplayer FPS game, and am currently designing maps with layout influences from the 2015 Star Wars: Battlefront game and from the original Halo CE game, as those games have the maps which I find very enjoyable.  When I was building the map layouts for my game, I started to wonder why I was looking at these older games for reference instead of, say,  maps from these games's sequels.  I know that the enjoyability of certain maps is subjective, but there's a big difference in the amount of fun my friends and I have had playing the maps in these specific games instead of the newer sequels.  Something about the maps in these games provides an inherently fun, memorable experience, and some newer games (like Battlefront II or Halo V) lack that experience.  Maybe some of these maps aren't really anything special, but  I know that certain maps like Blood Gulch have been praised by fans for years.

What makes these maps so memorable and fun to play on multiplayer?  Is it a product of the developers' map-making experience and the resources of the large  companies (the Battlefront devs went to Iceland for reference), or are there specific layout styles and/or structures that are known to provide interesting close-quarters scenarios?  Is there an intangible quality to good maps?


texts: How to save a global reference of an instantiated gameobject?

texts:
In my game, when I instantiate a particular prefab, I need to show a GUI window, then let player do some actions, finally close that window and update the caller GameObject with the info inserted from user.

So my question is: how to save the reference of the GameObject caller to update it at the end of the user action.

Consider that I call some sub functions and I don't want to pass a GameObject through all functions.

Is there a way to save a gameObject reference in a global variable ? I'm using a static class for that purpose.


texts:
Possible Duplicate:
  How do I detect ledges?

I'm working on a 2D platformer using XNA and Farseer. I would like the player's character to be able to grab and climb up ledges. Detecting a collision between the player and the side of a wall is simple enough with the OnCollision delegate, but I have to admit I'm a bit stumped on how to detect that there's enough clearance for the PC to mount the ledge.

Essentially, I want to ensure there's an appropriately sized rectangle above and to the left or right of the PC (depending on their direction) and I'm not sure how I would check for such a space.

Any suggestions on how to determine there is nothing in the simulated world within some bounding rectangle?


texts: How do I raycast to detect which hexagonal tile was clicked?

texts:
I want to detect the hexagonal tile a unit is on upon clicking on the unit. I was thinking of using a ray cast I can't  get it to work.

I'm trying to get the raycast to shoot from the bottom of the unit and change the material of the collided object.

if (Input.GetMouseButtonDown (0)) {

    Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
    RaycastHit hit;

    if(Physics.Raycast(ray, out hit)){

        Debug.Log (hit);

        string hitTag = hit.transform.tag;

        if(hitTag == "player"){

            if(Physics.Raycast(user.transform.position,Vector3.down,10)){

                Debug.Log ("I'm on something!");

                hit.collider.renderer.material.color = Color.red;

            }
        }
    }
}

What might be going wrong?


texts:
When you initially launch Minecraft you open the "launcher", which will check if your client is up to date. If it's not it proceeds to download the latest files & then runs the game.

How does this happen? Is the launcher a separate application, which can execute the main jar file?


texts:
I am revamping an engine I have been working on and off on for the last few weeks to use a directional vector to dictate direction; this way I can dictate the displacement based on a direction. However, the issue I am trying to overcome is the following problem; the speed towards X and speed towards Y are unrelated to one another. If gravity pulls the object down by an increasing velocity my velocity towards the X should not change. This is very easy to implement if my speed is broken into a Vector datatype, Vector.X dictates one direction Vector.Y dictates the other (assuming we are not concerned about the Z axis). However, this defeats the purpose of the directional vector because:

  SpeedX = 10
  SpeedY = 15

  [1, 1] normalized = ~[0.7, 0.7]

  [0.7, 0.7] * [10, 15] = [7, 10.5]

As you can see my direction is now "scaled" to my speed which is no  longer the direction that I want to be moving in.

I am very new to vector math and this is a learning project for me. I looked around a little bit on the internet but I still want to figure out things on my own (not just look at an example and copy off it). Is there way around this? Using a directional vector is extremely useful but I am a little bit stumped at this problem. I am sorry if my mathematical understanding maybe completely wrong.


texts: How to create animations for a game like Creative kill chamber?

texts:
Lately, I have been playing Creative kill chamber game (https://www.youtube.com/watch?v=SW6PyOy34fY). This game is a flash game where gameplay is "hardcoded". I mean, it is a game where player can access a set of otpions in each situation and an animation is played as the result. The tree of possible paths gameplay can follow is small and finite and more important, it is totally deterministic.

My main question is, how do this guys create this type of animations? Are all they created using the time line? Are they using some kind of logic in code? I'm not used to flash so, can't say if this kind of animations can be quickly done.

On the other hand, if this animations are 99% done using just the timeline what tool would you use in unity to achieve something like this? The Dopesheet doesn't seem versatile enough.

Cheers.


texts:
I have in my model, a list of Classes : Player, NonPlayerCharacter, Monster, Item, NonMovableItem etc

With AndEngine I've a list of sprite for each piece of my model,

How can I manage the relashionship between my model's classes and the graphical elements, what is the degree of abstaction recommended  for my problem?

One sprite for one Model
or one Model for one Sprite or n for n

for exemple If I do drag&drop have I to make abstraction of the Sprite Class, another exemple a map is a List of sprite or a list of element of my model?