texts: How to calculate ray polygon intersection?

texts:
I'm in a class where we are creating a ray tracer from the ground up in C++. I'm at a point where I can't seem to wrap my head around the math that is required to calculate the point at which a ray intersects a polygon.

We have some direction for how to do this, but all of the class materials as well as my Googling of the subject have not helped.

These are the functions we must complete:

bool polygon::Intersect(const ray &R, intersection &inter)
{
    // To Do: If you have implemented the "CalculateNormal" method
    // below, should already be calculated and placed in the member
    // "n".
    //
    // Now, using n, you need to calculate the intersection of the
    // ray with the plane containing the polygon.  Then, once you
    // have that point, you need to loop through each edge in the
    // polygon and make sure the point is to the left of that edge.
    //
    // If it is to the left of every edge, then fill the structure
    // inter with all of the data for the intersection and return
    // true, if not, return 0.
    //
    // Don't forget to check to see if the t you calculate for the
    // ray is > 0.

    return false;
}

void polygon::CalculateNormal(void)
{
    // To Do: Use the edges of the polygon to calculate the normal
    // of the polygon. You should be careful to take care of the
    // case where two edges give you a zero normal.  Place the
    // normal into the member "n" so that the intersection method
    // can use it when called.
    //
}

Could someone please explain this in a bit further detail?

Note: I am not asking for anyone to write the code or do my homework for me, but instead help me understand what exactly is going on here.

Thank you.


texts: How to adjust a path to avoid collisions with moving obstacles inside a nav mesh?

texts:
I'm writing a script for a bot and I'm a little bit stuck.
There's a game, there's a player (me) and I want to get from point A to point B.
I can find the path via bot's API (it returns a List<Vector3F> points).
There's also an NPC who wanders along a known route (also List<Vector3F>), back and forth. Actually there're several NPCs with their own predefined routes.
How can I adjust my path to not collide with these NPCs (which are themselves moving)?
I've read a bit about pathfinding, collision avoidance, velocity obstacles, WHCA*, HRVO, but I can't figure out what's the best in my situation.
The problem is that these algorithms can give me points which lie outside of nav mesh (I think so)...
Any ideas will be appreciated.


texts: Does XNA 4 support 3D affine transformations for 2D images?

texts:
Looooong story short I'm essentially trying to code Mode 7 in XNA. Before I continue bashing my brains out in research and various failed matrix math equations; I just want to make sure that XNA supports this just out-of-the-box (so to speak).

I'd prefer not to have to import other libraries, because I want to learn how it works myself that way I understand the whole thing better. However that's all for naught if it won't work at all. So no opengl, directx, etc if possible (will eventually do it just to optimize everything, but not for now).

tl;dr: Can I has Mode 7 in XNA?


texts: How can I create a rectangular SDL surface filled with a particular color?

texts:
I'm learning SDL. I'd like to create rectangular surface filled with a flat color (not an image). Below is my code -- it compiles fine, but doesn't work.

I'm passing the function these parameters:

SDL_Surface*  m_screen = SDL_SetVideoMode(
  SCREEN_WIDTH,
  SCREEN_HEIGHT,
  SCREEN_BPP,
  SDL_SWSURFACE
);
SDL_FillRect(
  m_screen,
  &m_screen->clip_rect,
  SDL_MapRGB(m_screen->format,0xFF, 0xFF, 0xFF)
);
...
Button button(m_screen,0,0,50,50,255,0,0)
...
...
Button::Button(SDL_Surface* screen,int x,int y,int w,int h,int R, int G, int B) {
      SDL_Rect box;
      SDL_Surface * ButtonSurface;
      ButtonSurface = NULL ;
      Uint32 rmask, gmask, bmask, amask;
      #if SDL_BYTEORDER == SDL_BIG_ENDIAN
         rmask = 0xff000000;
         gmask = 0x00ff0000;
         bmask = 0x0000ff00;
         amask = 0x000000ff;
      #else
         rmask = 0x000000ff;
         gmask = 0x0000ff00;
         bmask = 0x00ff0000;
         amask = 0xff000000;
      #endif

      box.x = x;
      box.y = y;
      box.w = w;
      box.h = h;

      ButtonSurface = SDL_CreateRGBSurface(SDL_SWSURFACE, box.w,box.h, 32,
                                    rmask, gmask, bmask, amask);

      if(ButtonSurface == NULL) {
         LOG_MSG("Button::Button Button failed");
      }

      SDL_FillRect(screen,&box,SDL_MapRGB ( ButtonSurface->format, R, G, B ));

      //ut.ApplySurface(0,0,ButtonSurface,screen);
      SDL_BlitSurface(ButtonSurface,NULL,screen,&box);
   }

What am I doing wrong here?


texts:
I am working on a road fighter kind of game. The game has its tracks moving to give the effect of  car movement. The car accelerates and decelerates as expected with certain keys pressed. But How do I give the notion of distance travelled by the car and how to calculate it?

For some reference, here's how the movement of tracks is sped to simulate acceleration and deceleration:

void Update ()
        {
        if (Input.GetKey(KeyCode.F))
        {
            if(speed<=35f)
            {
            speed = speed + 3f* Time.smoothDeltaTime;

            }

        }
        if (Input.GetKeyUp(KeyCode.F))
        {

                speed = speed - 7f * Time.smoothDeltaTime;

        }

        if(Input.GetKeyDown(KeyCode.S))
          {
            speed = speed - speed/2;
        }
        this.transform.Translate (Vector3.right * Time.smoothDeltaTime * speed);

        }


texts: How do fixed-point physics (engines) work?

texts:
I would think there should be an abundance of excellent articles answering this question, but my searches have come up completely empty.
I am developing an embedded graphics engine on a microcontroller which does not have an FPU or math co-processor.
I read somewhere before during my research that reasonably precise physics can be implemented without floating point math by using fixed point math.
How exactly does this work? What generally would be the programmatic behavior of a physics engine with some time step dt?


texts:
I need to generate a sprite sheet with squared sprite for a 2D game. How can I generate a sprite sheet where each frame has x = y? The only think I have to do is to "insert" some blank space between sprites (in case y were > x in the original sprite). Is there any program that I can use to trasform "irregular" sprite sheets to "squared" sprite sheets?

An example of non-squared sprite sheet: http://spriters-resource.com/gameboy_advance/khcom/sheet/1138


texts: Sprite not visible when using a Rectangle for collision in XNA

texts:
When I added a Rectangle to the Draw method for the sprite, it did not show up on screen.

 spriteBatch.Draw(texture, position, new Rectangle((int)position.X, (int)position.Y, (int)texture.Width, (int)texture.Height), Color.White, rotation, orgin, scale, SpriteEffects.None, 0f);


texts:
I'm trying to draw a bezier curve using 3 points. If I use the quadratic form:

I get this result:

And I believe it's correct.

Now since I need to draw it with a variable number of points, I'm trying to apply the explicit definition:

This is the code that implements it:

typedef struct Point2D
{
    GLfloat x;
    GLfloat y;
    Point2D operator+(GLfloat c) const
    {
        return {x+c, y+c};
    }
    Point2D operator+ (const Point2D& other) const
    {
        return {x+other.x, y+other.y};
    }
    void operator+= (GLfloat c)
    {
        y+=c;
        x+=c;
    }
    void operator+= (const Point2D& other)
    {
        x+= other.x;
        y+= other.y;
    }
    Point2D operator* (GLfloat factor) const
    {
        return {x*factor, y*factor};
    }
    void operator*= (GLfloat factor)
    {
        x*=factor;
        y*= factor;
    }
}Point2D;

Point2D bezier(const vector<Point2D>& points, GLfloat u) // u is t
{
    Point2D point;
    unsigned int n= points.size();
    vector<int> factorials(n);
    // For efficiency, I put all factorials in an array instead
    // of recalculating them each time.
    GLfloat c1= pow(1.0-u,n-2);
    // This is (1-t)^(n-1)
    GLfloat c2= 1.0;
    // This is t^i , I'll progressively multiply it for u.
    factorials[0]=1;
    for(unsigned int i=1; i<n;i++)
    {
        factorials[i]= factorials[i-1]*i;
    }
    point= points[0] * (GLfloat)(n-1) * c1; // This is the first point
    for(unsigned int i=1; i<n; i++)
    {
        c2*= u;
        GLfloat bCoeff= factorials[n-1]/(factorials[i]*factorials[n-2]);
            // bCoeff is the binomial coefficient: n! / ( i! * (n-1)! )
        point+= points[i] * bCoeff * c1 * c2;
    }
    return point;
}

void display()
{
    glClearColor(0.75,0.75,0.75,1.0);
    glClear(GL_COLOR_BUFFER_BIT);

    glColor3f(1.0,0.0,0.0);
    glBegin(GL_POINTS);
    vector<Point2D> points{Point2D{200,200}, Point2D{400,400}, Point2D{600,200} };
    for(GLfloat u=0.0; u<=1.0; u+=1.0e-4)
    {
        Point2D point;
        point= bezier(points,u);
        glVertex2f(point.x,point.y); // For now I use the immediate mode
                                         // I'll put it in a vbo.
    }
    glEnd();

    glutSwapBuffers();
}

Unfortunately this is the result that I get:

Which I believe is incorrect. I guess I'm not applying correctly the explicit definition, but I don't know where's the mistake, I would like to know what I'm doing wrong.


texts: Unity Animation Curve to change value over time

texts:
I am trying to learn how to use AnimationCurve to change a float value over time.

However i am not really sure how to do it

Say i have the following class:

    public class SpiritAway : MonoBehaviour
{
    public List<SkinnedMeshRenderer> MeshList;
    public List<Material> DissolveList;
    public float percentage = 0.0f;
    public bool IsDissolveing;
    public AnimationCurve Curve;

    private void Start()
    {
        percentage = 0.0f;
        for (int i = 0; i < MeshList.Count; i++)
        {
            for (int j = 0; j < MeshList[i].materials.Length; j++)
            {
                if (MeshList[i].materials[j].shader.name == "Dissolve")
                {
                    DissolveList.Add(MeshList[i].materials[j]);
                }
            }
        }
    }

