texts:
I'm fairly new to Unity and I can't really get my head around the best way to communicate between scripts.  For example, if the character jumps, what is the best way to inform other scripts (such as ground objects) to act on the characters velocity and move.

I recently had a look at this which describes how to make a messaging system.  My problem with this, is that I'm not sure how to pass arguments when triggering events.

For example, If I wanted to do:

if (Input.GetButtonDown("Fire1")){
    EventManager.TriggerEvent("Jump", jumpVelocity);
}

...

EventManager.StartListening("Jump", OnJump);

void OnJump(velocity)
{
    //scroll ground objects horizontally
}

How could I add arguments to a messaging system, or would there be a better way?


texts: Unity based washing/ cleaning game advice

texts:
I'm thinking about a way I can create a washing/ cleaning game as part of a project I'm working on within Unity, but given my lack of experience, I'm having trouble knowing where to start.

The goal is to be able to apply an effect of some kind to a Spine based character - which has a default 'idle' animation, and have the touch/ mouse positions remove the parts of the effect according to those positions.

I'm unsure how to go about creating such an effect - would I need to create a 'dirty' version of each sprite image used within the Spine imported character and make parts of it transparent, or would something like a shader be suitable?

While I have a lot of experience with C#, I have little experience with Unity, and having Googled for examples or tutorials or creating something like this, I'm left no better off...

I was hoping for some advice or pointers from the community...

Thanks!
Kieron


texts: Performance Difference Between Content.Load and Texture.FromStream xna

texts: Is there any performance difference between Texture2Ds loaded using the content pipeline and Texture2Ds loaded using Texture2D.FromStream()?


texts:
I am making a game using OpenGL ES 1.0 and I want to keep player score. So I need to draw text dinamically. What is the best approach? Some library, textures, bitmaps?
I tried to use TextView but when I want to update text I need to do that from main thread, and there is an obvious lag in the game.


texts: How to make an authoritative multiplayer game deterministic for all clients?

texts:
I'm starting to create a multiplayer online game, with an authoritative server. As it is, the clients send inputs to the server which do the simulation and then send back to clients the updated state. The game is a top-down shooter, so it's fast-paced and input lags are not allowed here, so to avoid this I'm doing the simulation on the client too, and when the server update come back I compare the local simulation with the server response. If they are compatible everything is fine, otherwise, the client version is corrected.

I was expecting that the client simulation desync at some point, because of all of the variables on physics, floating points, network etc... But this happens much more than I thought.

Just by sending the inputs and simulating on the server, the results are very different, even on simple movements, like forwards and backwards on a clear space.

Green is local, red is server response

I need help on this step, a way of keeping, at least this kind of simple movement, consistent on the server and the clients.


texts: How do I get the axes for SAT collision detection

texts: In SAT collision detection how do I calculate the axes for projection?


texts: Adjusting view matrix when glViewPort & resizing

texts:
I have an issue when my window resizes.

I have a simple MVP shader like this

gl_Position = projection * view * model * vec4(in_Position, 1.0);

to render a map in my game scene. The map is extremely simple that it simply offers a lane's vertex. And what I need to do is drawing it inside the window.

So I set up my MVP matrix individually, the "view" and "model" matrix remains the same because all I want to do is drawing a static map. "perspective" is the only matrix need to change since I want to have a zoom feature that I can zoom in/out by changing fovy. "perspective" is updated by calling

glm::perspective(glm::radians(fovy), (float)width/height, near, far)

and my view matrix is calculated by

glm::lookAt(camera_pos, camera_pos + camera_front, camera_up)

However, when I resize the viewport, I find everything changed. I mean by default, the resolution gonna drop when my window goes larger if I didn't do anything(like updating the glViewPort()). But the behavior I wanna achieve is like

"I could see more part of the map when I made my window size larger".

Therefore I believe that I should keep my viewport resolution same (glViewPort(0, 0, screen_width, screen_height)). And updating perspective matrix by changing the ratio when new window's width and height comes in. Then the final step is to update the camera's position to update view matrix. However I stuck here for a while coz I don't know how to adjust it. I believe this is a common issue but I cannot even find a source talking about it.

Do I think it the wrong way? Do I need to change Camera's position to update my view matrix to achieve the resize behavior?

Platform: Ubuntu 16.04, OpenGL3.3 , C++14


texts: What are the makings of a good Character

texts: What properties make the main character of a game such that players can easily identify with it? Can the same set properties be used when designing the NPC characters players interact with, or should a different set of properties be considered?


texts:
I'm looking to replicate a procedural terrain effect I found on a portfolio/blog site a few days ago.

Quoting the site, the terracing was generated through, "multiplying [the final height] by some damping value within a certain height range, to create beautiful canyon features."

I was wondering, would anyone be able to provide a more technical example or procedure for going about this? Over the past week, I've been researching and learning a lot about procedural terrain/texture methods and practices but I still haven't come across anything that explains in detail what 'clamping' is, and I'm starting to become frustrated.


texts: How to import animations from one model to others

texts:
I have two models (one animation in each) which I got for free from Mixamo. I imported them in Unity and they look like this:

http://imgur.com/atjQbkI

Justin@Idle and Justin@Walking.

As can be seen from the picture, they both contain only one animation (idle and walking). But in my scene I have a couple of other character models.

But I am unable to get these two animations (idle and walking) to work on any of those models at all. (I am pretty confident that they have the same skeleton, since they are coming from the same 'pack').

What are the steps I need to do in order to get these two animations to work on every character and I can trigger them by scripting in c#?

I figured out that I need to make the .fbx rig as 'Humanoid' I suppose, but since these .fbx files don't contain the animations the Animations tab does not contain anything.

This picture shows my situation: http://imgur.com/DuTQJoK

I would like to write in my code something like this:

npcObj.GetComponent<Animation>().animation.Play("idle");

or

npcObj.GetComponent<Animation>().animation.Play("walking");

I tried adding the animations in an Animation component and calling them in script like this, but the model keeps having its T-pose.

Thanks to whoever can help me!


texts: Minimap Render texture Mouse Hover Detect on 3d Object in world space

texts:
I have a resizeable minimap which is based on render texture. A camera rendering 3d space on Render Texture and then I used the texture as minimap. Now, I have a specific requirement to identify mouse hover on an object in Minimap(render texture). It may sound silly but I have to show some object information on minimap on mouse hover like a tooltip.
In 3d space or world space, I have several objects and they are showing on minimap. Now if any user mouse-hover on the same object on minimap then I want to show tooltip. Is this possible to get 3d space information from render texture?


texts:
I have game play scene in which user can zoom in and out. For which I used smooth camera in the following manner.

           public static final int CAMERA_WIDTH = 1024;
           public static final int CAMERA_HEIGHT = 600;
           public static final float MAXIMUM_VELOCITY_X = 400f;
           public static final float MAXIMUM_VELOCITY_Y = 400f;
           public static final float ZOOM_FACTOR_CHANGE = 1f;

            mSmoothCamera = new SmoothCamera(0, 0, Constants.CAMERA_WIDTH,
                            Constants.CAMERA_HEIGHT, Constants.MAXIMUM_VELOCITY_X,
                            Constants.MAXIMUM_VELOCITY_Y, Constants.ZOOM_FACTOR_CHANGE);
            mSmoothCamera.setBounds(0f, 0f, Constants.CAMERA_WIDTH,
                            Constants.CAMERA_HEIGHT);

But above thing create problem for me. When user perform zoom in and leave game play scene then other scene behaviour not look good. I already set zoom factor to 1 for this purpose. But now it show camera translation in other scene. Because scene switching time it so much small that player can easily saw translation of camera that I don't want to show. After camera reposition, everything works perfect but how to set camera its proper position.

For example my loading text move from bottom to top or vice versa based on camera movement.

Any more detail you want then I can able to give you.


texts:
So I've recently noticed how great FreeTime Unlimited is for my daughter. There's no ads, no in-app purchases, etc. She can just play the games/apps and I don't have to worry about it.

As a develop I thinking it could an interesting avenue to go down, but there's a few things that I for the life of me can't get Amazon support/forums to answer in any logical manner.

So the idea according to their information is that the apps are highly scrutinized to verify they are child friendly content, which is excellent. Also, you can't use webviews, ads, or in-app purchases.

My question is: How do devs monetize these applications? Clearly they're not just giving away their work for free? The only logical answer I can guess at, is that it uses the Amazon Underground scheme of earning $$ based on the amount of time the user spends in the app/game??

Does anyone have and actual experience or information on this? As I said, I've reached out to multiple people at Amazon, and keep getting the runaround with all of them pointing me to the same useless link.


texts: Hide back button bar of android mobile while playing game

texts:
I just want to hide back button bar of android mobile while playing the game.

I tried to make it close by pressing back button,it getting close but its always visible.
please help..


texts: Store and retrieve different objects on a tile

texts:
(I hope the title is clear enough, if not feel free to suggest a better one)

I'm trying to make a simple tile-based map for a college project in Java. But I'm stuck on how to literally place things on my map. On the programming side of things, I still haven't got into graphics on this. As of now I have:

A "Robot" class, which implements an "Attackable" and "Spawnable" interface, the robot can attack and moved

A "Obstacle" class, the obstacle too can be attacked, so it implements Attackable, Spawnable, but it also can be pushed by a robot (methods by the class itself).

A "Station", which is nor attacable nor can be pushed, so it only implements Spawnable and other specific methods.

A "GameWorld" class which hold the map (a 2D array of Tiles) and various methods.
A "Tile" class (which is arrayed to create the map). It has a boolean "Occupied" (which doubles as a collision too). Previously it stored just a single Attackable variable, because both Obstacles and Robot can be attacked, so I just tought it would be easy to just store them as such on the map for when I need to attack something, and then use some other reference to Robot instances when I need to move the robots and have a reference to the station in GameWorld in order to use that. But then I remembered that the Obstacles need to be moved too, so it wouldn't really work.

Now I'm thinking about having two maps, basically, an AttackableMap[][] for the attackable object (which would store both robots and the obstacles) and a ObstaclesMap[][] for the obstacles alone (with tiles occupied by robots set as occupied). Which would obviously mean having two tile classes, one to hold each kind of object.

But it feels cheap, I think. It uses a lot of memory and I think it might be hard to render at a later time. But having only one map would mean having to check what kind of object I'm getting and I'd have to do loads of casts and I want to avoid that.

So, I think, there must be a better way to do this. How do other people do it then? So basically my question is... How can I store different "things" on a tilemap in a better way? Is there some technique widely used?

What I've come up with feels rigid, if I wanted to add another kind of object that can be placed on the map (like a mine) I would need to create another map entirely, another tile, write new methods... There must be some flexible (and not too complex) way to have some freedom in this aspect.


texts: Drawing a dynamic indicator for a field of view