    // Update is called once per frame
    void Update()
    {
        if (IsDissolveing)
        {
            if (percentage < 1)
            {
                    percentage += 0.01f;
                    for (int i = 0; i < DissolveList.Count; i++)
                    {
                        DissolveList[i].SetFloat("_alphaClipDissolve", percentage);
                    }
            }
        }
    }

Now i wish to incrase the percentage value with the percentage of the animation curve to get a more smooth and controlled transition of the value.

Could anyone explain how this is possible?


texts: Representing a high-resolution deformable solid in 3D

texts:
I am currently working on a design that will incorporate an object that can change size and shape.

For an example, I'll use a brick of clay. It starts out with normal dimensions of 1"x3"x6", but that can be changed because it is a soft material that can be molded.

I'm looking for a way to represent the size and shape of that object, no matter what changes have been made to it. For example, if you push your thumb down into the clay causing a hole, how could I keep track of that (from a programmatic point of view).

I thought about going all the way down to a semi-molecular level, where each "molecule" (I'm not talking actual molecules, but units that are small enough that they can always be considered the same size regardless of the shape of the object -- the resolution if you will) is represented, but the amount of data that could generate for a decent-sized object seems to be staggering. Even if the units were always the same size, the location of every unit would constantly need updating, along with algorithms to determine where each unit would go in the case of a force. The problem seems to get out of hand at this point, which is why I'm looking for any suggestions.


texts:
Are there any platform or language agnostic (preferably step by step) tutorials regarding creating hexagonal grid based maps/games? I'm mainly interested in grid/tiles basics and not advanced game engine stuff. So far I have found these:

Hexagonal grid for games and other projects
Hexagonal grid math


texts:
I'm following a tutorial from XNA GPA, but in my project, none of the sprites are loading. I've followed all of the instructions exactly, and the code works as expected when I copy it from my project into the example project that he provides.

Here's my Game.cs

using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;

namespace Tutorial
{

    public class Game : Microsoft.Xna.Framework.Game
    {
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;
        Paddle paddle;
        Rectangle screenRectangle;

        public Game()
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";

            screenRectangle = new Rectangle(0, 0, graphics.PreferredBackBufferWidth,
                                            graphics.PreferredBackBufferHeight);
        }

        protected override void Initialize()
        {
            // TODO: Add your initialization logic here

            base.Initialize();
        }

        protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(GraphicsDevice);

            Texture2D tempTexture = Content.Load<Texture2D>("paddle");
            paddle = new Paddle(tempTexture, screenRectangle);
            // TODO: use this.Content to load your game content here
        }

        protected override void UnloadContent()
        {
            // TODO: Unload any non ContentManager content here
        }

        protected override void Update(GameTime gameTime)
        {
            // Allows the game to exit
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
                this.Exit();

            // TODO: Add your update logic here

            paddle.Update();

            base.Update(gameTime);
        }

        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.CornflowerBlue);

            // TODO: Add your drawing code here

            spriteBatch.Begin();
            paddle.Draw(spriteBatch);
            spriteBatch.End();

            base.Draw(gameTime);
        }
    }
}

Any help would be greatly appreciated, thank you.


texts: How can I load a large tile map with cocos2d?

texts:
I am try to design a cocos2d game with a big world. The world's tile map is very big, maybe 20 iPad screen sizes worth of tiles.

I want to know how to load this using a CCTMXTiledMap? If I directly add it to screen, will it use too much memory? If so, is there a solution to solve this problem?


texts: Why does this game loop stop my process from responding?

texts:
I implemented a fixed time step loop for my C# game. All it does at the moment is make a square bounce around the screen. The problem I'm having is that when I execute the program, I can't close it from the window's close button and the cursor is stuck on the "busy" icon. I have to go into Visual Studio and stop the program manually.

Here's the loop at the moment:

public void run()
    {
        int updates = 0;
        int frames = 0;
        double msPerTick = 1000.0 / 60.0;
        double threshhold = 0;
        long lastTime = getCurrentTime();
        long lastTimer = getCurrentTime();

        while (true)
        {
            long currTime = getCurrentTime();
            threshhold += (currTime - lastTime) / msPerTick;
            lastTime = currTime;

            while (threshhold >= 1)
            {
                update();
                updates++;
                threshhold -= 1;
            }

            this.Refresh();
            frames++;

            if ((getCurrentTime() - lastTimer) >= 1000)
            {
                this.Text = updates + " updates and " + frames + " frames per second";
                updates = 0;
                frames = 0;
                lastTimer += 1000;
            }
        }
    }

Why is this happening?


texts:
I am using OpenGL 3.3 and am tryin to implement shadow mapping using cube maps.
I have a framebuffer with a depth attachment and a cube map texture.

My question is how to design the shaders for the first pass, when creating the shadowmap.

This is my vertex shader:

in vec3 position;

uniform mat4 lightWVP;

void main()
{
    gl_Position = lightWVP * vec4(position, 1.0);
}

Now, do I even need a fragment shader in this shader pass? from what I understand after reading http://www.opengl.org/wiki/Fragment_Shader, by default gl_FragCoord.z is written to the currently attached depth component (to which my cubemap texture is bound to).

Thus I shouldnt even need a fragment shader for this pass and from what I understand, there is no other work to do in the fragment shader other than writing this value.

Is this correct?


texts: Unity Animator/Collider Default Property Issues

texts:
How do you use Unity's Animator when dealing with animation curve values that have a default value and the default value causes jumps in animation transitions?

I have a bit of a complex problem with updating the collider from animator properties. Here's an example:

I have a player character animator controller that has stand/crouch/prone states. Th capsule collider's height/radius/center can be controlled from animation curves. So for example I have these three properties in my mecanim animator controller with default values:

ColliderHeightMult = 1.0
ColliderRadiusMult = 1.0
ColliderCenterOffset = 0.0

If for example the player goes crouched, the ColliderHeightMult and ColliderRadiusMult are taken from the crouch animation's curve so that the collider scales down in size.

This is all good so far but the trouble starts with the prone posture because for that the direction of the collider needs to be changed to be horizontal (collider.Direction = 2).

Now if the player was prone and the collider was horizontal and he goes back to crouched or standing, the collider direction is changed back to vertical (collider.Direction = 1). This however causes the collider to extend into the ground for a moment which causes the player to jump up for a moment or messes up my ground/airborne check.

The solution I found for this is to check if the target height/radius/center was reached and only then change the collider direction. This changes the collider direction only at the point when it's high enough in the air to not extend into the ground.

But here's the issue: At every animation state change the ColliderHeightMult is back to 1.0 and my height mult check succeeds already at that point causing the direction to be changed instantly, ruining my solution.

Does anyone have an idea how to tackle this whole problem (maybe in a different way)? Note that checking IsInTransition() won't help and actually I would prefer to have it smoothly adapt the collider size even during state transition.


texts: How to create a vertex array from any shape in JBox2D?

texts:
I have a code, that add a vertex array to a shape, my code is:

PolygonDef shape = new PolygonDef();
for (int i=0; i<vertices.size(); i++) {
    Vec2 v = vertices.get(i);
    shape.addVertex(new Vec2(v.x/RATIO,v.y/RATIO));
}

But its very strange because not working good on any of my polygon creator tool.

So with a triangle, it work good:

    ArrayList<Vec2> vertices = new ArrayList<Vec2>();

    vertices.add(new Vec2(0,-size.height/2));
    vertices.add(new Vec2(size.width/2,size.height/2));
    vertices.add(new Vec2(-size.width/2,size.height/2));

but with a bigger polygon of 50 to 60 vertices it's not working.

How I can create a usable vertex array from a shape? I have a greyscaled image with black and white colors... How can use this shape (image) to define my vertex array good?

And in box2D with the addVertex how I can add this points to make a normal usable polygon? (counter clockwise?)


texts: Check if the vector is behind another or maybe opposite directions?

texts:
I'm doing a network game and on the client side, i interpolate the client position with the server sent extrapolated position. The client has its own physics simulation wich is corrected by the server in steps. The problem is when it laggs and i 'kick' the ball, the server gets a delayed message and sends me the position backwards of the client position wich makes the ball goes back and forth. I want to ignore those and maybe compensate that on the server, not sure though. The problem is the clock difference on those case are 0.07ms or 0.10 ms wich isn't that high to ignore the message i guess.

When i get the server position, i extrapolate with the clock interval * serverBallVelocity

Can i check if my new ball server position is behind my actual ball vector position? I tried to use the dot product after normalized the two vectors to check if they are opposite but it ain't working properly.

Any suggestions on checking that?


texts: Weird GLM perspective problems with my 2D Game

texts:
I am trying to create the graphics system of a 2D game using OpenGL 3.3.
To help me in this task I am using the GLM math libraries.
However I am having some trouble. When my objects (for now they are just squares) have  a different scale, they "slide" through each other. I am posting some examples below.
In this picture both objects are at the center and camera is centered at the center
In this other picture the code has only moved the camera, but for some reason the big square moved down faster than the smaller one

Here are the matrices I am using to transform my camera
  // Projection matrix : 120° Field of View, display range : 0.1 unit <-> 10000000 units
  glm::mat4 Projection = glm::perspective(3.141516f/1.5f, (float)_WindowWidth / (float)_WindowHeight, 0.1f, 10000.0f);

  //glm::mat4 Projection = glm::ortho(0.0f, 16.0f, 12.0f, 0.0f,  0.1f, 100000000.0f);
  // Camera matrix
  glm::mat4 View       = glm::lookAt(
    glm::vec3(CameraPos.x, CameraPos.y ,2.0f), // Camera Position
    glm::vec3(CameraPos.x, CameraPos.y ,1.0f), // Where the camera looks
    glm::vec3(0,1,0)  // This is another way to say camera is not rotated
  );

And here are my matrices for my model transform
  glm::mat4 ViewProj = View * Projection;

  // Object to world matrix
  glm::mat4 Model      = glm::translate(glm::mat4(), glm::vec3(ElementToDraw.Position.x, ElementToDraw.Position.y, 1.0f)) *
      glm::rotate(glm::mat4(), ElementToDraw.Rotation, glm::vec3(0.0f, 0.0f, 1.0f)) *
      glm::scale(glm::mat4(), glm::vec3(ElementToDraw.Scale.x, ElementToDraw.Scale.y, 1.0f));

  glm::mat4 MVP = Model * ViewProj;

I really don't know why this happens. Am I using some matrix wrong?
Another thing, this only happens on the axis of the different scale. If both objects have the same scale they don't "slide"
Thank you in advance :)
EDIT:
I tried using glm::ortho with the following parameters:
 glm::mat4 Projection = glm::ortho(0.0f, 4.0f, 3.0f, 0.0f,  0.1f, 1000.0f);

EDIT 2:
I am passing the MVP using shaders
But the sliding continued and the objects werent centered at the center of the window


texts: Unity3D : Unload a loaded and inactive scene

texts:
I am using the following coroutine to attempt to unload asynchronously a loaded but inactive scene in Unity :

private IEnumerator sceneUnloader(string s)
{

    AsyncOperation asyncUnload = SceneManager.UnloadSceneAsync(s);

     while (!asyncUnload.isDone)
     {
        Debug.Log("[SCENE UNLOAD] " + asyncUnload.progress);
        yield return null;
     }
    }

The scene name input is valid, as it's the same variable used to preload the same earlier, and the scene is being preloaded correctly.
There is an active scene when this coroutine is being called, as the attempt is to unload a partially preloaded scene while another one is still active.

The AsyncOperation is apparently null, is there a way to get around this issue and unload from memory an inactive scene?

I'm currently hacking around this issue by waiting for the scene to be fully loaded and activated, and then unloading it.


texts: Basic C# Script in Unity3D for firing a bullet (not working)

texts:
working on a 2D top-down view game. Im trying to get my player to fire a bullet when spacebar is pressed. I added a component to my player (a bullet sprite) and placed it under his gun (so you can't see it). I added a debug message "Shoot" to make sure that whenever I hit spacebar it gets registered - however, the bullet never shoots. I get the message

UnassignedReferenceException: The variable bulletPrefab of ShootBullet has not been assigned

Here is my script:

public class ShootBullet : MonoBehaviour {
    public Rigidbody bulletPrefab;
    float attackSpeed = 2f;
    float cooldown;

    void Update () {
        if(Time.time >= cooldown) {
            if(Input.GetKeyDown (KeyCode.Space)) {
                Fire();
                Debug.Log ("Shoot");
            }
        }
    }

    // Fire a bullet
    void Fire() {
        Rigidbody bPrefab = Instantiate(bulletPrefab, transform.position, Quaternion.identity) as Rigidbody;
        bPrefab.AddForce (Vector3.up * 100f);
        cooldown = Time.time + attackSpeed;
    }
}

Any ideas?


texts:
I currently am trying to figure out how rotate an object so it's aligned with a triangle along the Z Axis. I have the world matrix of the object and a triangle, which has it's 3 points and the normal. My goal is to try and get the y axis of the object to face the same as the triangle's face normal.

Currently, what I have works on normals that are facing the positive y, however if it's facing downward (<0) the the object will rotate the until it's is facing the opposite direction as the triangle's normal.

Here's what I'm doing:

compWorld.GetYAxis( axis );
result = axis.Cross( triColWith->vNormal );
compWorld.Rotate( D3DXToDegree( result.x ), 0, D3DXToDegree( result.z ) );

I would like to thank you in advance for any help you could provide me. If anything needs more explanation, feel free to ask.


texts: Adding Shader Model 3.0 support to my Direct3D9 app

texts:
So far, we've only used pixel shaders because we never needed to do any custom processing at the vertex shader level. However, the 3.0 model shader forces you to define a vertex shader. And that's where I get lost.

That's because our pixel shaders have this signature:

sampler2D Texture0;

struct PixelShaderInput{
        float2 TexCoord : TEXCOORD0;
        float4 Color : COLOR;
};
struct PixelShaderOutput {
    float4 color : COLOR0;
};
PixelShaderOutput PixelShaderFirstPass( PixelShaderInput input ) {
        //Magic happens here
        //We use the tex2D function to sample Texture0
}

From what I've read about vertex shaders, the vertex shader output is the pixel shader input. So I added this:

struct VertexShaderInput{
    float4 Position : POSITION;
}

PixelShaderInput MyVertexShader( VertexShaderInput input  ){
     //At a loss here...
}

I don't know how to map the vertex shader input to the pixel shader input. All examples I found on the web just have the vertex shader return a float4, which is what their pixel shader expects.


texts: Custom Update Function -OR- Multiple TimeScales

texts:
I'm trying to create some interesting variations on timescales in my game.  In essence, I'd like at least two, probably three or four separate timescales.

The player - the player timescale is likely to be the game/scene timescale always.
Mobs - mob timescales can be altered (slower primarily, but also faster possibly) depending on cast spells or other effects in the
game.
Environment - like mobs, the environment may be slowed or sped up depending on some game effects that occur.  This would control things
like traps, torches, etc.

I'm thinking about things such as a Slow Time spell that might slow most mobs, but maybe not others (bool flag), something like a time elemental or something of that nature.  I'd also like to possibly slow environmental time so the player may have a single-use item that would allow them to move easily navigate traps (but not have guaranteed success if they still don't see the pattern or such).

Having controller scripts that are added to all objects that listen for calls to change a multiplier on Time.deltaTime could be an option, but it's clunky, would have to be in all of the scripts, would have to be accounted for in many areas (movement, combat, possibly related effects), and is just not an ideal option.

Inversely, the same effect (a lich for example casting slow on a player) could require opposing things.  If I had global settings that contained a multiplier for player/mob/object that were impacted by an effect, I could still always use a multiplier with Time.deltaTime, but I still think it would be clunky.

Has anyone done this?  Are there any good ideas?  I've searched a bit, but didn't find anything terribly useful.

I've considered custom Update() classes, though I'm not entirely sure how to implement them.  Maybe extend the FixedUpdate() class that's built in to take other things into account?  I know that Time.timeScale is inherently for the current scene, but could I make instances of Time that are used by different scripts FixedUpdate()?  Am I overthinking this?  I feel like this shouldn't be quite so difficult.


texts: Issue with interpolation on a burn shader (lerp and smoothstep)

texts:
I'm trying to create a simple burn shader. See here for more info on the method I'm using. However, I don't get why replacing the smoothstep with a lerp results in completely different results. Am I missing something from my knowledge of maths? As far as I know they should return similar values given the same parameters.

// clips materials, using an image as guidance.
// use clouds or random noise as the slice guide for best results.
Shader "Custom/Dissolving" {
Properties {
  _MainTex ("Texture (RGB)", 2D) = "white" {}
  _BorderTex ("Border Texture (RGBA)", 2D) = "white" {}

  _EdgeColor ("Edge Color", Color) = (1,0,0)
  _EdgeSize ("Edge Size", float) = 0.1

  _SliceGuide ("Slice Guide (RGB)", 2D) = "white" {}
  _SliceAmount ("Slice Amount", Range(0.0, 1)) = 0.2

  [MaterialToggle] UseClipInstruction ("Use Clip Instruction", Float) = 0
}
SubShader {
  Tags {"Queue"="Transparent" "IgnoreProjector"="True" "RenderType"="Transparent"}
  //Cull Off
  Blend SrcAlpha OneMinusSrcAlpha

  CGPROGRAM
  //if you're not planning on using shadows, remove "addshadow" for better performance
  #pragma surface surf Lambert alpha addshadow

  struct Input {
      float2 uv_MainTex : TEXCOORD0;
      float2 uv_SliceGuide : TEXCOORD1;
      float _SliceAmount;
  };

  sampler2D _MainTex;
  sampler2D _BorderTex;
  sampler2D _SliceGuide;
  half _SliceAmount;
  half _EdgeSize;
  half3 _EdgeColor;

  void surf (Input IN, inout SurfaceOutput o) {
    o.Alpha=1;

    //Green is a good color for estimating grayscale values
    half fragSliceValue = tex2D(_SliceGuide, IN.uv_SliceGuide).g;

    #ifdef UseClipInstruction
    clip(fragSliceValue - _SliceAmount);
    #else
    //TODO: look for an alternative to this
    if (fragSliceValue - _SliceAmount<0)
        o.Alpha=0;
    #endif

    half rampX = smoothstep(_SliceAmount,_SliceAmount + _EdgeSize, fragSliceValue);
    half3 ramp = tex2D(_BorderTex,half2( rampX,0) ) * _EdgeColor.rgb;
    o.Emission = ramp * (1-rampX);

    o.Albedo = tex2D(_MainTex,IN.uv_MainTex);
  }
  ENDCG
}
Fallback "Diffuse"
}

Left is the result of smoothstep (the provided code), right is what happens when I replace smooth with lerp.


texts: Creating an object in javascript with unity (unityscript)

texts:
So I have a ton of experience with JavaScript (its what I do for a living) but I am new to unity. I have built a game engine in javascript but now want to move it over to unity. I have been trying to implement my player class but am running into this error.

I have a getter function for my level_up stats. and inside of my level_up function I call that getter function and store it now I know this would work in normal javascript but its not in unity and I have having a heck of a time googling any information on objects in unityscript. Here is the relevant code:

function level_getter(){
    return {base_level_exp : float , lvl_exp_modifier : float , current_level : int};
}

function level_up(){
    var level_object = new Object();
    level_object = level_getter();

    level_object.current_level += 1;
    level_object.base_level_exp = level_object.base_level_exp * level_object.lvl_exp_modifier;

    level_setter(level_object.base_level_exp, level_object.lvl_exp_modifier, level_object.current_level);

}

I guess my first question is, is it even valid to return an object like that in unityscript?(in the level_getter() function). If its not valid what do people suggest I do instead. Set a getter function for each var? My second is how do I declare level_object so that it can accept the return if it is valid, and so that I can access the members of the object.

I have been looking around at tutorials and google for several hours now and have found nothing to clear up my confusion over objects in unityscript. So any help would be appreciated.


texts: Rendering a selected part of the terrain with different shading

texts:
I'm trying to understand how to modify the shading of the section of the terrain based on some user selection. In a game like Civ5, when a user selects a city or unit, that area is lit up more than the other parts of the terrain. I'm trying to implement this effect.

In the civ 5 example the selected tile is has a circle outline and the selected city has a transparent overlay that follows the height of the terrain nicely.

My current pipeline so far is at a primitive state. I render a quad and texture it with a grass texture. Then I draw a rectangular grid on top of this (a set of lines, with a slightly higher height value than the background grid). Upon selection (ie a mouse click inside the grid area), I calculate the approriate grid index by converting mouse to world coordinates and then to grid coordinates, and highlight the appropriate grid rectangle by changing the color of that particular rectangle. But, my approach gets outdated the moment I get a height map (as it assumes constant height), and looks pretty bad, hence this question.

EDIT : Added my pipeline description


texts: AI not pathing correctly with pathfinding

texts:
I have implemented A* pathfinding to use in a game that im making for a project. The issue is that the AI that's using the pathfinding does not seem to wanna follow the path correctly. as displayed in the picture

blue dots = AI's path

yellow dots = path to take according to the pathfinding

red dots = impassable wall

As you can see the AI completly ignores the path to follow according to the pathfinding. I have been twisting my head multiple times around and have been unable to figure out the issue.

Below is the code where the pathfinding is used by the AI and shows all the states it cant be in. Position and rotation is applied later down in the code which is not shown here.

if (_pathState == SEARCHING)
        {
            if (glm::length(enemy->getPosition() - player->getPosition()) < 10.0f)
            {
                _isAtGoal = true;
                _pathState = ATTACKING;
            }

            _pathFinding->findPath(enemy->getPosition(), player->getPosition(), map);
            _isAtGoal = false;
            if (_pathFinding->foundGoal)
            {
                _targetPos = player->getPosition();
                _pathState = FOUND_GOAL;
            }
        }
        if (_pathState == FOUND_GOAL)
        {
            if (!_isAtGoal)
            {
                glm::vec3 targetDistance = _pathFinding->nextPathPos(enemy->getPosition(), getRadius()) - enemy->getPosition();
                angle = glm::degrees(atan2(targetDistance.x, targetDistance.z));
                rotation = glm::angleAxis(glm::radians(angle), glm::vec3(0, 1, 0));
                _velocityX += 0.1f * cosf(angle);
                _velocityZ -= 0.1f * sinf(angle);

                /*if (glm::length(_targetPos - enemy->getPosition()) < 10.0f)
                {
                    _pathFinding->intializedStartGoal = false;
                    _pathFinding->foundGoal = false;
                    _pathFinding->clearPathToGoal();
                    _pathState = SEARCHING;
                }

                if (glm::length(_targetPos - player->getPosition()) > 10.0f)
                {
                    _pathFinding->intializedStartGoal = false;
                    _pathFinding->foundGoal = false;
                    _pathFinding->clearPathToGoal();
                    _pathState = SEARCHING;
                }*/

                if (glm::length(enemy->getPosition() - player->getPosition()) < 1.0f)
                {
                    _isAtGoal = true;
                    _pathState = ATTACKING;
                }
            }
        }
        if (_pathState == ATTACKING)
        {
            if (glm::length(enemy->getPosition() - player->getPosition()) > 10.0f)
            {
                _pathFinding->intializedStartGoal = false;
                _pathFinding->foundGoal = false;
                _pathFinding->clearPathToGoal();
                _pathState = SEARCHING;
            }
            else
            {
                glm::vec3 playerDir = enemy->getPosition() - player->getPosition();
                angle = glm::degrees(atan2(playerDir.x, playerDir.z));
                rotation = glm::angleAxis(glm::radians(angle), glm::vec3(0, 1, 0));
            }
        }

The tutorial that I followed when implementing the pathfinding is from here:

https://www.youtube.com/watch?annotation_id=annotation_654919&feature=iv&src_vid=-A2HYXj186c&v=NJOf_MYGrYs

And my pathfinding is pretty much as follows. My own suspicion is that the radius is whats causing the problem, since the radius is just a set number that I didn't put any thought into when I set it.


texts: I want to convert the camera coordinate to screen coordinate. I have asked this question because my camera is 48m wide and 32m high but my screen is 480x320 pixels. So whatever collision point I get those are based on camera. Also I like to mention that my camera set at center of the screen. So I get (0,0) coordinate at middle of the screen. At collision time I put some particle effect but now that particle effect not at correct place in the screen. So someone from community please help.


texts: What is a systematic process for choosing a mobile game engine?

texts:
I am looking for a systematic process or methodology for choosing a mobile game engine for a mobile game project.

Intuition tells me that it should be similar in principle to choosing any off-the-shelf product (requirements, evaluation, short-list, trial, etc).

Any suggested processes?


texts: Mapping rectangular texture on trapezoid-like shape

texts:
I have a problem with rendering rectangular textures on non-rectangular surfaces. While googling, I found a thread with person having a pretty similar problem: http://www.gamedev.net/topic/419296-skewedsheared-texture-mapping-in-opengl/

But in my case, I cannot be sure about surface's exact properties. It's not regular trapezoid, it can be slightly bent. Which means, that I cannot just calculate correct texture matrix, or at least I don't know how.

I've tried to render triangle fan-like shape, but it just changed the characteristics of final distortion.


texts: Using ShapeShop you draw a silhouette and it converts the silhouette to a "blob", which gives a nice game character. Using 3DSMAX 2012 you draw a line and close the spine. How do you convert it to a "blob" there? Extrude gives sharp edges, BlobMesh only converts the lines to a blob, I want it to be the organic "blob" structure it is in ShapeShop.


texts: Building a shape out of an Texture with Farseer

texts: I have already looked at the Documentation on there Website, but the code provieded to create a shape out of an Texture is outdated for the newest version. The body is very simple so maybe i can do it with just 2 rectange but i have no idea how to do, because I just started with Farseer. Here my texture:  Texture


texts: Rotate a bitmap and bitmap is getting blur in android

texts:
I am developing an android game. and in this I want to move an object along a Bezier path.

my object is rotating with some angle on this curve.

I used this piece of code:

public void update() {

        // check collision with bottom wall if heading down
        if (droid.getSpeed().getyDirection() == Speed.DIRECTION_DOWN
                && droid.getY() + droid.getBitmap().getHeight() / 2 >= getHeight()/2 &&
                droid.getY() + droid.getBitmap().getHeight() / 2 <= getHeight()/2+ 100 ) {

            int pointX[], pointY[];
            pointX = new int[4];
            pointY = new int[4];
            int  X , Y;

                pointX[0] = getWidth()/2;
                pointX[1] = getWidth()/2 + 50;
                pointX[2] = getWidth()/2 + 25;
                pointX[3] = getWidth()/2;
                pointY[0] = getHeight()/2;
                pointY[1] = getHeight()/2 + 25;
                pointY[2] = getHeight()/2 + 50;
                pointY[3] = getHeight()/2 + 100;

                Log.i(TAG, "In the While Zone of Last Half Zone");
                X = (int) ((pointX[3] * u * u * u) + (3 * pointX[2] * u * u * (1-u)) + (3 * pointX[1] * u * (1-u) * (1-u)) +
                    (pointX[0] * (1-u) * (1-u) * (1-u)));

                Y = (int) ((pointY[3] * u * u * u) + (3 * pointY[2] * u * u * (1-u)) + (3 * pointY[1] * u * (1-u) * (1-u)) +
                        (pointY[0] * (1-u) * (1-u) * (1-u)));

                Log.i(TAG+" Value of X: ", Double.toString(X));
                Log.i(TAG+" Value of Y: ", Double.toString(Y));

                double deltaX = X - droid.getX();
                double deltaY = Y - droid.getY();

                Log.i("deltaX :", Double.toString(deltaX));
                Log.i("deltaY :", Double.toString(deltaY));

                double angle = Math.atan2(deltaY, deltaX)  ;
                Log.i(TAG+" Angle: ", Double.toString(angle));
                Matrix mtx = new Matrix();
                mtx.preRotate((float) angle);
                mtx.postScale(1, 1);

                Bitmap rotatedBMP = Bitmap.createBitmap(droid.getBitmap(), droid.getX(), droid.getY(),  X - droid.getX(), Y - droid.getY(), mtx, true);
                droid.setBitmap(rotatedBMP);
                droid.curveUpdate(X, Y);
                u = u + 0.001;
                Log.i(TAG+" Value of U: ", Double.toString(u));

        }
        // check collision with top wall if heading up

        // Update the lone droid
        else{
            droid.update();
        }

    }

my object is moving and rotating as i supposed but image is getting blur. am not getting why is so.

Please suggest what can be the problem.

Thanks.


texts: Rendering after interpolating, renders inside/outside other objects

texts:
So, we're working out our interpolated render-coordinates during our render call and it's doing a fantastic job of smoothing everything out.  All is great and collision detection is working to a perfectly acceptable level (for simple CD - ie, player hits other object, looses a life, starts over...).

However, how do we deal with situations that require 'collision and resolution'?  The classic example, of course, being our player character colliding with a solid object (usually a platform or the ground) and then being 'resolved' to bring the 2 entities out of collision.... here is what I mean:

Even if we say something simple like 'just don't interpolate vertically when touching a platform' - that wouldn't seem a very clean solution because we need to think about slopes where the player is moving both left/right as well as up/down.

What is the easiest and cleanest way to protect ourselves from this happening?


texts: Confuddled with learning C++ / UE4 . Why can't I access this AActors properties?

texts:
Hello all I decided to punish myself further by now adding C++ to my list of things i know a little bit about.

Some of it looks familiar having dealt with C# quite a bit, but i am getting caught out on many occasions.

Here  I am trying to open a door when the Actor enters a trigger in the level.

void UOpenDoor::Open_Door()
{
// Find the owning actor:
AActor* Owner = GetOwner();

// Create a rotator:
FString oldAngle = "old angle = " + Owner->GetActorRotation().Roll.ToString();
UE_LOG(LogTemp, Warning, TEXT(oldAngle));
FRotator NewRotation = FRotator(0.0f, Owner->GetActorRotation().Roll + OpenAngle, 0.0f);

// Set the door rotation:
Owner->SetActorRotation(NewRotation);
}

This is likely a very obvious and silly error to anyone with any experience writing in C++. But heres my questions:

Why is the Owner underlined in red? And can anyone help me out with what exactly the pictured error means? (I tried making the FString and FString* pointer , I also tried << instead of + in the string definition. And I also tried without the literal "old angle" string part. ---no dice!)

I've also tried this, now I seem to have accessed the Roll property, but how do I display it in a log output for example?

    // Find the owning actor:
AActor* Owner = GetOwner();

// Create a rotator:
int test = (int)Owner->GetActorRotation().Roll;
UE_LOG(LogTemp, Warning, TEXT("TEST = " << test.ToString()));
FRotator NewRotation = FRotator(0.0f, Owner->GetActorRotation().Roll + OpenAngle, 0.0f);

This code gave me error red-line under UE_LOG saying "expression must have class type"


texts: Precision problems with realistically scaled planets/terrains

texts:
Recently I've been working on a realistically scaled planet engine. I found several interesting links about how to do it, what problems will come up after, and how to solve them. The approach I took was the one I found on many articles: Use 6 quadtrees, one for each faces, then transform the cube into a sphere.

My quadtree logic seems to be working, I tried it on a flat terrain and on a sphere ( with reasonable distances ), and it worked great, then I tried with bigger distances.

The first problem was z-fighting, fixed using a logarithmic depth buffer ( http://outerra.blogspot.fr/2009/08/logarithmic-z-buffer.html ). The second was floating point precision on big numbers.

I read two main approaches to fix it. The first one is to use doubles instead of floats for operations, and give the gpu every positions relative to camera space. The second was to use different spaces in different units ( object space in meters, planets space in kilometers, solar system space in AU, etc... ). While the second was encouraged by many people, I took the first one because it seemed easier to do. I plan to try the second in the future anyway.

The first approach worked on flat terrains because it was easy to compute the position relative to the camera ( centerOfNode - cameraPos ). One bug I still have with it is about height. I use 3D simplex noise on the gpu, which works in float and needs a vec3 input. With relatively small distances, the worldspace position works great. With huge distances, the worldspace position doesn't work when far from the origin, the pattern is very odd because of missing precision. And of course, it won't work with cameraspace position as input. I haven't find anything about that. Something I will try tomorrow is the second approach above. That is, define several spaces with different units, transform the position in each of the spaces, and use each of them as input for the simplex noise function, which will give me several textures I will be able to use for scale. I don't know how I will do in details, but I think it won't work since transform from the lower to the high space might result in floating points errors right? I could dynamically create vertices in the CPU using simplex noise with double precision but it doesn't sound right... I'd like to use the GPU as much as possible, unless I have no other choices.

Second problem I have is with spherical terrains this time. So my steps to get the planet are:

1) From the quadtree nodes, scale, rotate and translate an unit quad to his position in the current plane of the 6 quadtrees

2) normalize it to get the normal

3) multiply the radius to get a sphere at sea level