texts:
My goal is to draw a dynamic indicator for a cube, which represents the field of view. The ideal indicator would look the same as in Metal Gear Solid(the blue ones):

From what I have gathered, I need an angle and a length for the indicator as such for a 50° FoV:

Now my issue is what method should I use to draw the indicator? A procedural mesh or is there a less demanding way of doing this?


texts:
I'm a little confused with using indexed vbos in opengl. I understand that different each vertex can only have one uv. How would it be possible to map a texture onto a 3d object if you can't "unwrap" the object? Here's what I mean:

3D pyramid with 4 vertices, 4 uv coordinates

3D pyramid unwrapped, 3 shared vertices, 3 unshared vertices

It is impossible to map a texture to it without having more uv coordinates, right?

Is there a solution to this problem while still using indexed vbos? Can I make this work with only 4 vertices?


texts: Farseer: Only allow the collision one time with the object

texts: I have there serveral platforms. I would like to allow the player to collide only one time with the object! Hope you can help me


texts: How should I setup my sprites for 2D combat?

texts:
I was painting pixel sprites of a goblin (the enemies in the game). I first thought of making sprites of it for each different scenario:
facing camera, moving toward camera 1, moving toward camera 2,
facing camera with sword, moving toward camera with sword 1, moving toward camera with sword 2,
facing left, going left 1, going left 2
facing left with sword etc.
(for a total of 18 sprites)

Then I wondered, how will I make the sword hit the player ? What if I want the goblin to have a different type of sword ? Do I have to make different sprites of it holding different weapon ?
I realised doing sprites for every scenario wasn't ideal. So my question is, how do I make this ?
Should I keep the sprites I have but remove the sword from them and then add a sword sprite attached to the player sprite and animating it so it matches the players movement ? Is that the way to go ?


texts: Increasing flexibility of a data passing system in a component based entity system

texts:
I'm creating a Component orientated system for a small game I'm developing. The basic structure is as follows: Every object in the game is composed of a "GameEntity"; a container holding a vector of pointers to items in the "Component" class.

Components and entities communicate with one another by calling the send method in a component's parent GameEntity class. The send method is a template which has two parameters, a Command (which is an enum which includes instructions such as STEP_TIME and the like), and a data parameter of generic type 'T'. The send function loops through the Component* vector and calls each's component's receive message, which due to the template use conveniently calls the overloaded receive method which corresponds to data type T.

Where the problem comes in however (or rather the inconvenience), is that the Component class is a pure virtual function and will always be extended. Because of the practical limitation of not allowing template functions to be virtualised, I would have to declare a virtual receive function in the header for each and every data type which could conceivably be used by a component. This is not very flexible nor extensible, and moreover at least to me seems to be a violation of the OO programming ethos of not duplicating code unnecessarily.

So my question is, how can I modify the code stubs provided below to make my component orientated object structure as flexible as possible without using a method which violates best coding practises

Here is the pertinent header stubs of each class and an example of in what ways an extended component class might be used, to provide some context for my problem:

Game Entity class:

class Component;

class GameEntity
{

public:
GameEntity(string entityName, int entityID, int layer);

~GameEntity(void){};

//Adds a pointer to a component to the components vector.
void addComponent (Component* component);

void removeComponent(Component*);

    //A template to allow values of any type to be passed to components
template<typename T>
void send(Component::Command command,T value){
       //Iterates through the vector, calling the receive method for each component
    for(std::vector<Component*>::iterator it =components.begin();  it!=components.end();it++){
        (*it)->receive(command,value);
    }
}
private:
     vector <Component*> components;

};

Component Class:

#include "GameEntity.h"
class Component
{
public:
static enum Command{STEP_TIME, TOGGLE_ANTI_ALIAS, REPLACE_SPRITE};

Component(GameEntity* parent)
    {this->compParent=parent;};

virtual ~Component (void){};

GameEntity* parent(){
    return compParent;
}
void setParent(GameEntity* parent){
    this->compParent=parent;
}

virtual void receive(Command command,int value)=0;
virtual void receive(Command command,string value)=0;
virtual void receive(Command command,double value)=0;
virtual void receive(Command command,Sprite value)=0;
    //ETC. For each and every data type

private:
GameEntity* compParent;

};

A possible extension of the Component class:

#include "Sprite.h"
#include "Component.h"
class GraphicsComponent: Component{
    public:
          GraphicsComponent(Sprite sprite, string name, GameEntity* parent);
          virtual void receive(Command command, Sprite value){
                 switch(command){
                      case REPLACE_SPRITE: this->sprite=value; break
                 }
           }

    private:
          Spite sprite;

}

Should I use a void pointer and cast it as the appropriate type? This might be feasible as in most cases the type will be known from the command, but again is not very flexible.


texts: unity - problem in limiting rotation of object?

texts:
I am trying to make a game with unity.

In this game, player uses mouse to rotate a container or box around x and z (rotate to left and right and also toward the camera and opposite).

I used below code to control movement and limit it.

float zRot = transform.eulerAngles.z;
float xRot = transform.eulerAngles.x;
float yRot = transform.eulerAngles.y;
Debug.Log (
  "xDir : "  + xRot.ToString() +
  " yDir : " + yRot.ToString() +
  " zDir : " + zRot.ToString() );

if ((xRot >= 330 || xRot <= 30) && (zRot >= 330 || zRot <= 30)) {
  transform.Rotate (Input.GetAxis ("Mouse Y"), 0, -Input.GetAxis ("Mouse X"));
}
else {
  Debug.Log(xRot.ToString() + "  " + zRot.ToString ());

  transform.Rotate (-transform.rotation.x , transform.rotation.y,-transform.rotation.z );
}

The contatiner rotate 60 degrees in x and z and when it gets to the limits it stops, which is what I want. However when I rotate in both direction to the near the limits (330 or 30), the contatiner becomes out of control and it rotates freely and constantly. It's like the contatiner has passed the limits.

The questions are:

Did I used a good approach to limit the rotation and how to stop the object completely when it get to the limit of rotation?
When and why the object becomes out of control exactly?


texts:
I am trying to find out the distance between game objects and the player position using Job System, But I am getting an error of unsafe pointer race condition. Can anyone tell me how to access transform in job system? to measure distance.
 Following is the code.

struct PositionUpdateJob : IJobParallelForTransform

{

    public TransformAccessArray Object;

    public float DIst;

    public void Execute(int i, TransformAccess transform)

    {

         DIst = (transform.position- Object[0].position ).sqrMagnitude;
        if (DIst < 20)
        {
           // Do Something
        }
    }

}

This is the Main script which measures gameObject position against its children

public Transform Player;
public List<Transform> ChildList = new List<Transform>();
public TransformAccessArray Transformz;
public float Dist;
PositionUpdateJob m_Job;
JobHandle m_PositionJobHandle;
public TransformAccessArray Mey;
void Start ()
{
    Transformz = new TransformAccessArray(0, -1);
    Mey = new TransformAccessArray(0,-1);
    Mey.Add(transform);
    GetChildRecursive(gameObject);
    }
private void GetChildRecursive(GameObject obj)
{
 //To Get All childrens for transform access array
}
void Update()
{
    m_PositionJobHandle.Complete();
    m_Job = new PositionUpdateJob()
    {
        DIst = Dist,
        Object = Mey
};
    m_Job.Schedule(Transformz);
  }
private void LateUpdate()
{
    m_PositionJobHandle.Complete();
    Transformz.Dispose();
}


texts: supporting multiple resolutions on mobile (cocos2d, ios)

texts:
I am looking into ios game development and the first question that comes to mind is how to support the growing number of iphone resolutions.

I have seen the Unity strategy of normalized screen coordinates, but all of the cocos2d tutorials I look at seem to hard code pixel positions.  How does this work with iphone 4 , 5, 6, 6+ all having different resolutions? (4 vs 6 is a major difference)

Is there a common practice for dealing with this?


texts: Procedural terrain generation zooming principle

texts:
I am asking myself how to solve the granularity of terrain by zooming into it.

My idea is to create very first just a square represented by four vertices and 6 indices.
By zooming in the square is divided into smaller squares each representing a chunk.
My question is now: Do I have to scale the whole quad or do I have to generate in the very first state just a very big square?

And how is the granularity of terrain determined?
By distance obviously, but what is the formula?

I thank You in advance!


texts: Why are extra assets left in the final game?

texts:
I was just reading about what was discovered in the files for No Man's Sky, a lot of things that weren't used or relevant to the game. I also read a short while ago about the E3 settings being left in the Watch Dogs files. Why do game developers leave old and unused files in the final game?

Surely this just takes up extra space on a disc and means more data has to be downloaded if you download the game?

Also, aren't the developers afraid of what people could find?


texts:
I'm currently creating a menu for my project and I'm trying to get the textures to blend so I'm only left with the actual Image on the texture and not the background. The problem is the whole texture is somewhat transparent, it's not just removing the background.

My RGBA texture looks like

And the black background needs to be removed from the image.

I was using GL_SRC_ALPHA, GL_ONE_MINUS_SRC, ALPHA for my blend function but it wasn't blending anything. I changed to GL_ONE, GL_ONE and now I'm at where I am now.

You can see the text is there but its also transparent, but the background has been removed which is good.

This is how i'm drawing my button. The world behind it is drawn after (i've tried switching order didnt change anything) and it's drawn using VBO's whereas the Buttons are drawn in immediate mode.

glEnable(GL_BLEND);
glBlendFunc(GL_ONE, GL_ONE);[/left]
// get button pos
Point3<float> pos = button->getPos();
// get button dimensions
int width = button->getWidth();
int height = button->getHeight();
// bind button texture and draw quad
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, button->getState() ? button->getDownTex()-
>getTextureID() : button->getUpTex()->getTextureID());
glBegin(GL_QUADS);
glTexCoord2i(0, 1); glVertex3f(pos.x, pos.y, 0.0f);
glTexCoord2i(1, 1); glVertex3f(pos.x + width, pos.y, 0.0f);
glTexCoord2i(1, 0); glVertex3f(pos.x + width, pos.y + height, 0.0f);
glTexCoord2i(0, 0); glVertex3f(pos.x, pos.y + height, 0.0f);
glEnd();

I'm using sdl to load the texture

SDL_Surface* image = IMG_Load(textureName);
data.m_w = image->w;
data.m_h = image->h;
data.m_bitsPerPixel = image->format->BitsPerPixel;
data.m_alpha = image->format->alpha;
int colourMode = image->format->BytesPerPixel;
if (colourMode == 4)
   internalFormat = GL_RGBA;
if (colourMode == 3)
   internalFormat = GL_RGB;
if (colourMode == 1)
   internalFormat = GL_LUMINANCE;
if (SDL_BYTEORDER == SDL_LIL_ENDIAN)
{
if (colourMode == 4)
  format = GL_BGRA;
else
  format = GL_BGR;
}
else
{
if (colourMode == 4)
  format = GL_RGBA;
else
  format = GL_RGB;
}
GLuint texture = -1; // create texture handle
glGenTextures(1, &texture);    // gen texture
bindTexture(GL_TEXTURE_2D, texture);
glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
glTexImage2D(GL_TEXTURE_2D, 0, internalFormat, image->w, image->h, 0, format,
GL_UNSIGNED_BYTE, image->pixels); // normal texture


texts: How to make a simple score system for my game?

texts: I'm making a simple game and I can't seem to impliment a simple score system. As the object moves 10 units forward the score should increase by 10. My issue is that when I turn the object around and move backwards the score decreases.


texts: Color sprite tint with opacity in MonoGame/XNA

texts:
In MonoGame I am using SpriteBatch to draw sprites. I want to create a semi transparent overlay that would 'tint' the sprite with a given color. SpriteBatch.Draw accepts Color parameter that allows to specify the tint, however the alpha channel seems to make the whole sprite transparent (not the tint only).

To address the problem i am overlaying my sprites with another white, semitransparent sprite tinted to a given color. It works as expected, but I am not sure if that is the correct (and most optimal) approach.

Can you suggest better/faster technique?


texts: Using a mesh stencil with 2D lighting in the Universal Render Pipeline