4) add the height

Since the first step is related to the origin of the planet, even in view space it will require operations with huge numbers ( the radius ), so I am not sure how I can avoid precision problems here... Again, I could create them on the CPU and send them to the GPU, but this sounds exhausting and I don't want to do it unless I have no other reasonable choices. I would gladly use the second solution ( several spaces ) if I had an idea of how to fix it with it, but I'm not sure how to do it...


texts:
I have a simple png square 8px x 8px. In Unity I've left the pixels per unit at 100 and added the image to the scene to create a prefab of the item.
I then add four items to the screen like so:
    var block = Resources.Load("Prefabs/Block", typeof(GameObject));

    Instantiate(block, new Vector3(1f, 0f), Quaternion.identity);
    Instantiate(block, new Vector3(0f, 1f), Quaternion.identity);
    Instantiate(block, new Vector3(2f, 0f), Quaternion.identity);
    Instantiate(block, new Vector3(0f, 2f), Quaternion.identity);

The results (as shown in the image below) seem to stretch the image dependant on where the prefab is placed. Is this normal behaviour? Is there a way round this or something I'm missing?


texts: Updating transform position after root motion

texts:
I have an animation of a character climbing with root motion in it (i.e. the character moves generally upwards for a couple of units during the animation). It is intended as a one shot, not a loop. The skeleton is fairly standard hips > spine 1, hips > right leg, hips > left leg etc. The root is the hips and the pivot is between the soles of the feet.

I know its generally best to make in-place animations without root motion but scripting the upward movement using Vector3.Lerp etc looks unrealistic (in reality when rock climbing for example the upward motion will come in perdiodic bursts as the knees are first bent, then extended, rather than a constant movement upwards), so I want to keep the root motion in the animation.

Problem is when the animation has finished Unity still considers the transform pivot to be in its original location, before the skeleton climbed up two units. Is there any way to instruct Unity that the new transform position is where the characters feet have ended up after the animation has finished?

I figure I could parent the hips to an empty which moves the charaters around normally, detatch the empty before the root motion climb, move it by the same amount the hips moved then re-attach but is there a less hacky way? Some kind of transform.returnToOriginalOffset method perhaps?


texts: How to use 3D transformation matrices with GLM old version that has simd functions

texts:
I need matrix 3D transformation, model transformation i.e scale-rotate-translate and then that model into world space so model-projection-view matrices.

I need it with GLM specified simd vectors and matrices according to their old version.
But I can only find transformation functions without simd vectors or matrix in examples like this

#include <glm/vec3.hpp> // glm::vec3
#include <glm/vec4.hpp> // glm::vec4
#include <glm/mat4x4.hpp> // glm::mat4
#include <glm/gtc/matrix_transform.hpp> // glm::translate, glm::rotate, glm::scale, glm::perspective
glm::mat4 camera(float Translate, glm::vec2 const & Rotate)
{
glm::mat4 Projection = glm::perspective(glm::radians(45.0f), 4.0f / 3.0f, 0.1f, 100.f);
glm::mat4 View = glm::translate(glm::mat4(1.0f), glm::vec3(0.0f, 0.0f, -Translate));
View = glm::rotate(View, Rotate.y, glm::vec3(-1.0f, 0.0f, 0.0f));
View = glm::rotate(View, Rotate.x, glm::vec3(0.0f, 1.0f, 0.0f));
glm::mat4 Model = glm::scale(glm::mat4(1.0f), glm::vec3(0.5f));
return Projection * View * Model;
}

I need it something like this

 glm::detail::fmat4x4SIMD MatrixMultiply()
    {
        glm::detail::fmat4x4SIMD m(1.0f);
        glm::detail::fmat4x4SIMD m1(1.0f);
        m1 = m1 * m;
        return m1;
    }

But If I try to give glm::lookAt, glm::rotate with fvec4SIMD/fvec4x4SIMD it gives me error that these built in functions does not support simd.

Any idea how to do this?


texts: Not able to assign any scripts to my game object

texts:
I am not able to assign a particular C# script to a game object. When I try to do so, I get this error as shown below Only the script I have is different.

In brief, just like the error above I am getting it as Can't Add Script Component 'AIWaypointNetwork' because the script class cannot be found. Make sure that there are no compile errors and that the file name and the class name match
And when I try to create a script component, I get the warning Associated Script cannot be loaded. Please fix compile errors and assign a valid script. Here is a screenshot of the situation.
As far as I know, I don't see anything wrong with the script and it's pretty simple too.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class AIWaypointNetwork : MonoBehaviour
{
    public List<Transform> Waypoints = new List<Transform>();
}

The unity version that I am using right now is Version 2020.1.11f1 Personal. And I have not faced these types of errors before. Based on my search, I see that I would probably have to reimport assets over again. How do we do that in this version of unity?
Is there something else I am missing here?


texts:
I'm working my way through a lot of game development resources, coming from a completely different field of software development, I'm interested in learning what patterns are frequently used in game development, and which aren't.

During my research, I wanted to know if/how event queues are handled in games, and came across Game Programming Patterns' post about Event Queues. (as an aside, what an awesome resource that book is!)

In it, Bob Nystrom gives an example of a "play audio" queue, where one part of the system can produce/enqueue the playing of an audio fragment, and the audio handler/consumer can act on that request whenever it can.

I like this pattern a lot, but the end-result still feels like it results in domains being crossed, because the sender (in this example the part of the system that deals with a unit dying) has to ask the audio system to play the "deathSoundID" sound using playSound(deathSoundID) (which, in this case, then enqueues that request for the audio engine to pick up as soon as it can).

What I expected to be proposed is that the sender in this case tells the audio engine that an event occurred (by having the audio engine listen for events from this specific game system), at which point the audio engine can then determine if/how it wants to act on that specific event.

Now, admittedly, there's still crossing of domains here, as in my example, the audio engine now has to have some kind of (huge) case statement that couples any game event to an audio-related action, but you no longer have to litter unrelated functions with calls to playSound, and it also forces you to be a good citizen, and allow other systems to act on whatever action you just took, be it the audio engine in this case, or the "gamepad rumbler" engine that wants to rumble your gamepad because you've just slain a large enemy.

Another downside to this is that you need many more queues for all your systems (if you want to avoid some kind of global event queue, which I think you should), which might not be practical/performant enough to do, so perhaps that's the reason why it wasn't chosen here.

Either way, as a newcomer to game development, I'm interested to hear why one would be preferable over the other, and in what situations that would be the case.


texts: Can a straight line be called a polygon?

texts: According to the definition of Polygon, If a Poly-line's first and last points are connected  then it is called Polygon. See the image below. I have P1, .... P5 Polyline. If I draw a line from P5 to P1 then it will be called polygon or not? I am confused here.


texts: 2D Platformer Multiple Body Collision Response

texts:
I've been stuck for the past few days on implementing multiple body collision response, and I can't seem to find any good resource to help me advance.
Colliding between two objects is simple enough. What I have so far is this:
    public static void ResolveCollision(ref Vector3 aVelocity, float aMass,
                                        ref Vector3 bVelocity, float bMass)
    {
        var totalMass = aMass + bMass;
        var temp = (aMass / totalMass * aVelocity) + (bMass / totalMass * bVelocity);
        bVelocity = (bMass / totalMass * bVelocity) + (aMass / totalMass * aVelocity);
        aVelocity = temp;
    }

This works fine in resolving collisions individually between objects. The issue that I need to resolve is when two or more bodies are involved in the calculation. For example, pushing an object against a wall or pushing two objects next to each other in the same direction. The component missing in my code is summing up the masses of the objects involved so that the final displacement is believable.
I am hesitant to implement a solution that once resolving the collision between A and B, that B will go and test its movement and resolve collisions between B and C, and return a response back to A to adjust itself to account for any findings, because that could become messy and recursive.
I have also considered an "island" approach, where connecting bodies form an "island" that has a total mass which would  be used when resolving collisions. However, this does not solve for the case of pushing an object against a wall, as I would omit walls and floors from being part of islands as their infinite mass would affect calculations of pushing objects vertially or horizontally respectively, if they are contributing their mass to the island.
Are either of my suggestions close to the mark, or what kind of pattern could I use to efficiently resolve collisions between multiple bodies?


texts: Developing a platform - why are age verifications even a thing?

texts:
I'm building an online gaming platform and have bumped into the question of age verification. Checkboxes such as "I verify that I am 13 years old or older" or a slider where you put in your age are common online when registering for accounts.

Why? I've been checking that box since I was a kid, it doesn't stop anyone. If you put it in your Terms of Service, is that enough?

Does any of this actually matter?


texts:
I run a free-to-play online game that involves collecting creatures and simply clicking on a button to give them a small amount of EXP. The idea is to do this for other people and they're likely to return the favour and help you make your own progress.

The initial tutorial guides you through the basic idea until you've successfully obtained a full Party of 6 before leaving you to your own devices, to make your own objectives and stuff.

I've noticed that players who make it through the tutorial tend to stay quite engaged with the game, but I also found these numbers:

25% of users join but never complete the first step of the tutorial, that is they never hatch their very first Egg.
A further 25% of users drop out of the game before finishing the tutorial, so having hatched only 1-5 Eggs.
Barely 50% of registered users actually complete the tutorial.