texts:
I've followed the CodeMonkey tutorial on using a dynamic mesh as a stencil for a field of view or visibility polygon effect, and have got it working using the latest version of Unity and its Universal Render Pipeline  (I believe this uses a Forward Renderer).
I'd like to use the 2D lighting and this requires a 2D Renderer, which I have also got working.
Unfortunately I can't figure out a way of combining these.  I've got a Universal RenderPipeline and added my 2D Renderer and the Forward Renderer to the renderer list, but it only allows one of these to work (I'd assumed it would trigger in order).
How can I get both of these effects working together, or if it isn't possible, is there a recommended approach for combining 2D lighting and stencil masking?


texts:
I am writing a 2D game in Unity and I want to offer an old-school style title screen demo (such as in Super Mario, etc.) where it shows a brief run through of either one or various levels. How would I accomplish this?

If anyone can either enlighten me or point me to some further reading then it would be very welcome.


texts: What is best method for 2D pathfinding in procedural world?

texts:
I have been researching path-finding for 2D games and would like to create a system that allows A* to perform as best as possible over a near infinite world. This system is intended to manage not only the player's character but other AI that would wander the world in search of resources.

So far I have made grid based A* that I then modified into Theta* to smooth out the path. But I would like to change that to use navmeshes so I can reduce as many nodes as possible. I have looked in to delaunay triangulation and fortune's algorithm for voronoi but am unsure how that works on a large scale where I would want to generate more navmesh as the world is explored.

I have also considered quadtrees but they seem slower then navmeshes.

So my main question is, what would work on a near infinite procedurally generated world? And what is fastest quadtrees or navmeshes? If navmeshes are faster, are polygons better than triangles?

Thanks for any help!


texts: How can I properly detect my cars collisions using hitboxes?

texts:
I have created two car objects and their current speed is represented as the len variable.

This is the code:

Under Blue Car Collision Event:

if (place_meeting(x,y,obj_CarRed)) { // Checking Collision
    len = 0 //Current speed
    if (len < obj_carRed.len) { // Blue Car's current speed is greater than Red's
        myHP -= obj_carRed.len/2
    }
}

So I copied the code to the other object and replaced Red with Blue. When the Red car crashes into the Blue car, the Blue car takes damage because the Red car is traveling faster than the Blue car. But when the Blue car crashes into the Red car, the Red car won't take any damage.

Later, I thought about using a Hitbox and have it as a parent for both cars, but I don't know if it would mess up the collisions, and I don't know how to tell the hitbox that it's been created by Blue Car, or by Red Car. I don't know if I should make a new hitbox for each car or one for both.


texts:
I want to use bone animations in my 2D game for Unity (5.0 beta). I am trying Spriter. Apparently, it has no official Unity support. There was some guy, back in 2014, who posted a plugin to convert Spriter files to Unity prefabs here: http://brashmonkey.com/forum/index.php?/topic/3365-spriter-for-unity-43-updated-integrated/.

However, the plugin does not seem to work (perhaps it is because I am using 5.0 beta).

There are deprecated lines, like

AnimationUtility.SetAnimationType(animClip, ModelImporterAnimationType.Generic);

Or

 UnityEditor.Animations.AnimatorController.AddAnimationClipToController(controller, animationClip);

If you remove them, of course it won't be able to properly export your files.

So my question is: is there a reasonable to use Spriter animations in Unity? I know I could just export to a spritesheet, but I was hoping to use bones for super fluid animations (I have several characters so I don't really want to make lots of spritesheets). Or perhaps there is a better bone-based solution for 2D animation in Unity?


texts: What is the best way to keep track of time in a game?

texts:
I'm getting to the part in development where I'm noticing that timing is going to be an issue.

If I put my movement update in the same function where I draw the scene, then a low FPS means slower movement and a high FPS means very fast movement. But putting it in its own function that is called every 1/60th of a second still has problems.  I'm starting to realize that there is no way you can rely on a scheduled function to keep track of time. It is just way too unreliable.

But I still need to be able to move at the same speed regardless of the FPS that a computer can handle. So what is the best way to keep track of time and move around?


texts: How to properly repeat a texture on a quad in OpenGL?

texts:
I'm drawing a quad and binding a texture to this quad like this:

#define TERRAIN_WIDTH         2000
#define TERRAIN_LENGTH        2000
#define TERRAIN_WIDTH_2       (TERRAIN_WIDTH / 2)
#define TERRAIN_LENGTH_2      (TERRAIN_LENGTH / 2)

glBindTexture(GL_TEXTURE_2D, gameTextures.terrain);
glBegin(GL_QUADS);
    glTexCoord2f(0, 0); glVertex3f(-TERRAIN_WIDTH_2, 0.0f,  TERRAIN_LENGTH_2);
    glTexCoord2f(X, 0); glVertex3f( TERRAIN_WIDTH_2, 0.0f,  TERRAIN_LENGTH_2);
    glTexCoord2f(X, X); glVertex3f( TERRAIN_WIDTH_2, 0.0f, -TERRAIN_LENGTH_2);
    glTexCoord2f(0, X); glVertex3f(-TERRAIN_WIDTH_2, 0.0f, -TERRAIN_LENGTH_2);
glEnd();
glBindTexture(GL_TEXTURE_2D, 0);

Normally, X would be equal to 1 but this will stretch the texture because the quad is very large. The idea is to increase that value so the texture is repeated (the texture was generated with GL_REPEAT of course).

But how should I find the best value for X? I have a few 512x512 textures which look nice if I replace X=512. Then I have another 1024x1024 texture which looks good to with X=512 but doesn't start to look so good with a higher/lower value. Another texture is 2048x2048 and now I need to go down to X=256, otherwise it won't look so good.

What's confusing me even more is the fact that both 512x512 and 1024x1024 textures look good with X=512. The way I see it, the lower the texture resolution, the more times I need to repeat it.

How should I calculate the value of X then?


texts: How to make other semantics behave like SV_Position?

texts:
I'm having a lot of trouble with shadow mapping, and I believe I've found the problem.
When passing vectors from the vertex shader to the pixel shader, does the hardware automatically change any of the values based on the semantic?

I've compiled a barebones pair of shaders which should illustrate the problem.

Vertex shader :

struct Vertex {
    float3 position : POSITION;
};

struct Pixel {
    float4 position : SV_Position;
    float4 light_position : POSITION;
};

cbuffer Matrices {
    matrix projection;
};

Pixel RenderVertexShader(Vertex input) {
    Pixel output;
    output.position = mul(float4(input.position, 1.0f), projection);
    output.light_position = output.position;
    // We simply pass the same vector in screenspace through different semantics.
    return output;
}

And a simple pixel shader to go along with it:

struct Pixel {
    float4 position : SV_Position;
    float4 light_position : POSITION;
};

float4 RenderPixelShader(Pixel input) : SV_Target {
    // At this point, (input.position.z / input.position.w) is a normal depth value.
    // However, (input.light_position.z / input.light_position.w) is 0.999f or similar.
    // If the primitive is touching the near plane, it very quickly goes to 0.

    return (0.0f).rrrr;
}

How is it possible to make the hardware treat light_position in the same way which position is being treated between the vertex and pixel shaders?

This differrence is almost exclusive to the Z component, as the X and Y values of light_position are behaving as expected.

EDIT: Aha! (input.position.z) without dividing by W is the same as (input.light_position.z / input.light_position.w). Not sure why this is.

EDIT 2: Dividing (output.light_position) by (output.light_position.w) in the vertex shader causes really odd behavior, where (input.light_position.z / input.light_position.w) will be either 0 or 1 based on the camera's position and angle.

EDIT 3: Moving the projection multiplication into the pixel shader doesn't seem to make any difference. This means that the hardware is doing something to the SV_Position semantic which is critical to make it work.

EDIT 4: (input.light_position.z / input.light_position.w) IS behaving like depth, it's just that the precision seems to have decreased unbelievably. Only does it approach 0 once it's primitive literally intersects the near plane.


texts: More smaller maps among which player can travel

texts:
I am developing 2d game, where maps are tile based, small about 20x20 tiles and player can travel between a lot of maps (in my game rooms) like this. The maps are connected sometimes verticaly and sometimes horizontaly and together they make one big cave.

Should I create a class where one 2d array holds all the maps (another 2d arrays), or is there any other way? Whats the most efficient way to create them in this class? Thank you for your help.


texts: Proper use of Dynamic Vertex Buffers for rapid update

texts:
I am creating a C#/SharpDx/DirectX10 application to plot line charts in a fast way.

I have a prototype which uses Dynamic Vertex Buffers and fills a fixed-size buffer, say 1M vertices, with new data per frame.

I'm finding sometimes the vertex buffer is filled with new data while the GPU is still drawing the last batch (especially on slower GPUs). Here is my code to create, map, fill and flush a vertex buffer. I wonder if I'm using it in the right way?

// Declare the re-usable buffer (once)
SharpDX.Direct3D10.Buffer d3d10Buffer = new SharpDX.Direct3D10.Buffer(_d3d10Device,
        new BufferDescription(size,
        ResourceUsage.Dynamic,
        BindFlags.VertexBuffer,
        CpuAccessFlags.Write,
        ResourceOptionFlags.None));

// ...

// Per-frame, map the buffer, write vertices and draw + Flush()
DataStream vertexBufferStream = d3d10Buffer.Map(MapMode.WriteDiscard,
        SharpDX.Direct3D10.MapFlags.None);
vertexBufferStream.Write((float)someValue);
vertexBufferStream.Write((float)anotherValue);
// lots of writing ...

// Then immediately draw
d3d10Buffer.Unmap();
vertexBufferStream.Dispose();
_d3d10Device.InputAssembler.SetVertexBuffers(0,
       new VertexBufferBinding(_d3d10Buffer, 16, 0));

_d3d10Device.Draw(); // Assumes shaders and topology have been applied
_d3d10Device.Flush();

So I'm wondering, am I doing this the right way? The MSDN Documentation tells me not to call Flush, but I don't want to overwrite my (shared) dynamic vertex buffer when the next frame begins.

I also saw on the SharpDX website that MapFlags and MapMode have enumerations to prevent overwrite, would MapMode.WriteNoOverwrite and MapFlags.DoNotWait help in this scenario?


texts: Pygame - Increase and decrease the image size

texts:
I'm creating a 2D game where the player shoots cannon balls.. To give the impression of movement, i want the cannon ball to increase size untill half of the path, and then decrease untill it reach the target (just like rampart game cannon balls).

right now im doing this in every draw, but the call doesnt increases

self.CannonImg = pygame.transform.smoothscale(self.CannonImg, (10 + int(auxDistance / 10), 10 + int(auxDistance / 10)))

http://i.gyazo.com/d88a0ef419bd1014eaa180144fa876bf.png

This is how the images shows up.

But it doesnt scales smoothly, and the image is cut on the edges (with time, it starts to look a little bit transparent).

Is there any easy way to do it?

Also, i'm using images as the following. Though i've been reading, and found some people using sprites. What should I do?

self.CannonImg = pygame.image.load('Imagens/CannonBall.png')
self.surface.blit(self.CannonImg, self.Position)

Thanks!


texts: Collision detection with isometric tiles stored in rectangular files

texts:
So I'm working with a player moving across a grid of isometric tiles. Each tile is stored in a .png file. I have a class that crops out BufferedImages from different sprite sheets and initializes them for use in my game. When I crop out a tile image, the image is cropped out like this (minus the black border):

Because the four corners of this rectangle are transparent, I'm able to tessellate the tiles perfectly. I'm now trying to implement collision detection and having a tough time. The player moves by following the mouse around. In the player's tick/update method, I am checking to see if his new position will be in a tile marked as being solid. If the tile is solid, I don't update his position so that movement doesn't occur. My problem is that when I check to see if the player is moving into a solid tile, I'm checking the entire .png image, including the transparent corners.

So, if I'm moving towards these 'stone' tiles and I mark them as being solid, the player isn't colliding with the tiles in a natural way.

In the image you see here, I've updated these stone tiles with a black border showing the edge of the BufferedImage, and I've updated my player with a red rectangle indicating his bounding box. I've marked these tiles as solid. As I approach the tiles from the left moving right, I collide with these black lines rather than the colored portion of the tile. Actually, sometimes I collide with nothing to the left of the tile, like in this image (I'm sure that's just my math somewhere.)

I considered trying to attach a Polygon object to each solid tile that covers only the visible pixels of each .png file and doing collision against the polygon instead of the whole tile. I'm currently trying to implement this and having troubles.

My question here then is, how would you implement collision detection in this scenario? Would you draw polygons in the shape of the visible portion of each BufferedImage and do collision against these polygons like this? Is there a change that I can make or a technique I can use to implement smooth collision detection? Should I use a polygon object to crop my tiles in the first place? I'm looking for the simplest way to go about this.


texts: Start Position & Move Step Problem Swipe Motion Mobile Unity C#

texts:
i am currently trying left & right, up & down swipe motion in unity C#.

I have done the scripting, it all working,

but after i debug the script,

the object's position suddenly changed to a very weird number:

from (-3, 0, 3) changed to (-3.000004, 0.00000464, 2.99999).

And i intend to move just 1 unit every time i swipe, but the unit seems different,

it always move around 1 but not exact 1 (Ex: maybe like 0.9954, or like 1.002931).

How i set the initial position to be exact integer number,

and also move only 1 unit every time i swipe? Thanks

  using UnityEngine;

    public class Player : MonoBehaviour
    {
        private Vector3 startTouchPosition, endTouchPosition;
        private Vector3 startRocketPosition, endRocketPosition;
        private float flyTime;
        public float speed = 1f;
        bool canMove;

        void Start()
        {
            transform.position = new Vector3(-3, 0, 3);
        }

        void Update()
        {
            if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began)
            {
                startTouchPosition = Input.GetTouch(0).position;
            }
            if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Ended)
            {
                endTouchPosition = Input.GetTouch(0).position;

                float xDifference = Mathf.Abs(endTouchPosition.x - startTouchPosition.x);
                float yDifference = Mathf.Abs(endTouchPosition.y - startTouchPosition.y);

                if ((endTouchPosition.x < startTouchPosition.x) && xDifference >= yDifference && transform.position.x > -5.5f)
                {
                    //StartCoroutine(Fly("left"));
                    MoveLeft();
                }
                else if ((endTouchPosition.x > startTouchPosition.x) && xDifference >= yDifference && transform.position.x < -0.5f)
                {
                    //StartCoroutine(Fly("right"));
                    MoveRight();
                }
                else if ((endTouchPosition.y > startTouchPosition.y) && yDifference >= xDifference && transform.position.z < 5.5f)
                {
                    //StartCoroutine(Fly("up"));
                    MoveUp();
                }
                else if ((endTouchPosition.y < startTouchPosition.y) && yDifference >= xDifference && transform.position.z > 0.5f)
                {
                    //StartCoroutine(Fly("down"));
                    MoveDown();
                }
            }
            if (canMove)
            {
                transform.position = Vector3.Lerp(startRocketPosition, endRocketPosition, speed * Time.deltaTime);
                canMove = false;
            }
        }

        {
            startRocketPosition = transform.position;
            endRocketPosition = new Vector3(startRocketPosition.x - 10f, 0, transform.position.z);
            canMove = true;
        }
        void MoveRight()
        {
            startRocketPosition = transform.position;
            endRocketPosition = new Vector3(startRocketPosition.x + 10f, 0, transform.position.z);
            canMove = true;
        }
        void MoveUp()
        {
            startRocketPosition = transform.position;
            endRocketPosition = new Vector3(startRocketPosition.x, 0, transform.position.z + 10f);
            canMove = true;
        }
        void MoveDown()
        {
            startRocketPosition = transform.position;
            endRocketPosition = new Vector3(startRocketPosition.x, 0, transform.position.z -10f);
            anMove = true;
        }


texts: How is this usually done? Especially when the character might need to use different animations, for instance at his hands and legs. I noticed some skeletal animation solutions but they were only applicable to platformer games. Any ideas?


texts: Applied force is backward instead of forward when shooting an object

texts:
I have this FPS I'm making and I wanted to apply force to objects I shoot at however when I shoot on them, instead of going away from the camera they come towards it.

I don't get it. I could fix the problem by putting a -myTransform.forward but I want to understand the cause of the problem so I can fix it better.

Here's the logic behind the calculation:

void ApplyForce(Vector3 hitPosition, Transform hitTransform)
{
    if ((hitTransform.GetComponent<Rigidbody>() != null))
    {
        hitTransform.GetComponent<Rigidbody>().AddForce(myTransform.forward * forceToApply, ForceMode.Impulse);
    }
}


texts: Should I use animation or simple object rotation in this case

texts:
I'm making game where players control hover tanks using Unreal Engine 4.
Tank have a turret which rotates around for aiming. Turret pivot/center of mass is not exactly in joint with rest of tank so it rotates around point behind the turret.
You can see it here: https://www.youtube.com/watch?v=2k_d4u6Htzg

I asked my friend who made this mesh to create skeleton for it.
Now I'm not sure, which is the best way to implement correct rotation.

Should I make and use animation of tower rotating?
Keeping turret as child of rest of tank and simply rotating it was easier and more straightforward, so maybe I should just change pivot position?
Maybe, there is some easy way to rotate turrent around bone?

Which way is best in Your opinion and why?


texts: Offset direction stops working when I get too close

texts:
I have a script trying to get the gun aim at the target instead of the origin:

It's partially working.

but when I get too close with the mouse the player starts spinning

I would appreciate a help regarding why it happens and how to fix it.


texts: How to draw chunks of a map within view of camera

texts:
I want to draw chunks of a map in the screen when it's visible by the camera.
I can draw a single chunk using:
map(celx, cely, screenx, screeny, 16, 16)

This draws the chunk celx cely to the screen position screenx screeny.
I can move this map where it's drawn using:
camera(camx, camy)

This will offset the map by vector camx camy.
This is basic PICO-8 api.
For my problem, I define a world by chunks of the map:
pworld = {
   0, 1, 2, 0, 3, 4, 0, 1, 2,
   0, 3, 4, 0, 3, 4, 0, 3, 4,
   0, 1, 2, 0, 1, 2, 0, 1, 2,
   0, 1, 2, 0, 1, 2, 0, 1, 2
}

World is laid out by chunks of 8x4 units.
0 means chunk where celx=0 cely=0
1 means chunk where celx=1 cely=0 and so on.
Now when the camera is at say x=10,y=10 I have to draw the portion of the world indexes 1,2,9,10:
I tried to calculate this using:
function v_map(x, y)
   local i = pworld[flr(y/16)*8+flr(x/16)+1]

   local my = flr(i/8)
   local mx = i%8

   return {
      {x=mx,y=my},
      {x=mx+1,y=my},
      {x=mx,y=my+1},
      {x=mx+1,y=my+1}
   }
end

and draw using:
function _draw()

  camera(cam.x, cam.y)

  local vm = v_map(camx, camy)
  map(vm[1].x, vm[1].y, 0, 0, 16, 16)
  map(vm[2].x, vm[2].y, 0, 0, 16, 16)
  map(vm[3].x, vm[3].y, 0, 0, 16, 16)
  map(vm[4].x, vm[4].y, 0, 0, 16, 16)
end

But this is wrong and I don't understand how this even should work.
How do I know the indexes of the chunks to draw?
How do I know at what screen position to draw the chunks?
How does this work well with moving the camera?


texts: get the value of lerp at the mouse position?

texts:
I want to get the value t (value of lerp ()) between two lines
and the position of the mouse and draw a gray line that goes from line a to line b.
what is the value of lerp at the mouse position?


texts: ScriptableObject's custom objects begin reset to default?

texts:
I'm using ScriptableObjects as a way to serialize objects that I work with in an editor script. I save them as assets using AssetDatabase.CreateAsset and get them
resetted
It is saving correctly native c# class objects like strings, primitives and arrays of primitives.
The problem is that my ScriptableObject also contains objects of custom classes and structs of my code. These custom objects are being set to default() (ie. value types being set to 0 and reference types to null) every time the code is recompiled and when the editor is restarted (while the primitive variables still have the right saved value). Even with blittable structs the problem persists.
Is that expected?
Edit with some code to contextualize:
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct MeshHeader
{
    public int numBones;
    public int numVerts;
}

public class MyClass
{
    public string s1 { get; set; }
    public string s2 { get; set; }
}

public class MySO : ScriptableObject
{
    public int myInt; // OK
    public int[] myArr; // OK

    // These 2 variables will have their value reset after any recompilation of the code
    public MeshHeader meshHeader; // This will become 0;0
    public MyClass myClass; // This will become null

    public static void SaveMySO(MeshHeader h, MyClass c)
    {
        var mySO = ScriptableObject.CreateInstance<MySO>();
        mySO.myInt = 10;
        mySO.myArr = new int[2] { 9, 8 };
        mySO.meshHeader = h;
        mySO.myClass = c;

        AssetDatabase.CreateAsset(mySO, "Assets/foo.asset");
    }

    public static MySO LoadMySO()
    {
        return AssetDatabase.LoadAssetAtPath<MySO>("Assets/foo.asset");
    }
}

When I call MySO.SaveMySO it will save the ScriptableObject. However if I run MySO.LoadMySO after any code recompilation between these two calls, it will have both meshHeader and myClass values set to default, which will be 0 and null respectively while still holding the right values for myInt and myArr.


texts: BoundingBox created from mesh to origin, making it bigger

texts:
I'm working on a level-based survival game and I want to design my scenes in Maya and export them as a single model (with multiple meshes) into XNA.

My problem is that when I try to create Bounding Boxes(for Collision purposes) for each of the meshes, the are calculated from origin to the far-end of the current mesh, so to speak.

I'm thinking that it might have something to do with the position each mesh brings from Maya and that it's interpreted wrongly... or something.

Here's the code for when I create the boxes:

private static BoundingBox CreateBoundingBox(Model model, ModelMesh mesh)
    {

        Matrix[] boneTransforms = new Matrix[model.Bones.Count];
        model.CopyAbsoluteBoneTransformsTo(boneTransforms);

        BoundingBox result = new BoundingBox();

        foreach (ModelMeshPart meshPart in mesh.MeshParts)
        {
            BoundingBox? meshPartBoundingBox = GetBoundingBox(meshPart, boneTransforms[mesh.ParentBone.Index]);
            if (meshPartBoundingBox != null)
                result = BoundingBox.CreateMerged(result, meshPartBoundingBox.Value);
        }
        result = new BoundingBox(result.Min, result.Max);
        return result;
    }
    private static BoundingBox? GetBoundingBox(ModelMeshPart meshPart, Matrix transform)
    {
        if (meshPart.VertexBuffer == null)
            return null;

        Vector3[] positions = VertexElementExtractor.GetVertexElement(meshPart, VertexElementUsage.Position);
        if (positions == null)
            return null;

        Vector3[] transformedPositions = new Vector3[positions.Length];
        Vector3.Transform(positions, ref transform, transformedPositions);

        for (int i = 0; i < transformedPositions.Length; i++)
        {
            Console.WriteLine(" " + transformedPositions[i]);
        }
        return BoundingBox.CreateFromPoints(transformedPositions);
    }

public static class VertexElementExtractor
{
    public static Vector3[] GetVertexElement(ModelMeshPart meshPart, VertexElementUsage usage)
    {
        VertexDeclaration vd = meshPart.VertexBuffer.VertexDeclaration;
        VertexElement[] elements = vd.GetVertexElements();

        Func<VertexElement, bool> elementPredicate = ve => ve.VertexElementUsage == usage && ve.VertexElementFormat == VertexElementFormat.Vector3;
        if (!elements.Any(elementPredicate))
            return null;

        VertexElement element = elements.First(elementPredicate);

        Vector3[] vertexData = new Vector3[meshPart.NumVertices];
        meshPart.VertexBuffer.GetData((meshPart.VertexOffset * vd.VertexStride) + element.Offset,
            vertexData, 0, vertexData.Length, vd.VertexStride);

        return vertexData;
    }
}

Here's a link to the picture of the mesh(The model holds six meshes, but I'm only rendering one and it's bounding box to make it clearer:
http://www.gsodergren.se/portfolio/wp-content/uploads/2011/10/Screen-shot-2011-10-24-at-1.16.37-AM.png
The mesh that I'm refering to is the Cubelike one. The cylinder is a completely different model and not part of any bounding box calculation.

I've double- (and tripple-)-checked that this mesh corresponds to this bounding box.

Any thoughts on what I'm doing wrong?


texts: Transparency in opengl - texture with alpha, color from background

texts:
I have to draw texture with transparent areas on square. But I don't want this transparencies to take color from this polygon, but from the background. Do you have any good tutorial to achieve it?

--EDIT--

   glColor4f(1,0,0,1);

  glBegin(GL_QUADS);

  glTexCoord2f(0,0); glVertex3f(-0.5, -0.5, -1);
         glTexCoord2f(1,0); glVertex3f(1, -1, -1);
         glTexCoord2f(1,1); glVertex3f(0.5, 0.5, -1);
         glTexCoord2f(0,1); glVertex3f(-0.5, 0.5, -1);

  glEnd();

I just takes color from polygon. How to make this polygon transparent.


texts:
I recently started to work on a project which consists in developing a game similar to the Urbz on Gameboy Advance (the Handheld version of the game developed by Griptonite Games). This is mainly a project to learn how to make a video game from scratch, especially one in 2D (isometric in this case). I'm planning to use C++ with SFML for this project. I already have some skill in programming, but since I would also like to draw the art by myself and have no experience in that I was wondering how I could do that.
Especially, I was wondering how did the the team behind the Urbz draw their art and what kind of technique was being used? It doesn't seem to me a 'handcrafted' kind of pixel art :

I also made some research about developing a 2D isometric game engine. It seems that a popular technique is to draw the map from an isometric tileset (as shown here by eishiya for instance). However the team from Griptonite Games seems to have used several big maps, such as this :

Or am I getting things wrong ? What kind of engine/technique might have they been using ?
Many thanks for reading this post (and maybe for answering too) !


texts: How to select a vertex by mouse clicking in OpenGL?

texts:
I'm programming a simple graph game and so far I'm still doing a few tests in OpenGL. Right now, let's say I defined a GL_POINT with the glVertex2f(20.0f, 0.0f). I have this function to calculate the coordinates from the mouse input to world coordinates:

void converterCoords(GLfloat winX, GLfloat winY){

GLint viewport[4];
GLdouble modelview[16];
GLdouble projection[16];
GLfloat winZ = 0;

glGetDoublev( GL_MODELVIEW_MATRIX, modelview );
glGetDoublev( GL_PROJECTION_MATRIX, projection );
glGetIntegerv( GL_VIEWPORT, viewport );

winX = (float)winX;
winY = (float)viewport[3] - (float)winY;
winZ = 0;

gluUnProject( winX, winY, winZ, modelview, projection, viewport, &worldX,
        &worldY, &worldZ);

}

After this I have a function to check if the mouse click coordinates are the same as one of the GL_POINTS I defined:

int determinaPosicao(double x, double y){

int i;
for(i = 0; i < nPontos; i++){
    if(pontos[i].vX == x || pontos[i].vY == y){
        pontos[i].seleccionado = 1;
    }
}

glutSetWindow(window);
glutPostRedisplay();
return 0;

}

I can check just fine if the mouse click is the same as the if condition with the "||" function, however, if I have two points with the same x or y value, then it will declare the mouse has hit both points. However, if I use the "&&" function it never seems to go into the if condition and never declares any point as having been hit.

This certainly isn't the best way to achieve my goal and I would really like to ask for some opinions on how to do this.

Solution I found with help from user concept3d:

int determinaPosicao(double x, double y){

const double maxDist = (1e0);
int i;

printf("%f\n", x);

//Escala no rato após conversão: ~5510

x = (x*xMaxRef)/10000;
y = (y*yMaxRef)/10000;

for(i = 0; i < nPontos; i++){
    if(pow((pontos[i].vX - x), 2) <= maxDist  && pow((pontos[i].vY - y), 2) <= maxDist){
        pontos[i].seleccionado = 1;
    }
}

glutSetWindow(window);
glutPostRedisplay();
return 0;

}

The operations I used in x = (x*xMaxRef)/10000 is a simple rule to scale the mouse coordinates (that range from 0 to approx 5510) from the max ortho referencial scale which is x and y = {-100, 100}


texts: Mouse state not acting as I intend it to

texts:
I am creating an inventory system.  I have it working well, but for some reason when I pick up an item from a slot(lets say slot 2 of 20) and drop it into that same slot(slot 2) the mouse state fails to update correctly, resulting in the item being dropped and picked back up in the same cycle.  I feel like I am missing something here, but would appreciate any help.  Below is my code.

The method that controls the Item being Dropped into the inventory:

    public void ItemDropped(Vector2 pos, Item item)
    {
        for (int intlc = 0; intlc < InvBoxes.Count; intlc++)
        {
            if (InvBoxes[intlc].Intersects(new Rectangle((int)pos.X, (int)pos.Y, 1, 1)))
            {
                if (Items[intlc] != null)
                {
                    ClampedItem = Items[intlc];
                }
                else
                {
                    //Set bln in Game to stop drawing item at cursor
                    ClampedItem = null;
                    GlobalVariables.TheGame.blnClamp = false;
                }
                Items[intlc] = item;
                break;
            }
        }
    }

Logic in my Inventory Class' Update method to Update the mouse state, after setting the old mouse state.  Then it check for hovering over an item, and sets all old hovers to false.  It then looks for if I am clicking on the item hovered over, and therein lies the problem :

        oms = ms;
        ms = Mouse.GetState();

        //set hover
        for (int intlc = 0; intlc < Items.Count; intlc++)
        {
            if (Items[intlc] != null)
            {
                if ((ms.X - Items[intlc].location.X) < 50 && (ms.X - Items[intlc].location.X) > 0 && (ms.Y - Items[intlc].location.Y) < 30 && (ms.Y - Items[intlc].location.Y) > 0)
                {
                    Items[intlc].invhover = true;
                }
                else
                {
                    Items[intlc].invhover = false;
                }
            }
        }

            for (int intlc = 0; intlc < Items.Count; intlc++)
            {
                if (Items[intlc] != null)
                {
                    if (Items[intlc].invhover)
                    {

                        if (ms.LeftButton == ButtonState.Pressed && oms.LeftButton == ButtonState.Released)
                        {
                            ClampedItem = Items[intlc];
                            Items[intlc] = null;
                            GlobalVariables.TheGame.blnClamp = true;
                        }
                    }
                }
            }

In my game Class at the end of the the Update I have a few calls that pertain to this issue :

        Rectangle rect = new Rectangle(mouseState.X, mouseState.Y, 1, 1);

        if (blnClamp)
        {
            if (rect.Intersects(inventory.Bounds) && mouseState.LeftButton == ButtonState.Pressed && MoldState.LeftButton == ButtonState.Released)
            {
                inventory.ItemDropped(new Vector2(mouseState.X, mouseState.Y), inventory.ClampedItem);
            }
        }

        inventory.Update(InvPos);

If you look at the conditional in my game's inventory's Update method's check for mouse state's current and old button state being pressed and released, when I grab an item from slot 1 and drop it into slot 2, the mouse state conditional validate as intended.  But when trying to grab the item at slot 1 and drop it back into slot one, the item drops, and is immediately clamped again because old mouse state is up and new mouse state is down.  Both instances will hit the conditional that is inside the hover conditional.

Additional Note : When I put a breakpoint on the ItemDropped Method inside my inventory class, the debugger causes the mouse state to update as intended, and the item that I picked up out of slot 2 is placed into slot 2 without fail.  There is a flaw programatically to how I have my updates set up somehow.


texts: How can i convert a non-convex mesh collider object to a convex mesh collider object

texts:
I created a character object in Maya and stored it as char.obj, then I imported the object into Unity.

The character object is not colliding with any other Unity objects like cube, plane, sphere, etc.

Then I found non-convex mesh colliders do not collide with any other Unity default objects. How can I convert the non-convex mesh collider to a convex mesh collider?

Here is the error message I see:

  Non-convex MeshCollider with non-kinematic Rigidbody is no longer
  supported in Unity 5. If you want to use a non-convex mesh either make
  the Rigidbody kinematic or remove the Rigidbody component. Scene
  hierarchy path "mesh_octopus/Default", Mesh asset path
  "Assets/PlaceAsset/mesh_octopus/mesh_octopus.obj" Mesh name "Default"


texts: Are completely dumb client multiplayer games feasible?

texts: Is it possible to make a networked game, where each client displays a pixel array sent to it by the server, and sends inputs back to the server? This would be much simpler to implement than using client-side prediction, but I would imagine it would be too slow. Would it be possible?


texts: Problem resolving angles in Unity (trying to apply a field force between particles)

texts:
So im trying to build a visual physics simulator that I intend to use at work to help some of my students understand how various forces interact within multi particle systems. I also want them to see how computational physics is done, and so want to code some physics into unity as opposed to use the pre-installed physics systems.

So I have a bunch of Spheres on my 2D plane which are acting as my particles - they have charge and mass. Im calculating the Coulomb Force that each particle acts upon one another, which gives a Vector2, where x is the magnitude of the force, and y is the angle the force acts. This all works perfectly I think:

force = (coulombConstant * particleCalculating.getCharge() * particleApplying.getCharge()) / (distance.magnitude * distance.magnitude);
angle = Mathf.Atan(distance.x / distance.y);

(except for some powers which I will sort out later, this works fine)

Then, the idea is to sum all these forces together as such:

foreach (Vector2 particle in forces)
{
    netXForce += particle.x * Mathf.Sin(particle.y);
    netYForce += particle.x * Mathf.Cos(particle.y);
}

Then I apply this to get an acceleration, and generate a velocity and move the particle.

Which should all work... the problem is the unity angle system (or my use of the unity angle system, whichever you prefer :)). I cant get it to differentiate from 0.5 rad to the bottom left and 0.5 rad to the top right (for example). This means two particles repelling one another actually add to each others acceleration a they are trying to go in opposite directions.