The problem is that I've never run this kind of game before. This is my first real project, but it's been going for several years now. I don't have any kind of baseline on what numbers to expect.

I can only imagine reasons right now, such as it being quite jarring to people that, in order to make progress, they have to help others make their progress and hope they return the favour.

So we have about half our users leaving before the tutorial is complete. Is this kind of thing normal? Am I worrying too much about this?


texts: Which works best to describe character, item or dungeon properties: Affix or Trait?

texts:
I am working on an RPG portion of my game called "The Underground King".

My item generator uses the same properties that also apply to characters, vehicles and racing levels (dungeons for short).

I am torn between using the term "Affix" and the term "Trait" to describe the procedurally generated properties, mainly because English is not my first language, and there may be a clear difference in usage between the two.

Examples of traits:
Hearty: For items, it gives 5 more HP, for characters they have 5 more HP, for vehicles they have 5 more durability, for dungeons, enemies have 5 HP each.
Indomitable: For items, characters and vehicles, it gives the player the ability to ressurect at 100% hp, once dead. For the dungeon, dead enemies remain invulnerable for a few seconds after being dead.

I am open to either opinions or arguments for any of them. Thanks!


texts: moving first person camera with the mouse on right click

texts:
I am new to game development and I am trying to get the game input working. I have successfully got all the movement keys for walking/running/looking around working; however, I am having a terrible time with the mouse lol.

Basically, I am trying to move the camera with the mouse when the user holds the right mouse button down and drags. I want to rotate the camera in that direction. So dragging to the right rotates right, dragging right/down will rotate right/down, etc.. I do not want the cursor to stay in the middle of the screen (this is not a FPS). I want the cursor to stay in the location it was in when the user first right clicked.

I am guessing this is probably not nearly as complicated as I am making it but I cant seem to find anything that has helped thus far. I have found several tutorials/excerpts on it but I havent got mine working yet. Below is my code for the MouseMove event (C# - I am using SharpDX framework).

            if (Input.Mouse.IsRightMouseDown &&
                Input.Mouse.PositionHasChanged(new Vector2(mouseEventArgs.X, mouseEventArgs.Y)))
            {
                var deltaY = mouseEventArgs.Y - Input.Mouse.OriginalRightMousePosition.Y;
                var deltaX = mouseEventArgs.X - Input.Mouse.OriginalRightMousePosition.X;
                var angle = (float)Math.Atan2(deltaY, deltaX);

                Camera.RotationY -= (float)Math.Sin(angle) * Global.MouseRotationSpeed;
                Camera.RotationX -= (float)Math.Cos(angle) * Global.MouseRotationSpeed;

                Input.Mouse.ResetMousePositionToOriginal();
            }

I would appreciate any help/advice I can get!! :)

Thanks in advance!!!


texts: Some help understanding and modifying a 2D shader

texts:
I have a similar question as the one posed here, except that I don't wish to use a 1D Color Palette.

I simply wish to have it display 1 color of my choosing (red, for example).  I plan to use this as a "shield" effect for a 2D ship.

I also wish to understand how it works a little bit better, as I'll be the first to admit that shaders in general are not my strongest suit.  I'm not asking for an overview of HLSL (as that is too broad of a subject), just an explanation of how this shader works, and the best way to implement it in a 2D game.

Code examples would be ideal (even if they are theoretical) but if the answer is explained well enough, I might be able to manage with plain old text.

This is also in XNA 4.0.

Thanks in advance.


texts:
I wrote a script to save and load game statistic. It works fine. In this script, two levels have it own score and timer. So, I have to write level by level it own score and timer. The issue is if I have 100 or 200 levels in my game. I have to write for every level. Yes will work, but will take time. So, I was thinking if there any simple method to shift the number of lines like use List or anything else ?

public gameStatic dr;

void Awake()    {
    Load_game_end();
}

   public void Save_game_end()  {
    BinaryFormatter bf = new BinaryFormatter();
    FileStream data_file = File.Create(Application.persistentDataPath + "/WarWorld.datt");

    level_static data = new level_static();
    data.level1tv = dr.level1t; // level one
    data.level2tv = dr.level2t; // level two
    //
    data.timer1 = dr.finalTime1; // level one
    data.timer2 = dr.finalTime2; // level two
    //
    data.total_money = dr.total_money;

    bf.Serialize(data_file, data);
    data_file.Close();

    Debug.Log("Game full saved");

}

public void Load_game_end() {
    if (File.Exists (Application.persistentDataPath + "/WarWorld.datt"))
    {
        BinaryFormatter bf = new BinaryFormatter();
        FileStream data_file = File.Open (Application.persistentDataPath + "/ballworlds.datt", FileMode.Open);
        level_static data = (level_static)bf.Deserialize(data_file);
        data_file.Close();

        dr.level1t= data.level1tv;
        dr.level2t = data.level2tv;
        //
        dr.finalTime1 = data.timer1;
        dr.finalTime2 = data.timer2;
        //
        dr.total_money = data.total_money;

        Debug.Log("Game full loaded");
    }

    else {
        Debug.Log("save not found");
    }

}

public void delete_save_file() {
    File.Delete(Application.persistentDataPath +"/WarWorld.datt");
    Debug.Log("delete save file");

}

[Serializable]
class level_static
{
    public float total_money;
    //
    public float level1tv; // height score level 1
    public float level2tv;

    //
    public float timer1; //  level 1 timer
    public float timer2;

}


texts: Draw line between tiles of tiled map in libgdx

texts:
I want to draw line between two tile of my .tmx map in libgdx . I want to get a tile position but not in pixels , in maps grid numbers like : (0 , 6 ).
or is there any way to change a tile color in libgdx.
i can get tile like below:

layer=(TiledMapTileLayer)tiledMap.getLayers().get(0);
layer.getCell(row, col).getTile()

but can not to draw some thing on the tile.


texts:
I'm new of the topic, and today, I tried my first OpenGL program. It simply drawa a particular  figure to the screen, and allows the user to rotate around it with buttons.

Writing code, I was thinking about rendering. When I create a list with glBeginList and I rotate, I cancel the figure on the screen and rotate the camera, before redrawing the figure.

Do I have to cancel everything and redraw for animation, or is there another way?


texts: Game-oriented programming language features/objectives/paradigm?

texts:
What are the features and language objectives (general problems to solves) or paradigms that a fictive programming language targetted at games (any kind of game) would require?

For example, obviously we would have at least Performance (in speed and memory) (because a lot of games simply require that), but it have a price in the languages we currently use.
Expressivity might be a common feature that is required for all languages.

I guess some concepts from not-usually-used-for-games paradigms, like actor-based languages, or language-based message passing, might be useful too. So I ask you what would be ideal for games.

(maybe one day someone will take those answers and build a language over it? :D )

Please set 1 feature/objective/paradigm per answer.

Note: maybe that question don't make sense to you. In this case please explain why in an answer. It's a good thing to have answers to this question that might pop in your head sometimes.


texts: Deformation of Sphere using Transformations

texts:
I have a graphic related question. I need to have a transformation matrix that I have no idea about what it is. The problem is to create right image from the right sphere. I created those images in Maya, but I need some matrices for the graphics course. Here is the image:

Our professor told us to use some sine and cosine in our transformations, but I have no idea what he meant. I thought of intersecting a plane from the grid(that is xz plane) and sphere, and then scaling down the resulting circle. Would that work?

I also checked this paper, however it looks like a bit advanced for me. Another thing is I guess that paper is not about the same type of information I was looking for.

It would be great if you could help me.


texts:
I am just curious as to how in many games (namely games like arkham asylum/city, manhunt, hitman) do they make it so that your character can "grab" a character in front of you and do stuff to them. I know this may sound very confusing but for an example go to youtube and search "hitman executions", and the first video is an example of what i'm asking.

Basically I'm wondering how they make your model dynamically interact with whatever other model you come across, so in hitman when you come up behind some one with the fibre wire you strangle the other character or if you have the anesthetic you come up behind some person and put your hand over there mouth while they struggle and slowly go to the floor where you lay them down.  I am confused as to whether it was animated to use two models using specific bone/skeletal identifiers, if it is just two completely separate animations that are played at the correct time to make it look like they are actually interacting or something else all together.

I am not an animator so i assume most of what i just said is not right but i hope that some one can understand what i mean and provide an answer.

PS) I am a programmer and I am in the process of building a hitmanesque game, just because i love that style of game and I want to increase my skills on something fun, so if you do know what i'm talking about have some examples with involving both models and programming (i use c++ and mainly Ogre3D at the moment but i am getting into unity and XNA) i would greatly appreciate it.

Thanks.


texts: I'm using SpriteBatch.DrawString, which seems to not have an overload for text alignment. How can I draw aligned text?


texts: Designing a profit maximization model - multi-level game

texts:
I am looking for some help in designing a multi-level game for a network simulator I am building.

In this network, actors have a choice to set up a number of units and to fill their units with money. They have a fixed amount of money that they start out with and are aiming to gain the earn the largest monetary reward they can.

Before the game starts, each actor has a heterogeneous amount of money and no units.

A pot of money will be distributed to the actors according to their relative size in the marketplace, which is determined by the number of units they have and the amount of money in each unit. Specifically, each unit will receive a score and the proportion of the reward claimable for that unit is determined by that unit's score divided by the total of all units' scores in the network. Logically, an actor's reward is the sum of their units' scores divided by all the units' scores in the network.

A unit's score is divided into two parts: operations and investment. A unit receives 0.7 points for operating (it is assumed all units will gain at least this score), and a unit can receive up to 0.3 points for the level of investment in the node.

There is a minimum investment of $20 for a unit to be eligible for rewards. When a unit has the minimum investment, it earns 50% of the total possible investment points - 0.15. This gives a node with the minimum investment amount a score of .85.

For all investment above the minimum, there are diminishing marginal returns with the optimal investment being $50, which gives 90% of the total possible investment points - 0.27 - and an overall score of .97

For further reference, here are the percentages of the total possible investment points (0.3) for each investment level.

$20 - 50% (of 0.3) --> .15

$25 - 65%

$30 - 75%

$35 - 81%

$40 - 85%

$45 - 88%

$50 - 90%

This is calculated by an arctan diminishing marginal returns function, the second derivative of which is 0 at $50.

--

How can I write an equation that shows how an actor chooses how many units to build and how much money to put in each unit?


texts:
Say I have three different gameObjevcts, each representing rock, paper or scissors. These objects all have a Player script attached to them. The Player script has two functions i want to use, MoveSelected(), MoveNotSeleccted(). When the function CPUMove() is called, I want the program to randomly choose one of the three moves. My question is, how do I call a either of the functions fro another script RPS_Game? I thought of using Invoke() somehow but after trying couple of things with it, I got no where. Can someone please help me out?

public class RPS_Game {
    public void CPUMove() {
        int rand = Random.Range(1, 3);

        if(rand == 1) {
          //call MoveSelected() for one of the three Player objects and
            MoveNotSelected() for the other two
        }
        else if(rand == 2) {
          //call MoveSelected() for one of the three Player objects and
            MoveNotSelected() for the other two
        }
        else if(rand == 3) {
          //call MoveSelected() for one of the three Player objects and
            MoveNotSelected() for the other two
        }
    }
}


texts: How do I make a vehicle move to a point and stop without overshooting or oscillating?

texts:
Ok so consider we have a vehicle like the one I described in my answer to this question, with a 2D position, velocity, angular velocity, and drag/friction. It can accelerate and break by a variable amount, but not stop dead instantly or reach top speed instantly. How can I make it move to a particular point and stop - in the fastest time possible - without overshooting or oscillating?

I was thinking something like:

turn towards target position.
accelerate
look 1 tick ahead, asking "If I applied the breaks next tick, would I overshoot the target?"
If it would overshoot, apply the breaks now by some amount.

I'm sure this is a solved problem and there is a probably a better method than the one I described.


texts: Unity AssetBundles, server and security concerns

texts:
We're trying to implement AssetBundles in our current Unity project for Android and iOS.

My question is about security. To download AssetBundles, our application need to connect to our server. On our server, we got a web service that returns the download link for the bundle needed by the application.

However, the ID and password to connect to our web service are written in plain text in our application. This may sounds as extremely naive, but is this an issue? Could someone find the ID and password from say, the .apk file?

I don't have a lot of knowledge in the field of servers and network security, so I'm trying to keep up with what our team is doing.


texts: Why does using glReadBuffer/glReadPixels returns black image on Intel cards?

texts:
I have this piece of code

glReadBuffer( GL_FRONT );
glReadPixels( 0, 0, width, height, GL_RGB, GL_UNSIGNED_BYTE, buffer );

Which works just perfectly in all the Nvidia and AMD GPUs I have tried, but it fails in almost every single Intel built-in video that I have tried. It actually works in a very old 945GME, but fails in all the others. Instead of getting a screenshot I am actually getting a black screen.

If it helps, I am working with the Doom3 Engine, and that code is derived from the built-in screen capture code. By the way, even with the original game I cannot do screen capture on those intel devices anyway. My guess is that they are not implementing the standard correctly or something. Is there a workaround for this?


texts: Why loss of floating point precision makes rendered objects vibrate?

texts:
I'm working on an open-world game. I noticed glitches when I move far away from the origin. The objects seem to be shaking or wiggle. Especially the z-fighting seems to wiggle. And the objects that move. If I understand correctly this is caused by floating point precision problems. Currently I'm using floats for everything on CPU side and in shaders, I don't use doubles.

Before I try to come up with a solution I want to understand how does float imprecision lead to objects shaking on the screen. (Why do they shake instead of disappearing or stopping or something?) And where does the error come from: the calculations on CPU side (camera movement / physics calculations of objects) or calculations on GPU side (transform in shaders / depth-buffer not being precise enough)? Why do objects not shake when they are far away from the camera?

(I asked this before but realized my question was very broad, I wanted to be more specific.)


texts: How to achieve a dynamic soft see-through hole effect in a wall with shaders?

texts:
I'm looking for a way to create a dynamic soft see-through hole effect for room walls. I know a few ways how to do it (for example multitexturing with second layer being the hole mask in screenspace), but all involve rendering walls with blending on which is too expensive for the mobile project I'm working on. Is there any way to do this without using blending on the whole geometry (the hole can appear in any place on any wall). Please see the attached image for a better illustration of the effect:

Also, I'm very open to any links to papers/tutorials that might not be solving the exact problem but doing something close that might get me on the right tracks. Thank you!


texts:
I'm trying to move the player based on UI buttons. I found this topic which covers the button listener: https://forum.unity.com/threads/touch-and-hold-a-button-on-new-ui.266065/#post-1944748

Now I know when the button is being pressed, but how can I "connect" those two scripts to make the player move?

I have this script to the player which was moving without using button.

public class player : MonoBehaviour {
     Rigidbody m_Rigidbody;
     public float m_Speed;

     // Use this for initialization
     void Start () {
         m_Rigidbody = GetComponent<Rigidbody>();
         //Set the speed of the GameObject
     }

     // Update is called once per frame
     void Update () {
         /* OLD -> WITHOUT BUTTON

         float x = Input.GetAxis("Horizontal");
         float y = Input.GetAxis("Vertical");

         x = -x;

         m_Rigidbody.velocity = new Vector2( x * m_Speed,  y * m_Speed);
         */
     }
 }

 public class scrLeftButton : MonoBehaviour, IPointerDownHandler, IPointerUpHandler {

     // Use this for initialization
     void Start () {

     }

     // Update is called once per frame
     void Update () {
         if (!isPressed) {
             return;
         }
     }

     bool isPressed = false;

     public void OnPointerDown(PointerEventData eventData){
         isPressed = true;
     }

     public void OnPointerUp(PointerEventData eventData){
         isPressed = false;
     }
 }


texts: How can OnMouseDown in the parent object be triggered from the child placed on top of it?

texts:
I am learning Unity from a book. The example is to create a 2D memory game as follows (viewed in perspective view).

The green (background) at z=5, the purple diamond (front card) at z=0 and the red (back card) at z=-5 for example. The front card is set as the parent of the back card in the hierarchy window.
A box collider (2D) component  and a script below are attached only to the parent.
public class FrontCard: MonoBehaviour
{
    public void OnMouseDown()
    {
        Debug.Log("testing 1, 2, 3!");
    }
}

When I play the game and click the back card, the OnMouseDown gets invoked.
Question
How can the OnMouseDown get invoked when I click the back card by considering the script is attached to the front card game object that is placed below the back card?


texts: Minimum target resolution for a desktop PC/Mac Game?

texts:
Lets assume I start a new PC/Mac desktop (not netbook) game today that will take something like one year to be released publicly and that is a lot about graphic details (not realistics, just graphically "rich").

The higher screen resolution the better but I build the game in a way that adapt to the screen (3D, screen space relative ui, etc). However I still need to have a minimal resolution to be sure my UI and texts are still clear in low resolutions.

For the moment I'm assuming that 1024x768 is the really lower resolution any such game could ask for. But as time is going on fast I'm thinking maybe I'm wrong and a game with visual details should target higher resolutions as minimum resolution, if started today?

Assuming Steam users would be the target audience, I looked at the Steam Hardware Survey to get an idea but it don't talk about the resolutions of games being played, only about desktop resolution. I'm assuming that most players will play most games with lower resolution than their desktop resolution...?


texts: Authoritative game server and database storage

texts:
In an authoritative game server working with websockets, should you store every action to the database before sending the response to the client? The risk is the slow response time.
Or should the result be calculated with variables we cached earlier and cache the result to update the cache to the database once in a while? But with a risk that data can be lost if the server crashes before it's stored into the database.
For a game server handling up to 500 players at the same time and up to 16 request by seconds with no heavy calculations, what should be decided?


texts: Can you specify which VBO/EBO to use with glDrawElements?

texts:
I'm creating a voxel-like game. I'm not sure if I am using VBO/EBO's correctly. I am creating a new VBO & EBO for every chunk. This is done once, but chunks call a render function in every block inside, and the block calls glDrawElements (Is there a more efficient way?). How can I specify which VBO & EBO each is supposed to use? Is this possible?

Thank you!


texts: Best way to calculate city influence maps similar to civilisation?

texts:
As the title says, imagine you want to generate the influence mask for a city, given that the map is a 2D grid rather than hex. An extra bit is that different points on the map might have different "influence absorpion" values. Some simple scenarios to make it less abstract:

Scenario 1:
City centered at (5,2) has 10 influence
All tiles have influence_absorption = 1
Tile at (6,2) has 9 influence, therefore within the influence of the city
Tile at (7,2) has 8 influence, therefore within the influence of the city
Tile at (14,2) has 1 influence, therefore within the influence of the city
Tile at (15,2) has 0 influence, therefore out of the influence of the city

Scenario 2:
City centered at (5,2) has 10 influence
All tiles have influence_absorption = 1, but tile at (6,2) has influence_absorption=4
Tile at (6,2) has 9 influence, therefore within the influence of the city
Tile at (7,2) has 5 influence, therefore within the influence of the city
Tile at (11,2) has 1 influence, therefore within the influence of the city
Tile at (12,2) has 0 influence, therefore out of the influence of the city

It's like using dijkstra on a 2D grid with single-source, multiple-destinations. Any pointers for good/fast algorithms are appreciated. Also, if this problem has a well-known name, that'd be appreciated as well.

I made the following algorithm (independently like Jon's, thanks btw, it's the intuitive solution I guess):

p0 = CITY_COORDS
Initialize all influences with 0
set CITY_INFLUENCE as the new influence at p0
list = [ p0 ]
while list not empty
    p = get point in list with highest influence rating
    pi = get influence at point
    pa = get absorption at point
    new_i = pi -pa
    list_is_updated = false
    for each valid neighbour nb
        nbi = get neighbour's influence
        if new_i > nbi
            set new_i as the new influence at nb
            add nb to list
            list_is_updated = true
    if list_is_updated
        sort list // with selection sort, very fast

And I have the following results, which can also be helpful to understand what I'm after:

Influence absorption

Influence mask

Influence visualisation (city at the brightest spot)


texts:
I’m designing something which has a rather large number of 3d roundish objects and needs collision detection, in the best way I can muster. The user can move her fingers through the pile of objects and they need to move away. The objects are all a little different, though.
I would love to know the various ways on how I can reduce this problem from typical O(n^n) nightmare.
Obviously I can reduce the non-visible geometry, and I’m suspecting a lot of simplification will be possible with applied graph theory.. I also play with the idea of having one or multiple meshes that represent the surfaces on which these round objects cling, and then only deforming these. But some effects may be hard to simulate that way.
But I am a little lost in getting a good footing to start. Can anyone point me to good resources or known algorithms/hacks? I’m not averse to using known engines (bullet/unity etc) but I want to have a specialised solution, not a generic one.