Any help here would be great - even if its just a description of why the unity angle system is great :)


texts:
I have a whiteboard object that I would like to put images/pdfs/powerpoints on. I am not sure how to overlay an image on a white shader. I looked at this post:

Loading .PNG file and using it for UnityEngine.UI.Image

But I am not sure where to put the UI.Image. If I create a mesh from the image won't it cover up my entire whiteboard?


texts:
I've already asked this before, but I just wanna encode this again with a new leveling format. What I want to do is that, the user will gain exp and once they leveled up, their previous experience will be added to their current exp.

So, to put it in a Scenario it goes like this:
User1 is on a Level 1 with an exp_needed of 1000 to reach level 2. He gained an exp of 1000, so he is now on level 2 with a current_exp of 1000 and an exp needed of 1,400. Or if User1 gained an exp of 1,100 he is on level 2 with a current_exp of 1,100 and 1,400 exp needed. And so on, depending on the algorithm. But I get a result of -900/1,400 if the user gains 1,100 exp.

Here is the code below:

while($user->curr_exp >= $user->exp_needed){
       $user->curr_exp -= ($user->exp_needed) + $user->prev_exp;
       $user->prev_exp = $user->exp_needed;
       if($user->level <= 19){
       $user->exp_needed = $user->prev_exp * 1.4;
       }
       elseif($user->level >= 20 && $user->level <= 39){
       $user->exp_needed = $user->prev_exp * 1.1;
       }
       elseif($user->level >= 40 && $user->level <= 59){
       $user->exp_needed = $user->prev_exp * 1.05;
       }
       elseif($user->level >= 60 && $user->level <= 79){
       $user->exp_needed = $user->prev_exp * 1.04;
       }
       elseif($user->level >= 80 && $user->level <= 99){
       $user->exp_needed = $user->prev_exp * 1.03;
       }
       elseif($user->level == 100){
       $user->exp_needed = $user->exp_needed * 0;
       }
       $user->level += 1;
       $user->save();
      }