texts: How should I rotate vertices around the origin on the CPU?

texts:
I have tried using glm::rotate and such. glm::translate works fine, but rotate doesn't work (if I rotate before/after a translation).

Here is my current setup:

glm::vec4 Off = glm::vec4(0, 0, 0, 1);
glm::vec4 result = Util::createTransform(offset) * Off;

for (int i = 0; i < Tvertex.size(); i++) {
    Tvertex[i] += glm::vec3(result.x, result.y, result.z);
    Tcolors[i] = currentColor;
}

And here is my Util::createTransform:

glm::mat4 Util::createTransform(glm::vec3 pos) {
    glm::mat4 trans = glm::mat4(1.0);
    trans = glm::translate(trans, pos);
    return trans;
}

glm::mat4 Util::createTransform(glm::vec3 pos, glm::vec3 rot) {
    glm::mat4 trans = glm::mat4(1.0);
    trans = glm::rotate(trans, glm::radians(rot.x), glm::vec3(1, 0, 0));
    trans = glm::rotate(trans, glm::radians(rot.y), glm::vec3(0, 1, 0));
    trans = glm::rotate(trans, glm::radians(rot.z), glm::vec3(0, 0, 1));
    trans = glm::translate(trans, pos);
    return trans;
}


texts: How to emulate knob turning, based on x/y movement?

texts:
I'm doing a game where one component is that you turn a knob.  I'm having trouble getting good "knob behavior".

I know the current touch/mouse X,Y location, and I keep track of the previous X,Y location, so I can determine if I'm going left or right and/or up or down.

It works, but it's crude.  I suspect I have to take an average of any given direction over a period of time (say, last quarter second) to eliminate jitter because people don't move uniformly in the same movement every moment.

I can't really use touchdown/release because you should be able to put the touch down, then move left/right up/down continuously without release, and the knob would turn, just as if you had a free-spinning audio control or video shuttle (say).

Any thoughts in this direction on how to even it out?


texts: "Your android setup is not correct" error on Unity showing up even after reinstalling OpenSSL (Using Facebook SDK)

texts:
I want to build for Android and today one error popped up after building.

  Your Android setup is not correct. See Settings in Facebook menu. UnityEditor.HostView:OnGUI()

Important things about this problem:

The only error in the inspector I can see is

  OpenSSL not found. Make sure that OpenSSL is installed and that it is in your path.

Even tho I have installed it and added it to my path

When I open the inspector in Facebook> Edit Settings, unity becomes very unresponsive
This error has not popped up before today
I still get a APK even if I get errors


texts:
Before we get started I checked the following questions:
Isometric Tile Selection with rectangular bounding boxes
Isometric rendering and picking?
Calculating the number of tiles shown on an isometric map <- this is exactly how I get my top-left and bottom-right tile, but I can't calculate what's between them
I can pick tiles perfectly, I'm struggling with the automatic selection given two tiles (top-left and bottom-right in screen coordinates).

I've attached a drawing to help you visualize:

As you can see it's a Diamond setup, not staggered isometric. I'm struggling with finding the orange tiles, I have the green tiles' coordinates.

Btw, it's not true isometric, it's 2:1 "isometric".


texts:
How do I raycast from a UI object?
I have tried

Ray ray;
Camera cam;
Transform obj; //UI object

ray = cam.ViewportPointToRay(obj.position);

AND

ray = new Ray(obj.position, obj.forward);

Neither of these seem to work.


texts: Should particles check if they are in a region, or regions if particles are in them?

texts:
I have around 100 to 200 particles in my game. Then I have 5 to 20 regions (circle-shape) which should count the particles which enter them and add some force to them, so they change their direction.

My idea was now to keep a list of all particles and every region should check the whole list every frame, whether a particle is inside it. For this I calculate the distance between the particle and the central point of the region and check weather its <= the radius of the region.

Is this the most efficient way to do it? Or should every particle have a list of all regions and check whether they are in one of it? Or a totally different approach?

I would like this application to be able to run also on older mobile devices like an iPhone 4S.


texts: How to convert coordinates between world coordinates and screen coordinates

texts:
I am using a tilemap in which I have square tiles.
Knowing that, the size of the screen and the player position(in world coordinates) how I convert between this systems? Is there any formula?

EDIT:
For example:
The top left corner is (0,0)
player position in tiles: (ScreenX / 2, ScreenY / 2)
player position in screen: always (0, 0)
grass tile position in tiles: (Gx, Gy)

Now the question is: how can I get the screen coordinates for the grass tile?


texts: Why are we not using integers in game physics?

texts:
We can use integer for game physics (or without physics, simply object representation): mass, position and rotation, where the integers represent, for example, the number of milligrams, millimeters or (1/56000) of a degree. However, almost all game code I've seen recently use floating points.

Is it slower to use integers for game physics calculations? Are there any other advantages and disadvantages from the developer's point of view for using integers? Or it is because all our hardwares


texts: Consturcting a sprite bitmap from mutliple partial sprties across sheets

texts:
First of all, I am not using engine and this is for Android. Bear with me if I use incorrect lingo as I am not experienced in game dev (but I am trying)

I am being provided multiple sprite sheets. Each sheet represent the animation of one part of a warrior (ie. Head sheet, arm sheet, leg sheet and body sheet).

I intend to basically construct the frames of the warrior using the sprite sheets. I basically thought of the following. For every Frame, I will create a bitmap that consists of the different parts ( by extracting the correct part from every sheet and placing it in the intended x/y position). That way every bitmap represent a frame.

Is my approach correct? Is there different way/recommended way to do this?

Please share your advice ( anything but game engine as it is tool late to use)

Thank you

PS: I need the end result to be a bitmap because at the end, I will supplying a bitmap to another function at once every 200ms.


texts: How do I interpolate an object's rotation on a Z-axis based on mouse position?

texts:
I need to apply rotation to an object, based on the mouse movement around it to a z-axis only.

Let's take this picture:

Violet - current mouse position
Blue - mouse movement
Red - the
object to be rotated

I use this script and it works fine:

mousePos = Input.mousePosition;
screenPos = Camera.main.ScreenToWorldPoint(Vector3(mousePos.x, mousePos.y,
transform.position.z - Camera.main.transform.position.z));

transform.rotation.eulerAngles.z = Mathf.Atan2((screenPos.y - transform.position.y), (screenPos.x - transform.position.x)) * Mathf.Rad2Deg;

but... it work's in real-time which I don't want, so I need to interpolate it. I used Quaternion.Lerp/Slerp and I got a strange result.

When I move the mouse too fast (rotate it around the cube) it lerps to mouse's new position (which is ok) but it changes the rotation direction when the angle changes from -180 to 180 or 180 to -180.

It's because of Quaternion math probably, to be precise - Quaternion decides to switch the rotation direction, because it found a shorter path.

The question

How do I smoothly (with lerp) rotate the object (on a z-axis) to look at the mouse position so it doesn't make the above glitch when lerping?


texts: convert mouse coords to zig-zag isometric

texts:
I was wondering, how do I convert mouse coordinates to zig-zag isometric coordinates?

I already know how to convert to isometric using the Diamond approach, so I just need to know about the zig-zag approach. I also know how to get the mouse coordinates as well.

Here is the zig-zag approach (copied from the link below):

Here is the link I used for the definition of drawing both the Diamond and zig-zig isometric approaches.

https://stackoverflow.com/questions/892811/drawing-isometric-game-worlds

Help is greatly appreciated, thanks.


texts:
My player in unity moves but doesn't stop when i let go of the key heres the code:

using UnityEngine;
using System.Collections;

public class Player : MonoBehaviour {

    Vector3 movement = new Vector3();
    public CharacterController player;
    public float speed;
    public float vertSpeed;
    public float gravity;
    // Use this for initialization
     void Start(){

    }
    void Update(){
        PlayerMovement ();
    }
    void PlayerMovement(){

        if (Input.GetKeyDown (KeyCode.Space)) {
            transform.Translate(Vector3.up * vertSpeed * Time.deltaTime, Space.World);
            if (!player.isGrounded) {
                movement.y = movement.y - gravity * Time.deltaTime;
            }
        }
        if (Input.GetKey (KeyCode.A)) { // left
            movement.x = movement.x - speed * Time.deltaTime;

        } else if (Input.GetKey (KeyCode.D)) {// goes right
            movement.x = movement.x + speed * Time.deltaTime;
        }

        player.Move ((movement * speed) * (Time.deltaTime));
    }

}


texts: Simplest way of skeletal animation in openGL

texts:
I am not interested in using easy libraries like assimp which will import collada files with ease to get skeleton animation done.

I wanna know what is the minimal requirement to get the animation done.

What I understand is that a bone is a 3*3 rotation matrix which is associated with each group of vertex.

We have to augment it with the model matrix to animate anything

How would I play a sequential animation with my existing bone system.

What's the workflow to process the bones. Sending bones through Uniform block is slow but I would consider doing it.

What's the simplest file format to store rig and animation data. Collada is unnecessarily advanced and complex.

Or how would I write my own file format for animation.

I am using blender to model and rig.
How would I even manage to get an exporter for my format in blender


texts: Detect Input.GetMouseButtonUp outside a GameObject in Unity?

texts: How do I detect Input.GetMouseButtonUp outside a specific GameObject's area in Unity? Are there any Unity Assets for this?


texts: Any way to visualize how will game objects look on different screens?

texts: After completing my game and sending it to a bunch of friends with different devices, they complained about how some game buttons were too small. (I have developped a touchscreen game but after finishing and having issues with the touch detection I just decided I'd place buttons for controls on the screen. ) I obviously put all the button in a canvas, so it should normally scale with the screen and keep its anchor point, but the problem apparently is that it DID keep the anchor point, but it didn't scale, so even though the buttons looked pretty huge on my small sized game screen, and looked decent in an 480 x 800 emulator, it looked very mini sized in a 720x1280 phone. Any help on how I can make a button scale to the screen? Thanks!


texts: Getting velocity in only one plane (X) in Kismet (UDK)

texts:
I'm trying to make a character in 2.5 platformer (in UDK) to "climb" a giant tree trunk by walking on a spiral staircase enveloped around the tree. When character goes right the tree rotates thru matinee sequence so it seems that the character is moving while in reality it is the tree that moves.

I connected the matinee sequence playrate to the velocity of the character and its all good as long the character just moves left or right. When it jumps though, the velocity still affects the playrate - it should not as character moves up/down, not right/left.

How do I set it up in Kismet so I get a float variable with velocity only in the X plane (horizontal)?