Any ideas how to deal with this? Thanks.


texts:
Character falls through the Platform Effector 2D in Unity. How can I fix it?
Here is the demonstration: https://imgur.com/G5YkTxa.
I tried changing the Edit - Project Settings... - Physics 2D - Default Contact Offset from the current 0.01 value to the 0.1 value. The result is the same and here is the demonstration of it: https://imgur.com/3TAOsNY.
Here are my settings for the platform:

Here are my settings for the character's RigidBody 2D:

Here is what character colliders look like when my character runs: https://imgur.com/CTialU3.
I basically run the recorded inside Unity animation of running and move my character with the help of the:
        private void FixedUpdate()
        {
            ... some code which computes the velocity vector depending on the input (the pressed buttons)
            characterRigidBody2D.velocity = velocityVector;
        }

I googled for a while now similar issues, but was not able to find a solution. I want to avoid the character falling down randomly during running.


texts: Trying to 'stamp' an arbitrary assortment of pixels to a texture2d that may be rotated at an arbitrary angle

texts:
This one is hard to explain but I'll try to not to overcomplicate it. Engine is Unity, for reference.
I have a system where an object has a 2d texture to display a custom splat map. The user can 'paint' to this texture, which uses world space coordinates of the mouse to see which pixel should be painted to. They can also paint larger shapes, which are essentially just implementations of square / circle drawing algorithms that choose what pixel coordinates to paint to based off the starting world space coordinates.
This works fine while the object/texture are unrotated, but if I rotate the object an arbitrary amount of degrees (say, 45 for the most extreme result), like squares and circle etc are drawn to the texture with missing pixels. I assume this is because the 'grid' of the texture is now rotated, and because I'm still trying to 'stamp' the shape in the original world space orientation (without respect to the rotation), the pixel 'sizes' or coordinates aren't the same?
I can't post screenshots as I'm at work, but this is what my desired output would be (Ignore the pixelisation, had to use an online crappy paint program), where the first square is the object in its original rotation, with a red square stamped on to it as expected. The second square is after the object is rotated 45 degrees, and the yellow square stamped on it is what I want (and what is currently appearing with missing pixels in my implementation).

EDIT: And here is the actual result I'm getting, pixels per unit is 16. The first square was stamped, the rect then rotated 135 degrees, and then the second square was stamped (shown with the missing pixels):

Anyone have any idea how I would go about drawing onto a rotated texture like this without ending up with missing pixels? I can post code snippets / build images later.
EDIT:
This is the code executed on the object to register a single pixel draw (very loosely), which uses the RotatePointAroundPivot function to get the pixel on the original pixel grid location in world space by rotating the point against the transforms current rotation. This works perfectly for individual pixel draws from mouse position clicks, but with the larger shapes I end up with the issue described
void DrawToTex(Vector2 worldPos) {
    worldPos = RotatePointAroundPivot(worldPos, transform.position, transform.rotation.eulerAngles)

    (xPixelCoordinate, yPixelCoordinate) = GetPixelCoordinatesFromWorldPos(worldPos);

    pixels[xPixelCoordinate, yPixelCoordinate] = color;
}

public Vector3 RotatePointAroundPivot(Vector3 point, Vector3 pivot, Vector3 angles) {
    return Quaternion.Euler(angles) * (point - pivot) + pivot;
}

public void DrawSquare(Vector2 worldPos, int size) {

    (int startXCoord, int startYCoord) = GetPixelCoordinatesFromWorldPos(worldPos);

    // Literally just gets an array of the correct size
    int[,] squareMatrix = GetSquareMatrix(size);

    sizeHalved = size / 2;

    pixelWorldSize = 1f / pixelsPerUnit; // pixels per unit is 16 in my build

    for(int x = 0; x < size; x++) {
        for(int y = 0; y < size; x++) {
            int newX = startXCoord - sizeHalved + x;
            int newY = startYCoord - sizeHalved + y;

            Vector2 pixelWorldPositionToDraw = worldPos + new Vector2((newX - startXCoord) * pixelWorldSize, (newY - startYCoord) * pixelWorldSize);
            DrawToTex(pixelWorldPositionToDraw);
        }
    }
}

(int, int) GetPixelCoordinatesFromWorldPos(Vector2 worldPos) {
    float xMin = bounds.min.x;
    float yMin = bounds.min.y;
    float distFromStartX = worldPos.x - xMin;
    float distFromStartY = worldPos.y - yMin;
    float xScaled = distFromStartX * pixelsPerUnit;
    float yScaled = distFromStartY * pixelsPerUnit;
    int xPixelCoordinate = (int) xScaled;
    int yPixelCoordinate = (int) yScaled;

    return (xPixelCoordinate, yPixelCoordinate);
}


texts: Where can I find documentation or an example of a C/C++ Plugin for FSX

texts:
I want to make a plugin for FSX in C/C++ but all the examples and documentation forward to the SimConnect Examples for FSX.

I want to access USB-hardware from the plugin and for this reason I'm looking for a way to write a plugin in C/C++ which does not rely on the SimConnect interface.


texts: OpenGL: How to render a "shadow" for an object that's behind another?

texts:
First off, an image from Fez that depicts the effect I'm after:

I'm trying to achieve a similar effect in my project. I'm quite certain this is done with a stencil buffer, but the resources on such effect are scarce. How should I approach this? I'm guessing I'm after a sort of "AND" stencil where I'd render a semi-transparent black rectangle over the player where only the pixels that had both the player and a map object.

I'm not sure if it has any effect on it (besides maybe inverting the stencil operations..?), but for other reasons, my pipeline first renders the world and the player is rendered last.


texts: Can't Get .enabled to Work for Children Sprites. What Gives?

texts:
So I have an object with a few children. I want to be able to disable/enable 2 of their SpriteRenderers via one of my scripts. I feel like I'm doing things right, but apparently I'm not. And yes, my game objects have the appropriate tags that are being searched for in my code. I'll paste the relevant bits of code below:

public bool isAiming = false;
Animator playerAnim;

GameObject arm;
GameObject weapon;

SpriteRenderer armRenderer;
SpriteRenderer weaponRenderer;

void Start()
 {
     playerAnim = gameObject.GetComponent<Animator>();

     arm = GameObject.FindGameObjectWithTag("Arm");
     weapon = GameObject.FindGameObjectWithTag("EquippedWeapon");

     armRenderer = arm.GetComponent<SpriteRenderer>();
     weaponRenderer = weapon.GetComponent<SpriteRenderer>();
 }

void Update()
 {
     CheckIfAiming();
 }

void CheckIfAiming()
 {
     if (Input.GetButton("Fire2")) // Holding right click
     {
         isAiming = true;

         armRenderer.enabled = true;
         weaponRenderer.enabled = true;

         playerAnim.SetBool("isAiming", isAiming);
     }
     else
     {
         isAiming = false;

         armRenderer.enabled = false;
         weaponRenderer.enabled = false;

         playerAnim.SetBool("isAiming", isAiming);
     }
 }

What gives? I want to just enable the sprite rendering when I hold down the right mouse click. SetActive(false/true) is not an option as I still want code to affect them while they're not visible.

Am I just trying to access the SpriteRenderers incorrectly?


texts:
i created tool that generate lua script on each level which contain lot function, and they named based on the object+id format. ex : trigger1(), etc; so every level may have same function name, what i need is call luaL_dofile on beginning level load.(+ registration ofcourse)

on game every level load i call do_file this lua script, so i can call it in the code. the thing is, when i try to change level to another level, i dont want close entire lua state and do rereigistration / initialization ,i just want close previous luaL_dofile and change it with new luaL_dofile on the next lua level script. since i want instaneous transition each level.

can anyone help me on this ?


texts:
I want to render one sprite on top of another one. I create both sprites using same coordinates and while debuging I can see that they have same position but still one is being rendered beneath another and slightly to the left. Could somebody tell me what am I doing wrong? here is my code where I create sprites:

Sprite sprite1 = new Sprite(new Texture("1.png"));
sprite1.setScale(1/PPM);
Sprite sprite2 = new Sprite(new TextureRegion(...));
sprite2.setScale(1/PPM);
sprite1.setPosition(x,y);
sprite2.setPosition(x,y);

Could it have something to do with scaling? Or maybe the fact that second sprite is created from TextureRegion?


texts: Collision detection between player and tiles

texts:
I am trying to implement basic (for now) collision detection into my platformer. I have tiles that are each 16 x 16 in size. The character is 32 x 32 pixels in size and has its own bounding box. Now, in my Tile class, I have a bool, isSolid. Each of these tiles in my array also have a rect for their respective bounding boxes.

I am checking to see if there's an intersection between the player and tiles by doing:

if (player.GetBoundingBox().Intersects(map.tiles[(int)player.position.Y / 16,
(int)player.position.X / 16].bounds) && map.tiles[(int)player.position.Y / 16,
(int)player.position.X / 16].isSolid)
{
...
}

Now, my problem is that this is extremely inaccurate as I'm rounding off the position. I'm tired as heck right now and for the life of me I can't figure out how to properly do this. What is the best way to approach this issue?


texts: XNA Deserialization Error: XML element "Type" not found

texts:
I want to deserialize an xml file that contains a path for an image
I have 3 projects:

One with the Program.cs class and the main template stuff from xna,

another with classes such as the default 'Game1" as well as others,

and a final project containing the resources.

The build order is: Classes -then-> resources + Program.cs last
Resources (the xml) depends on the classes, and program also depends on classes

Here is a screenshot of the solution explorer: http://imgur.com/a/lUFbB
(Game1 is renamed to Main.cs)

Here is the class which loads the image:

namespace WORLib
{
    class SplashScreen : GameScreen
    {
        Texture2D image;

        public string Path;

        public override void LoadContent()
        {
            base.LoadContent();
            image = content.Load<Texture2D>(Path);
        }
...

Here is the class that manages the screens:

namespace WORLib
{
    class ScreenManager
    {
        //fields
        public static ScreenManager instance;
        public Vector2 Dimensions { private set; get; }
        public ContentManager Content { private set; get; }
        XmlManager<GameScreen> xmlGameScreenManager;

        GameScreen currentScreen;

        public static ScreenManager Instance
        {
            get
            {
                if (instance == null)
                    instance = new ScreenManager();
                return instance;
            }
        }

        private ScreenManager()
        {
            Dimensions = new Vector2(640, 480);
            currentScreen = new SplashScreen();
            xmlGameScreenManager = new XmlManager<GameScreen>();
            xmlGameScreenManager.Type = currentScreen.Type;
            currentScreen = xmlGameScreenManager.Load("SplashScreen.xml");
        }
...

This is the xml code:

<?xml version="1.0" encoding="utf-8"?>
<XnaContent xmlns:ns="WORLib">
  <Asset Type="WORLib.SplashScreen">
    <SplashScreen>
      <Path>SplashScreen/image</Path>
    </SplashScreen>
  </Asset>
</XnaContent>

And this is the error I get upon building:

XML element "Type" not found

This error does not appear in any thread ive found anywhere, and most other threads did not get me very far. This thread:
C# XNA - Can't Deserialize Element   helped me the most, but I did not know how to get rid of the xnamanager class without breaking my content loading.


texts: What kinds of conflict-resolution can be fun beyond combat in an RPG?

texts:
As someone who grew up on the single-digit Final Fantasy games and AD&D, there are few ways of solving an rpg problem as fun as a fight. Different streams of accomplishment (object acquisition/crafting, skill trees, puzzles, player strategies, team combination/synergies, etc) all go into a few minutes of frenetic action, allowing for the feeling of accomplishment and progress via stat increases as the game progresses.

That said, we tend to characterize rpg players as murderhobos for good reason. When you incentivize killing things, it's not long before all problems start looking like something to hit with your sword. And when you're able to steal anything not nailed down, why not do it?

While other kinds of conflict-resolution can be fun when in their element (farm/ Civ/Sim games for the sense of building something, spy/ninja/assassin games for deftness and exploiting situations, social games for roleplaying a character or out-thinking the other guy), they're often not fun outside their very narrow venue. And because we're limited to conversation with a computer (at least in single-player games), social games can't even explore the whole of their venue.

I'm racking my brain trying to figure out how to properly gamify the societal ideals of don't-kill, don't-steal in such a way that attacking or stealing becomes a conscious choice, not just a default means of action...but at the same time keep the same diversity of fun-inputs that fighting/stealing games have. Most games just code in consequences: the town guards are sent after you and/or some faction is less willing to deal with you. But this feels unnatural, and only invites further gaming of the system, producing better murderhobos at the end.

My reason for doing so? The main theme of my game is a heavily philosophical one(think a halfway-understandable Xenosaga) on how morality might play out in the post-post apocalypse. While killing and stealing would be a part of that, I feel that our natural tendency as gamers wouldn't allow this question to play out 'fairly'.

Any idea on how to put killing and stealing on a truly equal playing field with other forms of conflict resolution?


texts: How to set object's / node's absolute rotation correctly?

texts:
Usually when I want to rotate an object/node in my Ogre scene I call the node's rotate() method. That rotates the node locally relative to it's current rotation. So for example, when I start with 0 rotation, then rotate twice for 5 degrees about one axis, then after the second call the object is rotated by 10 degrees in total.

Now I need to set the absolute rotation of the node/object directly, regardless of its current rotation. Thus, say I don't know the objects current rotation, I need to set it say to 45 degrees on the X axis. Something like setRotation().

I know there is a setOrientation() method in the SceneNode class, which expects a quaternion object. I also know that I can get the current orientation quaternion. What I don't know: how can I use/change this current orientation quaternion to set the new absolute rotation of the node?

PS: Crosspost at http://www.ogre3d.org/forums/viewtopic.php?f=2&t=77710


texts:
I want to make a small 2D game.
In the game you can go in all directions(with the bird's-eye view) and can shoot.
(A little bit like BoxHead http://de.y8.com/games/box_head_2play)
My problem there is the collision detection and especially the response, in which the detection of a collision is not really the problem(I use for that a quad tree).
The real problem is the response to the collision.
For simplifying it, all objects in the game are rectangles that cannot rotate, no shapes or circles.
The rectangles are represented by a vector for the left bottom corner and a vector for the right top corner.
The origin of the coordinate system is in the left bottom corner(I know in games its often on the left top corner but I prefer the bottom corner).
So now a object in the world is composite with a rectangle and a velocity vector.
The algorithm for now is, change the velocity(For example if the user press a key) from a object(In this case the player), add the velocity on the object and at last check for collision(I leave fro now the acceleration alone).

The real question now:
How I response to the collision now ?
What should I do, if the quad tree detect a collision ?
Is the basic algorithm right ?

Still a small question: How I can detect collision in a endless world with a quad tree(Quad trees was always limited to a specify size) ?

You see I have a lot of questions.
I don't know where to start and handle/detect the collision.
I hope you can help me to get started.

EDIT:
I don't need/want advanced collisions/physics.
I only want that a player cant go through walls and detect if a bullet hits something.


texts: Clean way to detect collision of object with box2d

texts:
I have been looking into box2d (in java with libgdx) lately and have been trying to create my own custom bounce effect (I increase the Restitution after the first bounce)

To do this as a test I simply checked the location of the object and waited for the first bounce.

But now I wanted to actually implement this and came across a problem: How to detect the collision of 2 specific object in box2d?

I found this tutorial:
box2d collision detection - but I am very reluctant to use that code. There must be a simpler and cleaner way to detect a collision between 2 objects (without having to set user data and checking all collisions with giant if() conditions...)

Can anyone help me out?  (assuming I am not just hopeful and there actually is a better way)

Help is greatly appreciated

Thanks, Jason


texts: How to fix issues with repeated coroutines for lerping values?

texts:
I have created a progress bar system that lerps the value over a duration to provide some life to the progress bars.
I've done this using a coroutine that gets called each time a value (such as life or exp) gets modified.
The problem with this is, if the coroutine gets called in rapid succession, i.e. before the previous instance of the coroutine is finished, the lerped values inside the progress bar get messed up. They get fixed at the next coroutine call, but it kind of bothers me, so if someone can provide some insight into this, or maybe a workaround or an alternative way of accomplishing this, I would very much appreciate it.
The code for the coroutine I'm using is this:
private IEnumerator FillLerp(int currExp, int expNeed)
{
    float lerpDuration = 2f;
    float lerpSpeed = 3f;
    float i = 0f;
    float amountToFill = (float)currExp / expNeed;

    while (i < lerpDuration)
    {
        yield return null;
        _experienceBarFill.fillAmount = Mathf.Lerp(_experienceBarFill.fillAmount, amountToFill, Time.deltaTime * lerpSpeed);
        i += Time.deltaTime;
    }
}


texts: Finding the normals of an oriented bounding box?

texts:
Here is my problem.

I'm working on the physics for my 2D game.

All objects are oriented bounding boxes (OBB) based on the separate axis theorem.

In order to do collision resolution, I need to be able to get an object out out of the object it is penetrating.

To do this I need to find the normal of the face(s) that the other OBB is touching.

Example:

The small red OBB is a car lets say, and the big OBB is a static building. I need to determine the unit vector that is the normal of the building edge(s) the car is penetrating to get the car out of there.

Here are my questions:

How do I determine which edges the car is penetrating.
I know how to determine the normal of an edge, but how do I know if I need  (-dy, dx) or (dy, -dx)?
In the case I'm demonstrating the car is penetrating 2 edges, which edge(s) do I use to get it out?

Answers or help with any or all of these is greatly appreciated.

Thank you


texts: How to display a lot of small objects using WebGL?

texts:
Introduction

The game scene contains a lot of 10x10 pixel elements: for 1980x1200 px. screen the number of elements on the scene can vary from 0 to 23760 (elements cannot intersect).

The live example: http://fintank.ru/game/

The entire game space comprised of tiles: each tile is responsible for some area and keeps elements for that area (similar to google maps).

Each tile exist as 2 entities: S and G. S is a set of elements in the tile, G is rendered image of a tile. When the server put/remove elements to the tile, we change S and then re-render the G.

To draw a frame (at 20 fps) I just put the G of each visible tile using the putImageData(). That is done without WebGL.

The question

What is the most CPU effective approach to implement such many-elements management using WebGL? Should I render each tile to a texture or each element may be implemented as a separate textured rectangle? The main concern is that each tile may be updated 30-60 times a second (elements adding/removal).

How to avoid memory leaks (how to reuse buffers?) if we make many new textures every second?

What is the most effective way to manipulate pixels during rendering a 100x100 tile?

How to avoid re-uploading the unchanged textures to graphic card?


texts:
I have a Orthographic camera. I have a fixed landscape texture and a texture for a moveable object.
If the object moves to the right the camera will also move with the object.

When I also draw an score text that should have fixed position on the screen, that score text position will be update too if the camera's position gets updated so that it looks like that it is fixed on the screen. But if I do that, I have some edge flickering at the text object. I'am using SpriteBatch!

Is there another approach to implement a fixed positioned object on the screen?


texts: Why am I unable to edit the Input Field object's script?

texts:
When attempting to edit an Input Field object's script like so

I get the following error:

  Unable to open C:/Program Files/Unity/Editor/Data/UnityExtensions/Unity/GUISystem/UnityEngine.UI.dll: Check external application preferences.

Why is Unity attempting to open a *.dll, here?


texts:
never realized how the animation intro of a game is done, I've thought that perhaps you have all the images of each frame of the animation, or have a video made and make the load.

anyway, if it is made of any of these ways,
What is the best way to do this?


texts:
I want to make a particle that interpolates in Alpha and velocity.

public class Particle extends GameObject implements Updateable
{

    int time;

    int lifetime;

    int Alpha;

    double dx;

    double dy;

    int[][] alphaEnvelope;

    double[][] speedEnvelope;

    @Override
    public void update()
    {
        time++;

    }

}

this is my particle class.

alphaEnvelope[x][y] changes the Alpha over time where X is the time and Y is the Alpha Value.

For example:

[1][100]

[60][70]

[70][0]

the Alpha is 100 at lifetime 1,
70 at lifetime 60
and 0 at lifetime 70.

How do I interpolate between these values fluently?


texts: Multiplayer Game - Node.js syncing other players' position

texts:
I'm creating a multiplayer platformer game with 4 players in multiple rooms. I've read a lot of articles and researched about client prediction and lag compensations. I think I can somehow manage to understand how to update "my client". But what would be the best approach in the multiplayer platformer game to update "other clients". This is what I'm thinking:

Approach 1: the client sends input "left" to the server -> server increases the velocity of the player -> the server sends the actual input "left" of this client to all other clients -> other clients run the physics on the input.

Apporach 2: the client sends the input to the server -> server adds velocity, update state -> game loop in server updates the position of every single client back to everyone, sends it to all clients -> client gets it and updates.

What would be a better approach? or please if there is a better approach, tell me I am very stuck..


texts: Render only a cross-section of a 3D scene in Godot

texts:
I'm working on a 3D game where I sometimes want to display only a cross-section of the scene.  Ideally I would like this to be just the intersections of the scene with a plane.  But the only way I've been able to achieve this so far is by setting the near and far culling planes to be very close together.  However, there are two problems with this approach:

The result isn't actually 2D, the cross-sections have the thickness the size of the gap between the culling planes (this isn't a huge deal, but would be nice to fix)
Most objects become quasi-outlines since their fronts and backs are now culled by the camera.  I at least want this to be filled in (e.g. for a sphere I want a solid circle instead of just an outline).

Is there a way to make a very small gap between the near and far culling planes but filling in the interior of the objects, or is there another way to achieve this plane-intersection effect?


texts:
I am thinking about giving a go to one of my ancient ideas for a game. The core point of this game would be the possible level of functional customization of the game environment and objects (such as modifying the behavior of a space ship weaponry). For this the game would need to be scriptable. Also I don't aim to commercialize it, it is merely an interesting programming challenge for me.

As I am mostly a .NET guy I will use XNA/C# for the game itself. For the scripting I think about going with Python or Lua. I have previous experience with Python and have nothing against it as a language. Lua on the other hand is almost completely new to me, besides some minor World of Warcraft addons modifications I did here and there, and it looks promising. So here is my question:

What are the pros and cons of Lua vs. Python as a scripting language for XNA/C# platform?

Is one of them considerably easier to use with XNA/C#? Has one of them some specific advantages or disadvantages when used with XNA/C#? Why would you recommend one over the other for XNA/C#?


texts: How to determine counter-clockwise vertex winding

texts:
I've been causing myself some confusion lately with regards to vertex winding in a mesh class that i'm writing.

Currently, the mesh contains the appropriate structures for:

vertices (vector3)
indices (vector3 - actually a custom struct of 3 ints)
normals (vector3)
colors (vector4)

Starting out simple, i'm trying to model a cuboid with 24 vertices and 12 indices. What is causing me confusion at the moment is how vertex winding is determined for each face. OpenGL-ES seems to be set to counter clockwise winding by default (which can be changed) but i'm really not sure how CCW is determined in 3 dimensions?

It was my understanding that the "front" and "back" of an object would be defined by the direction of the vector for each vertices normal, rather than the ordering of each vertex that defines a "face". It would seem however that this isn't true. Either that, or (more likely) my code isn't entirely correct.

If this isn't the case, how is CCW defined in 3 dimensions? How does this translate for the 6 faces of a cuboid? If I use the same logic for the back face of the cuboid as the front face, surely one of the faces would point inwards?

I'm really struggling to get my head around this when manually defining vertices for my mesh. The confusion really kicks in when I try to work out how vertex data is stored in a model/mesh file created by MAYA or Blender etc. Are all faces oriented outwards when an object is exported?

Or perhaps my original assumption was correct whereby the normals define what is to be determined as the front of each face, but then why does OpenGL have a flag for specifying the vertex winding order?

Also, considering the three vectors A, B and C; surely the same winding (regardless of orientation) could be achieved in three different ways, i.e: A->B->C or B->C->A or C->A->B?

Is there a simple way for determining such things or have I completely missed the mark somewhere?


texts: How would I detect if two 2D arrays of any shape collided?

texts:
Say there's two or more moveable objects of any shape in 2D plane, each object has its own 2D boolean array to act as a bounds box which can range from 10 to 100 pixels, the program then reads each pixel from a image that represents it, and appropriatly changes the array to true(pixel has a alpha more then 1) or false(pixel has a alpha less than one).

Each time one of these objects moves, what would be the best accurate way to test if they hit another object in Java using as few APIs/libraries as possible?


texts: Why does this no longer render the "test tri"?

texts:
So I got this code about rendering a shaded tri using sharpDX ...

var vertexShaderByteCode = ShaderBytecode.CompileFromFile("MiniTri.fx", "VS", "vs_4_0", ShaderFlags.None, EffectFlags.None);
var vertexShader = new VertexShader(device, vertexShaderByteCode);
var pixelShaderByteCode = ShaderBytecode.CompileFromFile("MiniTri.fx", "PS", "ps_4_0", ShaderFlags.None, EffectFlags.None);
var pixelShader = new PixelShader(device, pixelShaderByteCode);

var layout = new InputLayout(
    device,
    ShaderSignature.GetInputSignature(vertexShaderByteCode),
    new[]
        {
            new InputElement("POSITION", 0, Format.R32G32B32A32_Float, 0, 0),
            new InputElement("COLOR", 0, Format.R32G32B32A32_Float, 16, 0)
        });

var vertices = Buffer.Create(device, BindFlags.VertexBuffer, new[]
    {
        new Vector4(0.0f, 0.5f, 0.5f, 1.0f), new Vector4(1.0f, 0.0f, 0.0f, 1.0f),
        new Vector4(0.5f, -0.5f, 0.5f, 1.0f), new Vector4(0.0f, 1.0f, 0.0f, 1.0f),
        new Vector4(-0.5f, -0.5f, 0.5f, 1.0f), new Vector4(0.0f, 0.0f, 1.0f, 1.0f)
    });

As with all demos they are often not very modular and over wordy, but also I wanted to play with other ways of rendering in these simple scenarios before I move on to more complex things.

So I updated the code to this ...

var vertexShader = new VertexShader(device, ShaderBytecode.CompileFromFile("Shaders/Coloured.fx", "VS", "vs_4_0", ShaderFlags.None, EffectFlags.None));
var pixelShader = new PixelShader(device, ShaderBytecode.CompileFromFile("Shaders/Coloured.fx", "PS", "ps_4_0", ShaderFlags.None, EffectFlags.None));
VertexPositionColour[] data = new VertexPositionColour[]
{
    new VertexPositionColour { Position = new Vector4(0.0f, 0.5f, 0.5f, 1.0f), Colour = new Vector4(1.0f, 0.0f, 0.0f, 1.0f) },
    new VertexPositionColour { Position = new Vector4(0.5f, -0.5f, 0.5f, 1.0f), Colour = new Vector4(0.0f, 1.0f, 0.0f, 1.0f) },
    new VertexPositionColour { Position = new Vector4(-0.5f, -0.5f, 0.5f, 1.0f), Colour = new Vector4(0.0f, 0.0f, 1.0f, 1.0f) }
};

var vertices = Buffer.Create(device, BindFlags.VertexBuffer, data);

And now the test triangle no longer renders.
Could anyone tell me why?