texts:
I have implemented basic shadow mapping for the first time in OpenGL using shaders and I'm facing some problems. Below you can see an example of my rendered scene:

The process of the shadow mapping I'm following is that I render the scene to the framebuffer using a View Matrix from the light point of view and the projection and model matrices used for normal rendering.

In the second pass, I send the above MVP matrix from the light point of view to the vertex shader which transforms the position to light space. The fragment shader does the perspective divide and changes the position to texture coordinates.

Here is my vertex shader,

#version 150 core

uniform mat4 ModelViewMatrix;
uniform mat3 NormalMatrix;
uniform mat4 MVPMatrix;
uniform mat4 lightMVP;

uniform float scale;

in vec3 in_Position;
in vec3 in_Normal;
in vec2 in_TexCoord;

smooth out vec3 pass_Normal;
smooth out vec3 pass_Position;
smooth out vec2 TexCoord;
smooth out vec4 lightspace_Position;

void main(void){
    pass_Normal = NormalMatrix * in_Normal;
    pass_Position = (ModelViewMatrix * vec4(scale * in_Position, 1.0)).xyz;
    lightspace_Position = lightMVP * vec4(scale * in_Position, 1.0);
    TexCoord = in_TexCoord;

    gl_Position = MVPMatrix * vec4(scale * in_Position, 1.0);
}

And my fragment shader,

#version 150 core

struct Light{
    vec3 direction;
};

uniform Light light;
uniform sampler2D inSampler;
uniform sampler2D inShadowMap;

smooth in vec3 pass_Normal;
smooth in vec3 pass_Position;
smooth in vec2 TexCoord;
smooth in vec4 lightspace_Position;

out vec4 out_Color;

float CalcShadowFactor(vec4 lightspace_Position){

    vec3 ProjectionCoords = lightspace_Position.xyz / lightspace_Position.w;

    vec2 UVCoords;
    UVCoords.x = 0.5 * ProjectionCoords.x + 0.5;
    UVCoords.y = 0.5 * ProjectionCoords.y + 0.5;

    float Depth = texture(inShadowMap, UVCoords).x;
    if(Depth &lt (ProjectionCoords.z + 0.001)) return 0.5;
    else return 1.0;
}

void main(void){

    vec3 Normal = normalize(pass_Normal);
    vec3 light_Direction = -normalize(light.direction);
    vec3 camera_Direction = normalize(-pass_Position);
    vec3 half_vector = normalize(camera_Direction + light_Direction);

    float diffuse = max(0.2, dot(Normal, light_Direction));
    vec3 temp_Color = diffuse * vec3(1.0);

    float specular = max( 0.0, dot( Normal, half_vector) );

    float shadowFactor = CalcShadowFactor(lightspace_Position);

    if(diffuse != 0 && shadowFactor &gt 0.5){
        float fspecular = pow(specular, 128.0);
        temp_Color += fspecular;
    }

    out_Color = vec4(shadowFactor * texture(inSampler, TexCoord).xyz * temp_Color, 1.0);
}

One of the problems is self shadowing as you can see in the picture, the crate has its own shadow cast on itself. What I have tried is enabling polygon offset (i.e. glEnable(POLYGON_OFFSET_FILL), glPolygonOffset(GLfloat, GLfloat) ) but it didn't change much. As you see in the fragment shader, I have put a static offset value of 0.001 but I have to change the value depending on the distance of the light to get more desirable effects , which not very handy. I also tried using front face culling when I render to the framebuffer, that didn't change much too.

The other problem is that pixels outside the Light's view frustum get shaded. The only object that is supposed to be able to cast shadows is the crate. I guess I should pick more appropriate projection and view matrices, but I'm not sure how to do that. What are some common practices, should I pick an orthographic projection?

From googling around a bit, I understand that these issues are not that trivial. Does anyone have any easy to implement solutions to these problems. Could you give me some additional tips?

Please ask me if you need more information on my code.

Here is a comparison with and without shadow mapping of a close-up of the crate. The self-shadowing is more visible.


texts: How long till HTML5 canvas becomes a viable game development platform?

texts:
So I have been working on web application. So invariably what it boils down to is making simple games which were previously based on flash or openGL. Now I know apple was moving away from flash because its proprietary unlike their stance that its got "pathetic performance"!
Not true, try playing a canvas game, I can assure you at any point of time (including when its idle) it will use up a fair bit of processing power just to redraw the UI. Now I do understand that this is my fault because when the game is not active I should not be redrawing the canvas, but honestly its a lot of work and I suppose there should be libraries which should be able to assist me with that! So, how much will it be before I see a decent canvas library which handles these "tiny" issues for me? I can't honestly expect Steve Jobs to be doing anything more for HTML5!
I someone knows of a good library, I am all ears...! :)

PS: I use mootools and am presently using Mootools Canvas Library.


texts:
I'm very new to Unity and this may simply be a failure of google-fu but I hope someone here can help me out.

I'm working through a series of tutorials on how to create an RPG in Unity, making small improvements and embellishments as I go to make sure I understand the concepts.

I've built a player character with walk and run animations and a camera which follows the player around and stays aimed at the centre of the character model using the following code.

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

public class CameraFollowPlayer : MonoBehaviour
{
    GameObject target;

    // Start is called before the first frame update
    void Start()
    {
        target = transform.parent.gameObject;
    }

    // Update is called once per frame
    void Update()
    {
        transform.LookAt(target.transform.position);
    }
}

The problem with this is the angle this leaves the camera pointing at in-game is to acute, making it difficult to see what is ahead of the character. How can I adjust the target of the LookAt instruction to result in a shallower X-axis rotation of the camera?


texts:
I'm currently making a shoot em up in monogame.

I want to add just one animation to my object. No commands or transitions between animations for different actions: just an object swapping between different images all the time.

For example, my player will have 4 different images for it and I'd want it to always swap trough these images.

Animation guides I've reviewed seem way too complicated for my needs. Unlike the examples they cover, I don't want different animations for different commands.

How can I make this type of simple, always-looping frame animation?

Edit

I managed to make a constantly looping animation to a sprite and but I don't know how to insert into myPlayer.

Game1:
        Texture2D myPlayerAnim;
        Rectangle myDestRect;
        Rectangle mySourceRect;
        Texture2D myEnemyAnim;
        Rectangle myEnemyDestRect;
        Rectangle myEnemySourceRect;
        float myElapsed;
        float myDelay = 100f;
        int myFrames = 0;

Initialize:
            myDestRect = new Rectangle(0, 0, 512, 512);
            myEnemyDestRect = new Rectangle(0, 0, 808, 608);

LoadContent:

            myPlayerAnim = Content.Load<Texture2D>("SpriteSheetPlayerAnim");
            myEnemyAnim = Content.Load<Texture2D>("SpriteSheetEnemyAnim");

Update:
            myElapsed += (float)aGameTime.ElapsedGameTime.TotalMilliseconds;

            if (myElapsed >= myDelay)
            {
                if (myFrames >= 3)
                {
                    myFrames = 0;
                }
                else
                {
                    myFrames++;
                }
                myElapsed = 0;
            }

            mySourceRect = new Rectangle(512 * myFrames, 0, 512, 512);
            myEnemySourceRect = new Rectangle(808 * myFrames, 0, 808, 608);

Draw:

            mySpriteBatch.Draw(myPlayerAnim, myDestRect , mySourceRect,
            Color.White);
            mySpriteBatch.Draw(myEnemyAnim, myEnemyDestRect, myEnemySourceRect,
            Color.White);´

Draw just draws the animations out but I don't know how to insert it into myPlayer. For myPlayer I currently have this but I couldn't figure out how to do it with my animations.

Draw:
myPlayer = new Player(TextureLibrary.GetTexture("player"), myPlayerPos, 200, new Vector2(.3f, .3f), 0, Color.White, 1000, 1);


texts: How do I create an in-app update for a mobile game?

texts:
I'm researching how to make an in app update on mobile game.

When there is a hotfix, or an update, I don't want users to have to go to Play store, or App Store to update, but rather for them to update inside the game (like in Clash of Clans). I want to do this because Apple takes too much time for reviewing.

I found https://ionic.io, they use Cordova to embebed HTML inside. We can do live update, rollback to old version with a click. This is pretty suitable for normal app, but for game, the performance is not great.

How can I create an in-app update like this?


texts: What is a fair price to pay for music licensing for a commercial game?

texts:
What is a fair price range for already existing (not custom-made) music if it's intended for a commercial game?

The music I have in mind is relatively unknown (independent music) and I'm already in contact with the label that controls the rights to it, I just need a relative price range to take with me into the negotiation.


texts:
I am looking to get a Camera component's "view" matrix in a script. I see that I can get the projection matrix using Camera.projectionMatrix, but I don't see a Camera.viewMatrix property...

I want these matrices in a script for a 3D graphics refresher tutorial that will visualize a camera's view and projection transforms in the form of game objects (representing vertices) that can be moved around the scene.


texts: 2D racetrack collision bounce using angle of reflection (bounce angle)

texts:
I am currently working on a race game where I want to define the collision of my vehicle with the outer and inner borders of the track.

If that happens to be the case I want to vehicle to bounce of the track but still move forward using the angle of reflection.

My racetrack looks like this:

I am wondering if the implementation is possible especially since I have curves in my track. I was thinking of defining the inner and outer boundaries using color recognition, in this case white and red, and then check for collision.

Thank you.

Update 1:

To execute what @Zebraman suggested I plan on doing the following:
To get the pixel color under the vehicle I think I have to iterate over all pixels and then check the colors of the pixels infront of the vehicle to make the vehicle bounce in the reflection angle.

How to perform the color check is for me still a question now. Hope Anatole could help. @Zebraman provided an explanation of how to get the pixels color. I don't understand it yet.

Hopefully someone would be able to explain.

Update 2:

I am going to use the following code to detect pixel collision:

static bool IntersectPixels(Rectangle rectangleA, Color[] dataA,
                            Rectangle rectangleB, Color[] dataB)
        {
            // Find the bounds of the rectangle intersection
            int top = Math.Max(rectangleA.Top, rectangleB.Top);
            int bottom = Math.Min(rectangleA.Bottom, rectangleB.Bottom);
            int left = Math.Max(rectangleA.Left, rectangleB.Left);
            int right = Math.Min(rectangleA.Right, rectangleB.Right);

            // Check every point within the intersection bounds
            for (int y = top; y < bottom; y++)
            {
                for (int x = left; x < right; x++)
                {
                    // Get the color of both pixels at this point
                    Color colorA = dataA[(x - rectangleA.Left) +
                                         (y - rectangleA.Top) * rectangleA.Width];
                    Color colorB = dataB[(x - rectangleB.Left) +
                                         (y - rectangleB.Top) * rectangleB.Width];

                    // If both pixels are not completely transparent,
                    if (colorA.A != 0 && colorB.A != 0)
                    {
                        // then an intersection has been found
                        return true;
                    }
                }
            }

            // No intersection found
            return false;
        }

Could anyone point me where to next?


texts: Accessing vertex Input in surf directly without vert's out parameter In Tessellation Shader

texts:
I can get the vertex Input in vertex shader as follows:

   o.worldPos = v.vertex.xyz;

But how do I get the worldPos directly without filling the out parameter in the vert function. Asking this because the shader is a DX11 Tessellation one and out parameter in vert function is not available at all.

basically I want Initialize my Input shader and pass It to surface shader In vertex shader.I can do It but It's different In Tessellation shader so I need to Accessing vertex position in surf directly without vert's out parameter.

Shader "Tessellation Sample" {
        Properties {
            _EdgeLength ("Edge length", Range(2,50)) = 15
            _MainTex ("Base (RGB)", 2D) = "white" {}
            _DispTex ("Disp Texture", 2D) = "gray" {}
            _NormalMap ("Normalmap", 2D) = "bump" {}
            _Displacement ("Displacement", Range(0, 1.0)) = 0.3
            _Color ("Color", color) = (1,1,1,0)
            _SpecColor ("Spec color", color) = (0.5,0.5,0.5,0.5)
        }
        SubShader {
            Tags { "RenderType"="Opaque" }
            LOD 300

            CGPROGRAM
            #pragma surface surf BlinnPhong addshadow fullforwardshadows vertex:disp tessellate:tessEdge nolightmap
            #pragma target 4.6
            #include "Tessellation.cginc"

            float _EdgeLength;

            float4 tessEdge (appdata_full v0, appdata_full v1, appdata_full v2)
            {
                return UnityEdgeLengthBasedTess (v0.vertex, v1.vertex, v2.vertex, _EdgeLength);
            }

            float _Displacement;

            struct Input {
                float4 position  : POSITION;
                float3 worldPos  : TEXCOORD2;   // Used to calculate the texture UVs and world view vector
                float4 proj0     : TEXCOORD3;   // Used for depth and reflection textures
                float4 proj1     : TEXCOORD4;   // Used for the refraction texture
            };

            void disp (inout appdata_full v, out Input o){
            UNITY_INITIALIZE_OUTPUT(Input,o);
            o.worldPos = v.vertex.xyz;
            o.position = UnityObjectToClipPos(v.vertex);
            o.proj0 = ComputeScreenPos(o.position);
            COMPUTE_EYEDEPTH(o.proj0.z);

            o.proj1 = o.proj0;
            #if UNITY_UV_STARTS_AT_TOP
            o.proj1.y = (o.position.w - o.position.y) * 0.5;
            #endif
            }

            sampler2D _MainTex;
            sampler2D _NormalMap;
            fixed4 _Color;

            void surf (Input IN, inout SurfaceOutput o) {
                o.Albedo = float3(0,0,0);
            }
            ENDCG
        }
        FallBack "Diffuse"
    }

but I have error:

Shader error in 'Tessellation Sample': 'disp': no matching 1 parameter function at line 173 (on d3d11)


texts:
Dear people from the forum, I am trying to develop a game prototype which uses OpenGL and I am designing the entire graphic engine. My game requires some tricks with the shaders, and therefore I had to write a very complex geometry shader with lots of ifs and for loops, it increases the complexity of the geometrical models.

I program on a linux OS and I was using an AMD graphic card with the MESA drivers (which have a very limited OpenGL support) but I managed it to work by forcing the driver to use newer versions of the api (by putting this before the command: MESA_GL_VERSION_OVERRIDE=3.3 MESA_GLSL_VERSION_OVERRIDE=330) and the program worked fine.
But even then, I had been struggling with the glsl shaders compilation. Sometimes there was nothing wrong with the code, but the compilation would raise an error and it would be fixed by adding a blank line somewhere in the source, by deleting one irrelevant line, multiplying some float by 1., or any ridiculous patch. Doing this would solve it. However, at least I know there is something wrong because the compiler tells me. But sometimes there could be an undefined behavior because some variable is not initialized or something like that, and there is no way of finding out what the problem is, especially if the shader is very complex like mine.

Right now I am using an nVidia graphic card with the proprietary drivers,
therefore I don't need to force the driver to support a 'new' version of OpenGL, but the shader does not work. It compiles but it doesn't work, I suspect there could be an undefined behavior but I cannot find it. The code is really complex and I cannot upload it here.

I am wondering why the ridiculous errors mentioned above occur (sometimes they appear when there is a REAL error, which is not detected), and if there is a way to get the warnings or undefined behaviors when the shaders are compiled successfully because the compilations logs are blank. I would not like to rewrite my shader entirely when it works perfectly with other graphic cards. Thank you in advance!


texts: What should developers do when they receive conflicting feedback about their game?

texts:
I've been working my first mobile game (I have done a lot of web and PC games before).

I wanted the idea to be simple but fun. The thing is, I received feedback from friends and family and I have heard a lot of contradictory opinions about my game. Some would say that the game is addictive, challenging and fun, while other didn't see it as a fun game and said it was boring or not really good enough.

Now that I have these two opposite opinions I don't know if my game is good or not.

What opinion should I listen to, and how am I supposed to know if the game is fun or not when people's opinions are mixed?


texts: What is the correct Order of Operations on OpenGL 2.0 Loading Texture in condense format?

texts:
I have come across a problem when I am loading a single texture onto a single quad, and this problem persisted during the planning phases of my project, before starting my development phase. I am confused on the order of operations required to load a texture.

Why am I confused? I used the order listed below and rewrote the project over and over again, and the results vary. As in, one project would load and display the texture correctly, while the other projects can't display the texture, but loads the texture just fine. Due to this, I am conflicted.

Here is the rundown on the order of operations required for me to load a texture and show it onto the screen using OpenGL 2.0.

Create window.
Set up game loop.
Create OpenGL 2.0 context.
Initialize objects and load necessary files and data. (Textures, bitmaps, etc.)
Set up vertex data. (In this case, a quad.)
Create vertex shader code.
Create fragment shader code.
Compile the codes. (Checking included.)
Create program.
Attach shaders to program.
Link.
Validate.
Obtain attribute and uniform locations.
Set up viewport.
Create projection matrix, be it perspective or orthogonal.
Create view matrix and initialize matrix state.
Set vertex attribute pointer.
Enable vertex array buffer.
Use view matrix as model matrix. Push/pop/transform when necessary.
Clear screen.
DrawArrays().

Are these correct in chronological order? Are there anything else I am missing? I am just stuck on the planning phase, and wanted to get the chronological order done right.


texts:
Video as you can see there I am trying to make my end screen restart my game but whats happening is that its not restarting my game its just loading the same thing when I die >> how could I make it so it restarts my game when I click start game on my end screen?

my end screen def

---------------------------------------------------

def button(msg,x,y,w,h,ic,ac,action=None):
    mouse = pygame.mouse.get_pos()
    click = pygame.mouse.get_pressed()

    if x+w > mouse[0] > x and y+h > mouse[1] > y:
        pygame.draw.rect(window, ac,(x,y,w,h))
        if click[0] == 1 and action != None:
            action()
    else:
        pygame.draw.rect(window, ic,(x,y,w,h))
    smallText = pygame.font.SysFont("comicsansms",20)
    textSurf, textRect = text_objects(msg, smallText)
    textRect.center = ( (x+(w/2)), (y+(h/2)) )
    window.blit(textSurf, textRect)

#------------------------------------------------------

def text_objects(text, font):
    textSurface = font.render(text, True, black)
    return textSurface, textSurface.get_rect()

def endScreen():
    red = (200,0,0)
    green = (0,200,0)
    bright_red = (255,0,0)
    bright_green = (0,255,0)

    intro = True
    while intro:
        for event in pygame.event.get():
            #print(event)
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()

        window.fill((255,255,255))
        largeText = pygame.font.Font('BLOODY.ttf',100)
        TextSurf, TextRect = text_objects("You Have Died Fool", largeText)
        TextRect.center = ((800/2), (800/2))
        window.blit(TextSurf, TextRect)
        button("Start Game",150,450,100,50,green,bright_green,game_loop)

# make the square brighter if collideded with the buttons
        mouse = pygame.mouse.get_pos()
        if 150+120 > mouse[0] > 150 and 450+50 > mouse[1] > 450:
            pygame.draw.rect(window, bright_green,(150,450,120,50))
        else:
            pygame.draw.rect(window, green,(150,450,120,50))
        if 550+110 > mouse[0] > 550 and 450+50 > mouse[1] > 450:
            pygame.draw.rect(window, bright_red,(550,450,110,50))
        else:
            pygame.draw.rect(window, red,(550,450,110,50))
# ---------------------------------------------------------------------

        smallText = pygame.font.Font("freesansbold.ttf",20)
        textSurf, textRect = text_objects("Start Game", smallText)
        textRect.center = ( (150+(120/2)), (450+(50/2)) )
        window.blit(textSurf, textRect)

        smallText = pygame.font.Font("freesansbold.ttf",20)
        textSurf, textRect = text_objects("Quit Game", smallText)
        textRect.center = ( (150+(910/2)), (450+(50/2)) )
        window.blit(textSurf, textRect)

        pygame.display.update()
        clock.tick(15)

#----------------------------------------------------------

and on my main loop I said if my playerman health is > -1 it should load the end screen

            if playerman.health < -5:
                endScreen()

```


texts: How can I move objects in a cyclic loop?

texts:
I have number of objects I want to move them up and forward then when the last one each time in the array get to the end position move this object to the start of the array and to the start position the original start position of the first object.

The idea is to make the objects cyclic on place. Not to move all the objects but to cyclic them up and forward.

I tried this but it's totally wrong. It's moving all the objects as a group to another place and the last one return to the first position big mess.

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

public class MoveObjects : MonoBehaviour
{
    public float speed = 1f;

    private Vector3[] startPos;
    private Vector3[] endPos;
    private Vector3[] currentPos;
    private GameObject[] objectstoMove;

    // Use this for initialization
    public void Init()
    {
        objectstoMove = GameObject.FindGameObjectsWithTag("Stair");
        startPos = new Vector3[objectstoMove.Length];
        endPos = new Vector3[objectstoMove.Length];
        currentPos = new Vector3[objectstoMove.Length];

        for(int i = 0; i < objectstoMove.Length; i++)
        {
            startPos[i] = objectstoMove[i].transform.position;
            endPos[i] = new Vector3(objectstoMove[i].transform.position.x + 50, objectstoMove[i].transform.position.y + 50, 0);
        }
    }

    // Update is called once per frame
    void Update()
    {
        if (objectstoMove != null)
        {
            for(int i = 0; i < objectstoMove.Length; i++)
            {
                currentPos[i] = objectstoMove[i].transform.position;
                objectstoMove[i].transform.Translate(1, 1, speed * Time.deltaTime);

                if(currentPos[i].x >= endPos[i].x && currentPos[i].y >= endPos[i].y)
                {
                    SetTransform(objectstoMove[objectstoMove.Length-1]);
                }
            }
        }
    }

    void SetTransform(GameObject n)
    {
        n.transform.position = startPos[0];
    }
}

Example screenshot:

Each cube should move up and forward following the one above it.
The top one when it's reaching to the end position it should move back to the first cube start position. Then the next top cube when reaching the end position it should move to the original first cube start position !

The idea is to simulate some kind of stairs escalator.
So the cubes should move in cyclic. The whole cubes not should change position but they should cyclic.

I tried also this for testing:
But not working at all.

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

public class MovingTest : MonoBehaviour
{
    public List<Transform> objectstomove = new List<Transform>();
    public float speed = 1;
    public Vector3 position1;
    public Vector3 position2 = new Vector3(2, 2, 2);

    private Transform lastobj;

    // Use this for initialization
    void Start ()
    {
        position1 = objectstomove[0].position;
        lastobj = objectstomove[objectstomove.Count - 1];
    }

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

        for (int i = 0; i < objectstomove.Count; i ++)
        {
            objectstomove[i].position = Vector3.MoveTowards(objectstomove[i].position,
                                                 position2, speed * Time.deltaTime);
        }

        if (lastobj.position.x == 2)
        {

            lastobj.position = position1;
            objectstomove.Remove(lastobj);
            objectstomove.Insert(0, lastobj);
            lastobj = objectstomove[objectstomove.Count - 1];

            for (int i = 0; i < objectstomove.Count; i++)
            {
                objectstomove[i].position = Vector3.MoveTowards(objectstomove[i].position,
                                                     position2, speed * Time.deltaTime);
            }
        }
    }
}


texts: Drawing a one pixel wide line in 3D space

texts:
I'd like to draw a line in 3D space that is always exactly one pixel wide on screen, no matter how far away from the camera it is. (And the same for single points too).

Any hints on how I could do that?


texts: Box2D LibGDX Body.getPosition() and Body.getWorldCenter() problems

texts:
I have a problem with my game in Java with Box2D and LibGDX

I found out that when I use

body.getPosition() it is only half of that of body.getWorldCenter().

The problem here is for me that I use Joints also, which forces me into using body.getPosition().

But now my body gets drawn on the position of body.getWorldCenter().

which makes it so it looks like that

http://i.imgur.com/Q910eFs.png

Here is the source code where I create the Car Body

}

public static Body createCarBody(Vector2 position, float sizeX, float sizeY, float density, float friction, float restitution, float linearDamping, float angularDamping)
{

    System.out.println("position createCarBody " + position);
    Body body = Physics.createBody(createBodyDef(position, linearDamping, angularDamping));
    body.createFixture(createFixtureDefCar(createPolygonShape(sizeX, sizeY,position), density, friction, restitution));

    return body;
}

public static FixtureDef createFixtureDefCar(PolygonShape shape, float density, float friction, float restitution)
{
    FixtureDef fixtureDef = new FixtureDef();
    fixtureDef.shape = shape;
    fixtureDef.density = density;
    fixtureDef.friction = friction;
    fixtureDef.restitution = restitution;
    return fixtureDef;

}

public static PolygonShape createPolygonShape(float sizeX, float sizeY, Vector2 position)
{

    PolygonShape polygonShape = new PolygonShape();
    polygonShape.setAsBox(sizeY/2 , sizeX/2, position,0);

    System.out.println("position polygonshape " + position);

    return polygonShape;
}

I use the createCarBody method in my car class where it is given a Position Vector of (30,30) ( first car ) and (40,40) second car

If I print body.getWorldCenter() i get (60,60) and (80,80 )


texts:
I'm wondering how to achieve a neon-light type effect. For example, in Pac-Man Chamipnship Edition:

Or in Geometry Wars:

Is that a Bloom Effect? Or what techniques would I have to look for?


texts: Player doesn't move smoothly, when trying to follow position between cursor and player

texts:
When my player moves, moving the camera looks like the camera is teleporting to the player, and then after loading teleporting again. I want to make it move smoothly.

When the camera is following the player position, it is moving smoothly.

Camera following code:

private void Update()
{
    Vector3 position = GetFollowingPoint();
    position = new Vector3(
        Mathf.Clamp(position.x,
                    Bounds.bounds.min.x + Camera.orthographicSize * Screen.width / Screen.height,
                    Bounds.bounds.max.x - Camera.orthographicSize * Screen.width / Screen.height),
        Mathf.Clamp(position.y,
                    Bounds.bounds.min.y + Camera.orthographicSize,
                    Bounds.bounds.max.y - Camera.orthographicSize),
                    transform.position.z);

    transform.position = position;
}

GetFollowingPoint():

return Player.transform.position + (cursor.transform.position - Player.transform.position) / 3;

Player movement: rigidbody.velocity = Vector in FixedUpdate(), Input with Input.GetKey() and Vector += Vector2.up/down/left/right.

Interpolation in Rigidbody set to Interpolate.


texts: Why are my geometry-shader-generated billboards not showing up given the following code?

texts:
My program is a rain particle system. After processing a list of positions of rain particles, I passed them to the geometry shader for generating a billboard for each position.

If I use a simple method to generate the billboard, (it is a rectangle, not really a billboard), it work well and I can see them in the render target. This simple method proves that the input positions for the geometry shader are right.  The below HLSL source implement this simple billboard.

[maxvertexcount(4)]
void GSMAIN( point GS_INPUT input[1], inout TriangleStream<PS_INPUT> SpriteStream )
{
    //Transform to view space
    float4 viewposition = mul(float4(input[0].position, 1.0f), WorldViewMatrix);

    // Emit two new triangles
    for (int i = 0; i < 4; i++)
    {
        // Transform to clip space
        //g_positions is an array of four deltal vectors in the form: (-scale, +scale, 0, 0)..
        output.position = mul(viewposition + g_positions[i], ProjMatrix);
        output.texcoords = g_texcoords[i];
        output.color = color;

        SpriteStream.Append(output);
    }
    SpriteStream.RestartStrip();
}

But if I changed to create a real billboard, it shows nothing. My method is based the velocity vector of rain drop. The implementation is in below:

[maxvertexcount(4)]
void GSMAIN( point GS_INPUT input[1], inout TriangleStream<PS_INPUT> SpriteStream )
{
    PS_INPUT output;

    //Velocity of raindrop = Rate + original velocity
    //The billboard will stays along this vector
    float3 velocityVector =  input[0].speed.xyz/FrameRate + TotalVelocity;

    //ViewPosition: the position of camera
    GenRainSpriteVertices(input[0].position, velocityVector, ViewPosition, pos);

    for(int i = 0; i < 4; i++)
    {
        output.position = mul(float4(pos[i], 1.0f), WorldViewProjMatrix);
        output.texcoords = g_texcoords[0];
        output.color = color;
        SpriteStream.Append(output);
    }
}

///////////////////////////////////////////////////
//The function generating billboard from
//1. Point Position
//2. Eye Position
//3. Velocity vector
///////////////////////////////////////////////////
void GenRainSpriteVertices(float3 worldPos, float3 velVec, float3 eyePos, out float3           outPos[4])
{
    float height = g_SpriteSize / 2.0;
    float width = height / 10.0;

    velVec = normalize(velVec);
    float3 eyeVec = eyePos - worldPos;
    float3 eyeOnVelVecPlane = eyePos - ((dot(eyeVec, velVec)) * velVec);
    float3 projectedEyeVec = eyeOnVelVecPlane - worldPos;
    float3 sideVec = normalize(cross(projectedEyeVec, velVec));

    outPos[0] = worldPos - (sideVec * 0.5*width);
    outPos[1] = outPos[0] + (sideVec * width);
    outPos[2] = outPos[0] + (velVec * height);
    outPos[3] = outPos[2] + (sideVec * width);
}

I tried to use Nsight and Graphics Diagnostics in VS2012 to debug, and all of them show that the geometry shader generated the right vertices. The following pictures are from Visual Studio and Nsight, which present the result after the geometry shader finished its job.

And the next result is from Nsight:

For some reason, the generated vertices in the geometry shader are discarded in the pixel shader. Why might this be?


texts: Textures not displaying. Problem with fragment and vertex shaders

texts:
Hi i have newbe question. I am sending to gpu textures unit and they dont display.
This is simple version of my fragment and vertexshader. (More complicated version also dont work with other textures than DDS but maybe simpler version will tell you what newbe mistake i made)

for (unsigned int i = 0; i < textures.size(); i++){
    glActiveTexture(GL_TEXTURE0+i);
    glBindTexture(GL_TEXTURE_2D, Textures[i]);
    // Set our "myTextureSampler" sampler to user Texture Unit 0
    glUniform1i(TextureID, i);
}

This is my simple fragmentshader

#version 330 core

// Interpolated values from the vertex shaders
in vec2 UV;

// Ouput data
out vec3 color;

// Values that stay constant for the whole mesh.
uniform sampler2D myTextureSampler;

void main(){

    // Output color = color of the texture at the specified UV
    color = texture2D( myTextureSampler, UV ).rgb;
}

This is my simple vertexshader

#version 330 core

// Input vertex data, different for all executions of this shader.
layout(location = 0) in vec3 vertexPosition_modelspace;
layout(location = 1) in vec2 vertexUV;

// Output data ; will be interpolated for each fragment.
out vec2 UV;

// Values that stay constant for the whole mesh.
uniform mat4 MVP;

void main(){

    // Output position of the vertex, in clip space : MVP * position
    gl_Position =  MVP * vec4(vertexPosition_modelspace,1);

    // UV of the vertex. No special space for this one.
    UV = vertexUV;
}

EDIT this corrected version but still something dont work. If i had DDS everything was working OK but jpg textures all time i have problems.

EDIT i have correct number of textures but they looks diffrent than original


texts: Missing colors in Collada export from Blender

texts:
I've noticed something strange in a Collada DAE export from Blender. I've assigned Diffuse BDSF colors to 4 faces of a cube as shown here:

http://www.4shared.com/photo/_hM04zywba/blendcube.html

It renders fine in Blender but after exporting to the following DAE file the diffuse and ambient color's RGB values stay the same for all materials. Shouldn't each material block in DAE have different values? Do I need to do something more in Blender to save the material info?

http://www.4shared.com/file/KdzuIwWGce/matcube.html


texts: LibGDX limit the PerspectiveCamera for a FPS view

texts:
I'm using LibGDX and I'm trying to implement a FPS camera into my game. I'm not using the FirstPersonCameraController for multiple reasons:

I don't want to touch to roll (only yaw and pitch), with this camera when looking on sides the horizon goes up and down like waves (meaning that the roll is changing)
I don't want dragging, I want the camera to always move with the mouse.
I want movements to stay consistent whatever the player is looking at. I don't want it to go slower even if he looks at the ground.

So I've come up with this which does pretty much what I want:

    @Override
    public boolean mouseMoved(int screenX, int screenY)
    {
        float deltaX = (mousePos.x - screenX) * sensitivity;
        float deltaY = (mousePos.y - screenY) * -sensitivity;

        Vector3 tmpAxis = game.getGame().getPool().obtain(Vector3.class);

        game.getCamera().rotate(Vector3.Y, deltaX);
        tmpAxis.set(game.getCamera().direction.z, 0, -game.getCamera().direction.x);

        game.getCamera().rotate(tmpAxis, deltaY);
        //if(game.getCamera().up.y < 0)
        //  game.getCamera().up.y = 0;

        mousePos.set(screenX, screenY, 0);
        game.getGame().getPool().free(tmpAxis);
        return true;
    }

However, I have an issue described by the commented lines. When the camera goes to low or too high (when the y value of the up vector become negative), the rotation is reversed and the rotation starts to make it come back. In pratice, it just flickers a lot and when I try to go back, I have 1/2 chance of going back normally, and 1/2 chance of looking backward with my camera reversed (if the up vector is negative).

So naturally, what I want is to lock the movement so It can never look pass his feets or pass the sky. Locking the up vector is easy, I just have to prevent it from going negative but I need to replace the direction vector also. However, I don't know how to "replace" the direction vector. I search on google for how to set the camera rotation or just how to get it and didn't found anything convincing.

I've just tried also adding game.getCamera().direction.y = -1f; to my commented if to make it look down when getting past the point I don't want it to get past. However, I found out the direction vector isn't normalized and that's really confusing.


texts: Best Way To Develop Robust Cross-Platform Application?

texts:
Possible Duplicate:
  Any tips for creating cross-platform games?

Windows C programmer here (going back to 1992 and Windows95 back when it was called Windows93). Can function in C++, but mostly still a C programmer.

Looking to build a cross-platform casual game. Very numbers heavy with only a few artistic embellishments and animations, so perhaps a development environment for business apps might be the best option. Or an easy-to-use 2D game dev platform.

Target platforms: Windows, Mac, MS Tablet, iPhone, iPad, Android.

I currently develop on Windows with Visual Studio 2012, but we could spend up to $50K on hardware/software/middleware if necessary. Not very competent getting open-source software working. Would rather pay the money and jump right into app development.

Recommendations?


texts: LibGDX HexagonalTiledMapRenderer wrong stagger index?

texts:
Im using Tiled map editor, Hexagonal(staggered) map, libgdx version 1.9.9

If I set staggeredIndex = even in tiled map editor, libgdx seems to render odd

If I set it to odd in map editor, libgdx renders even

Screen Shots:

Here's the code:

@Override
public void create () {
    map = new TmxMapLoader().load("mapa.tmx");
    cam = new OrthographicCamera(Gdx.graphics.getWidth(),Gdx.graphics.getHeight());
    mapRenderer = new HexagonalTiledMapRenderer(map);

}

@Override
public void render () {
    Gdx.gl.glClearColor(0, 0, 0, 1);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

    cam.update();
    mapRenderer.setView(cam);
    mapRenderer.render();
}


texts: Unity - Game not running on android 8 and 9

texts:
Game  is crashing with message "app has stoped" when i am opening it (it doesnt show splash screen) ,  everything is fine when I am creating new project with same unity version, build, player and sdk settings . No errors in unity and log from logcat. Any ideas??
Link to logcat log https://pastebin.com/yzvkB3Jv  (Game name is iPenkim)


texts:
I need to make not repeating background for platformer. I can't find any description of implementation and I developed algorithm but I'm not sure that it's right.

I can't load one big texture per level, because many devices don't support textures more than 2048x2048 pixels and my levels require 4096 pixels at least on the one side. Therefore I have to cut big texture into smalls(512x512, 1024x1024), load them using separate thread and render. Picture shows it:

Green rectangle is screen(for example Nexus S with display 800x480)

Problems:

In case 2 layers I have to keep in memory 4 big textures.
I have to constantly load and unload big textures.
Additional thread.

If it's not problems then ok :) But it seems that I'm doing something wrong.


texts: How to implement "Flick" gesture for throwing an object in the 2D realm

texts:
I am trying to implement a FLICK gesture for throwing a ball from point A to point B on the iPhone.  This is my current plan....

Using touchesBegan and touchesEnd I can find the direction I need to move the ball, and with a small counter, I can impact a certain velocity on the object.

My question is simple...

Is there a better way to do this ?

I am unaware of the physics engine and how I could use it in this scenario. Any good suggestion will help !


texts: How to know when to use UIViews and other Quartz2d features and when to use OpenGL ES?

texts:
When starting a new 2d project on the iOS framework, it seems pretty to start creating UIView subclasses and having fun with Quartz to create very quick prototypes, but I am guessing there will be times where it will be impractical(or impossible) to use such powerful(and wasteful compared to openGL ES) abstractions.

I know a couple dozen subviews work allright, but there must be a point where having more than X is just impossible to keep a good frame rate.

How do you know if it would be a good idea to drop the UIKit and start doing some more powerful stuff on openGL?


texts: Draw character silhouette when not visible

texts:
I have a mesh representing my character. I want to give it a partially transparent greyish silhouette when other objects are blocking it from view of the camera.

I'm using Ogre3D, and GLSL as a shading language, but this is a pretty technology/language agnostic question.


texts:
I am building a game for which I want to simulate certain rigid body dynamics.Could someone suggest me some engines which work on Ubuntu.Also as I have dont have much time to implement it,so it would be helpful if it is a easy one to work with.
I have some across one namely ODE.Am looking for others which would help me simulate collisions and angular movements.


texts: What are reasons for input polling vs. input events?

texts:
I noticed people use both - but is there any empirical evidence when it's better to use one over the other?

This is related but not quite a 'why use either' or even 'why use both': Polling vs event driven input


texts: Altering Physics Property of a Shape in Unity

texts: I want to create say 4 blocks, and each block will dictate how e.g. the bounciness of an object landing on it will behave. So if the block is made of sand, I don't want bounciness, if the block is wood I want it to bounce, if it's ice block i want it to bounce a bit and then slide for X amount of time. How can I adjust the physics of the object landing on that block based on what block it is?


texts: How often to update a Game Client about the World?

texts:
Using socket.io, I have a communication similar to that of other MMORPGs, a steady connection with messages.

In my design so far, the client sends the player's position and animation frame with every update frame. When the server gets that message, it broadcasts it to all the clients, which will then move the graphic accordingly.

Would it be a better idea to 'collect' these and broadcast them, say, once in 1/10 of a second?

Also, should the client send many different messages (exp gained, clicked on item) as soon as they occur or rather just one collected? The first would be implemented easier.


texts:
I am planning to implement in my game a very big map. I won't be showing all map at once but rather only a selected part of it. Additionally, I would need to connect hexes into bigger pieces (provinces) and show them altogether.

I was thinking of using a hex map. Can you recommend any manual relating to working on coordinates on hex map? I am looking for a good way to store the hex positions on map so that I can easily find nearby hexes and do not have to load all the map at once.

Maybe you may also recommend some reliable alternatives to hex maps?

I am limited to 2D.


texts:
I have a tile based game. Each tile texture is loaded and then I draw each one next to the other, forming a continuous background. I actually followed this tutorial for the xml files.

http://www.xnadevelopment.com/tutorials/looksleveltome/looksleveltome.shtml

The sources of the textures are 50x50.

However, it works only it the scale is 1 (or lower), if the scale is greater

The results:

Larger size (Zoomed or 100 pixel in xml file)

We can see there are lines between the tiles, which are not in the texture. It's actually not so bad here, but in my game tileset, that's what it does:

The same effect is present whether I increase the tile size in the xml file, change the scale when drawing or use my camera to zoom.

//zoom code
public Matrix GetTransformation()
{
    return
       Matrix.CreateTranslation(new Vector3(-_pos.X, -_pos.Y, 0)) *
       Matrix.CreateRotationZ(Rotation) *
       Matrix.CreateScale(new Vector3(Zoom, Zoom, 1)) *
       Matrix.CreateTranslation(new Vector3(_device.Viewport.Width * 0.5f, _device.Viewport.Height * 0.5f, 0));
}

//draw
_spriteBatch.Begin(SpriteSortMode.Immediate,
  BlendState.AlphaBlend, null, null, null, null,
  _camera.GetTransformation());

//for each tile
theSpriteBatch.Draw(mSpriteTexture, Position, Source,
  Color.Lerp(Color.White, Color.Transparent, mAlphaValue),
  mRotation, new Vector2(mSource.Width / 2, mSource.Height / 2),
  Scale, SpriteEffects.None, mDepth);

Is there a reason for this? A way to fix it to have a continuous texture when zoomed?


texts: Rotation, further I go from 0:0, the further the object positions around the origin while rotating

texts:
For some reason I am having the issue where the following code:

 global.spriteBatch.Draw(obj.sprite, obj.getPosition(), null, Color.White, obj.rotation, obj.center, 2f, SpriteEffects.None, 1);

causes the object to rotate around the origin in such a way, as though there is an offset to the position relative to its location. The calculation for the center it correct and this happens even if I set the pivot to be the location of the object. The further I get from 0:0 the larger the radius or rotation. I am not sure what is going on here because given the following tutorial

http://www.riemers.net/eng/Tutorials/XNA/Csharp/Series2D/Rotation.php

I have done the code setup correctly. Any ideas? Any help is greatly appreciated!!!


texts:
How can I check if a players held item is of a specific item type - for example an axe. (can be iron axe, gold axe, wooden axe, etc.)?

Or do I have to do multiple if statements to have this done?

@EventHandler(priority= EventPriority.HIGH)
    public void onInteract(PlayerInteractEvent event){
        Player p = event.getPlayer();
        ItemStack heldItem = p.getInventory().getItemInMainHand();

        if(heldItem.getType() == Material.DIAMOND_AXE){ //I dont want to do multiple if statements for multiple type of Axes
            //...
        } //other if statement for Material.WOODEN_AXE etc.
    }


texts: Godot: Using an argument's methods as kwarg

texts:
I downloaded and tried out the Rakugo addon out of the box and I ran into this problem:

'Parser Error: Identifier 'node' is not declared in current scope'

If you look you can see that node is an argument variable and the kwarg is meant to be a method (name) of that arg.

It seems that gdscript does not allow this.

My question is, 'how do I fix this or work around it?'


texts: Efficient visualization of a large voxelized volume

texts:
Lets consider a large voxelized volume stored in an oct-tree or any other convenient structure. This volume represents, for instance, a landscape, where each block is either empty (air), or it has an specific material that will be later used to apply a texture.
Voxels that are next to each other represent connected sections of the surface.

What I need is an algorithm to generate a mesh from this voxels that represents the volume, with the following caracteristics:

All the "holes" in the voxelized volume are correct.
All the connections are correct, i.e. seamless.
The surface appears smooth.

In a broad sense, I want to somehow preserve the surface topology, meaning that connected sections remain connected in the resulting mesh and that the surface has a curvature that responds to the voxels topology. Imagine trying to render the Minecraft world but getting the mountain ladders to be smooth instead of blocky.


texts:
No matter how thick the wall is, the player will glitch through. I've tried changing the settings on the rigidbody but nothing have worked. The walls fits together almost perfectly. Why is this happening?

I already searched a lot and also found a lot of questions regarding the same problem at "Unity Answers" - not a single one of them gets answered. I dont know why, it seems theyr community is almost dead.


texts: Need to count a number of programmatically created objects in separate script

texts:
I have a game that creates and places a random number of "pickups" on a plane at random places.

I then have a script on the "Player" game object that uses OnTriggerEnter to tell when an item has been "picked up" and compares a count (the score) to the number of objects that are created:

void OnTriggerEnter(Collider other)
{

    // Get all game objects with the Tag "Pickup"

    if (other.gameObject.CompareTag ("Pickup")) {

        // Deactivate objects that are touched/collected
        other.gameObject.SetActive (false);

        // add to count
        count++;

        scoreText.text = "Score: " + count;

        //TODO: fix this statement; pickupCount is always 0 here, why?

        if(count >= pickupCount){
            winText.text = "You Win!";
        }

    }

}

The problem I am facing is that during building this worked fine, I built the project and it outputted "You Win!" after picking up 1 "pickup", I found out this is because for some reason the value of pickupCount is now always 0.

pickupCount =  GameObject.FindGameObjectsWithTag("Pickup").Length;

My guess is that because the Playerscript checks at Start() and the SpawnScript creates at Start() that the reason the number is always 0 is because at the time of checking there are in fact no "pickups" created. My question is then, how do I check for the total number of these pickups without doing it in an update function?

SIDE NOTE

I know I could just change the OnTriggerEnter() function to be something like this:

void OnTriggerEnter(Collider other)
{

    // Get all game objects with the Tag "Pickup"

    if (other.gameObject.CompareTag ("Pickup")) {

        // Deactivate objects that are touched/collected
        other.gameObject.SetActive (false);

        // check number of pickups left
        pickupCount =  GameObject.FindGameObjectsWithTag("Pickup").Length;

        // add to count to show the score
        count++;

        scoreText.text = "Score: " + count;

        if(pickupCount <= 0){
            winText.text = "You Win!";
        }

    }
}

But it is more a case of curiosity now more than anything. Is what I am asking even possible?


texts: Identify when Unity Button Enters Pressed State

texts:
I am trying to create a UI Button Prefab with a text child element that I would like to use all over my application. Its intended behavior is very simple:

Its size would be dependent on the text's width (this has been achieved using content size fitter and a horizontal layout group).
Its states would be done using sprite swap (this had also been done partly)

The problem is that the pressed state uses an image on which the button is visually pressed (its top moves downward a few pixels). This is a nice effect and the image works great, however, I cannot make the text move in synchrony with the image to sell the downward movement.
My way of thinking was to use an initial padding of 4 at the bottom in the horizontal layout group (to move the text upward) then change it to 2 when the button enters a pressed state. Something like this:
using UnityEngine.UI;

public class ButtonController : MonoBehaviour {
    public Button buttonComponent;
    public HorizontalLayoutGroup buttonLayout;

    // Update is called once per frame
    void Update() {
        RectOffset tempPadding = new RectOffset(
        buttonLayout.padding.left,
        buttonLayout.padding.right,
        buttonLayout.padding.top,
        buttonLayout.padding.bottom);

       if (buttonComponent.isPressed) { //This does not work OFC!
        tempPadding.bottom = 2;
       } else {
           tempPadding.bottom = 4;
       }

       buttonLayout.padding = tempPadding;
    }
}

The problem is that I cannot seem to identify when the button enters said pressed state, which seem like a simple enough problem yet I cannot find an answer to it. I've looked all over the internet but couldn't find anything useful.


texts: How to get NPC to Find and Follow Path to other NPC?

texts:
Problem:

I am using Skyrim Creation Kit to create a very simple mod. I want the mod to make one NPC follow another NPC. My first problem is that I am not really 100% sure where to start. The second problem is which functions I should use. I have been reading the documentation at www.creationkit.com. In other words:

LOOP: {
  // move Bob to Mike's current position with speed of 0.5
  (npc_Bob.moveToPosition( npc_Mike.getPos(), 0.5 )
} // end loop

My Attempt:

I tried making a quest but to no avail. So then I made 2 custom actors (member and leader) and I put this script in member:

Scriptname NpcFollowNpc extends ObjectReference
//***put a loop once you get this part working
// moves member to leader with speed of 0.5
member.PathToReference(leader, 0.5)

but it didn't compile. I don't really know if this is the right way to implement what I want. I know how to code and make algorithms and a bunch of that computer science stuff, but I don't know how to move the actor member to the location of actor leader in Skyrim and loop it while the actor leader is alive.

Any ideas how I could go about doing this? thanks for any help/feedback!


texts: So this is an easy question. I need to implement gravity in my game but where I'm stuck is what variables do I need in my Entity object for the calculations and a good algorithm that I can use for gravity and collision. The main reason why I'm stuck here is not just I'm implementing this into a huge program that handles the different states, windows, buttons and plenty of other stuff but all I got it the x, y, width, and height for my Entity and every time I try and calculate collision if the object hits a wall it stops, and I have no acceleration variables as I don't know how to use a algorithm with them so I'm guessing as I go and so my whole program is a mess. To make it clear of what I need someone to help me with is can you show me an example of how I would use my x, y, height, and width and move it around, use jumping, use gravity. I never really saw any of this so if someone knows how to do this, and or you have done this is a game before which you could show me what you did that would be great. I'm new to this so even a link is good. Thanks in advance!


texts:
I am making an RTS game, and like most RTSs, you can see what's going on in a part of a map only if you have a unit over there.

I have few ideas how to accomplish this, but there are problems with them.

Problems are:

Algorithm must be efficient.
I need to notify players (over network), when an enemy comes into sight.
How do I account for obstacles obstructing sight (such as cliffs).

Naïve approach would be like this:

// pseudocode
func calculate_visibility:
   vector<Bitfield> visible;

   for all units on map:
        let unit = enumerated unit

        for all human players:
             let player = enumerated player

             for all units of player:
                  let player_unit = enumerated unit

                  if player_unit sees unit
                       visible[unit.id][player.id] = true
                       process next player

And then run this calculation each frame, compare results with previous frame and send out events, like “enemy unit detected”.

I did some benchmarking, and using approach like this may take up to 2/3 of a frame, which is unacceptable.

I figured out a better way to calculate which units are visible. This approach is to use a visibility map.

Subdivide the map into N×M cells.
Each cell is marked by IDs of players that can see the cell.
To determine which players can see an unit, I need only to check cells that contain given unit.

However, I don't know how to fill the map in the first place. I could iterate through all units and use a circle-drawing algorithm.

But I'll have to redraw the visibility map every frame, so this doesn't look much more efficient than the first approach. Unless I update it at a lower rate, but then there's a problem with fast-moving units.

And how do I detect when unit comes in player's sight, except than iterating through every unit and comparing with previous frame?

How is this done in modern RTS, such as StarCraft 2?


texts:
Ive been looking at tutorials and trying to figure out how to do basic ray-picking. But I'm stuck at figuring out what space to do the distance calculations in. What space does glm::unproject() lead to exactly?

This is what I'm doing:

first I get the mouse unprojected, like so

//mouse ray start
vec3 m_uproj = glm::unProject(
    vec3(mouse_xy .x*glutGet(GLUT_WINDOW_WIDTH), mouse_xy .y*glutGet(GLUT_WINDOW_HEIGHT),0.0f),
    workshop.access_gui()->view_mat(),
    workshop.access_gui()->proj_mat(),
    glm::ivec4(0, 0, glutGet(GLUT_WINDOW_WIDTH), glutGet(GLUT_WINDOW_HEIGHT)));

//end of ray
vec3 m_uproj2 = glm::unProject(
    vec3(mouse_xy.x*glutGet(GLUT_WINDOW_WIDTH), mouse_xy.y*glutGet(GLUT_WINDOW_HEIGHT), 1.0f),
    workshop.access_gui()->view_mat(),
    workshop.access_gui()->proj_mat(),
    ivec4(0, 0, glutGet(GLUT_WINDOW_WIDTH), glutGet(GLUT_WINDOW_HEIGHT)));

Then I find its direction, mray, like so

vec3 mouse_ray = normalize(m_uproj2 - m_uproj); //get mray direction

And Im expecting to find the closest point to some_object by using this calculation:

vec3 closest_point = mouse_ray * glm::dot(locations[i], mouse_ray); //closest point;

But locations seems to be in the wrong space? Or am I thinking about this the wrong way? Ive been looking around, but I cant find anywhere that explains just this part that I must be misunderstanding.

the idea is to compare the distance between closest point and locations[i], but the results are incorrect. Im getting something like this:

Where it should be red only if the cursor is over the square.

What space does glm::unproj() put my ray in anyway? And in what space should I put the objects that I want to pick/highlight?


texts: XNA - Strange Texture Rendering Issue Using XNA BasicEffect

texts:
I have been reading and working through Riemers 3D XNA tutorials to expand my knowledge of XNA from 2D into 3D. Unfortunately I am having rendering issues that I am unable to solve and I need a point in the right direction.

I am not expecting the Models to look identical to Blender but there is some serious discoloring from the texture files once rendering through XNA. The Character model is using completely incorrect colors (Red where Grey should be) and the Cube is rendering a strange pattern where a flat color should be drawn.

My sampling mode is set to PointClamp.

The Character model that I created has a 32 by 32 pixel texture that has been UV mapped to the model in blender. The model was then exported to .FBX. For the Cube Model a 64 by 64 pixel texture is used.

foreach (ModelMesh mesh in samuraiModel.Meshes)
{
    foreach (BasicEffect effect in mesh.Effects)
    {
        effect.Projection = Projection;
        effect.View = View;
        effect.World = World;
    }
    mesh.Draw();
}

Does this look like it is caused by a mistake I made while UV Mapping or Creating Materials in Blender?
Is this a problem with using the default XNA BasicEffect?
Or something completely different that i have not considered?

Thank You!


texts: Gamma Space and Linear Space with Shader

texts:
I am using Unity and I can choose between two color space mode in the settings: Gamma or Linear Space.

I am trying to build a Custom Lighting Surface shader but I am facing some problems with those Color Space. Because the render is not the same depending of the Color Space.

If I render the lightDir, Normal or viewDir I can see that they are different depending of the Color Space I use.

I made some test and the result I have in Linear Space is great but how can I obtain the same result in Gamma Space ?
Are there some transformations ? On what component should I apply those transformations ?

Thank you very much !


texts: Is it possible to be a game artist and not work on character/creature animation?

texts: If I don't want to develop and animate living characters (animals, humans, robots, et cetera) for games, but I do want to develop/animate objects (TVs, phones, cars, et cetera) or levels... is it possible to have a career as an artist in the industry?


texts: How is a 3d perlin noise function used to generate terrain?

texts: I can wrap my head around using a 2d perlin noise function to generate the height value but I don't understand why a 3d perlin noise function would be used. In Notch's blog, http://notch.tumblr.com/post/3746989361/terrain-generation-part-1, he mentioned using a 3d perlin noise function for the terrain generation on Minecraft. Does anyone know how that would be done and why it would be useful? If you are passing x,y, and z values doesn't that imply you already have the height?


texts: Unity: Dimensions of color surface does not match dimensions of depth surface

texts:
I am receiving the error, "Dimensions of color surface does not match dimensions of depth surface" whenever I attempt to use my screenshot code, without any callstack or anything further insight of what I am doing wrong.

I have a separate camera from my main camera, whose purpose is to take screenshots at different angles.  Hierarchy as such:

The main camera captures the 3D scene just like a normal main camera would, including post-processing components.  No HDR or MSAA.

The GUI camera captures just the UI layer.  Nothing enabled except MSAA.
The canvas and image are simply a watermark, rendered by the GUI camera.

I point both the main camera and GUI camera to the same target render texture.  When ready to take a screenshot, I enable the camera components, thus Unity takes over and tells them to render the frame.  In the OnRenderImage callback, I disable the camera so it can be used again, I remove the render texture I previously assigned, extract the pixels, and save it as a PNG.

In a separate test, this all seems to work as intended.  No error messages.  However, when playing the full game, suddenly I receive the dimensions errors upon each screenshot.

I have read that RenderTexture.IsCreated will test if the render texture is still available.  Supposed, it will be set to false due to a large variety of events, such as window changes.  I have made it impossible to even get the reference to the render texture without it checking if the IsCreated bool is true.  I have also tested if the render texture matches its Descriptor property, out of paranoia.  All of these checks succeed.

I don't know what to look at next.

What is SUPER strange is I have a GIF generator, using quite similar code, that's much more complicated, and it does not suffer from this problem.

Has anyone dealt with this error before?  Any hints at all?


texts: Auto-generate optimal direction for Unity Raycast with specifications

texts:
How can I have a Physics.Raycast auto-generate a direction for itself to try to hit a given target through a restricted window of space?

[Update]

After much work, my problem has slightly morphed into one about mesh colliders: given a (convex) mesh collider, how can I detect all of the points intersecting with the collider? Or, if this can be done easily, can I get one Vector3 per object that is within the mesh collider?

[/Update]

This is kind of a long question, so I'll try to explain it the best I can:

I have 3 GameObjects: a source, a target, and a "window". This window sits between the source and target.
I want the source to make a raycast that points in the direction of the target (not necessarily it's transform.position, just a direction that will make it hit the target) and this raycast must pass through (collide and continue through) the window GameObject
I would like to automatically generate this direction for the raycast to follow such that #2 happens
I would like this algorithm to also recognize if the above is not possible
As an added item, I would like this raycast to pass through (collide and continue through) any objects that may be in it's way between it and the window

Here's an image describing my issue in more detail:

How can I accomplish this?

Thank you for your help in advanced!


texts:
I'm using Canvas to create polygons like this:

http://bl.ocks.org/mbostock/6675193

I want each of those polygons to represent a clickable province. How do I know which province is clicked when the user clicks on something? I have a list of vertices (thousands) but I feel like each time looking for the closest vertex is too slow (I think I might be wrong). What's a fast way to do it? Thanks.


texts: HLSL: Using instance float input to select texture index, possible?

texts:
I'm writing a game for the xbox360 using XNA.
I would like to draw several models with a single DrawInstancedPrimitives call. Each model will use a different texture.

To do this, I would like to create a sampler array, and select which sampler to use in the array from a value passed into the shader from the instance vertex buffer.

So the shader code might look like:

void InstancingVertexShader(..., in float4x4 data : TEXCOORD0)
{
    output.TextureIndex = data._m00
}

void InstancingPixelShader(...)
{
    color = tex2Dlod(samplers[input.TextureIndex]);
}

Before I start trying to implement that, my question is:

Is it possible to do that, or will the HLSL complain?

Are there any cons to this method that I should know about?


texts: Rendering Tilemap Tile Layer Side by Side for Infinite/Endless Runner Game

texts:
I was strugeling this for days how to implement tilemap into libgdx and box2d with infinite/endless scheme. I can load a single map and display everything on screen. But placing 2 or more tilemap side by side got me headache. I know currently not possible to offset/add x value position of tilemap. What I do right now is use setview for camera of it's render method. This is my map helper and currently I works with 3 renderer for 3 tilemap as a test...

public class MapHelper {
private Array<OrthogonalTiledMapRenderer> renderer = new Array<OrthogonalTiledMapRenderer>();
private int number;
private float oldDistance, currentDistance;
private String layer = "world";

public MapHelper(Callback callback) {
    this.callback = callback;
    number = 0;
    item = new ItemMap[3];
}

public void render(CamHandler cam) {
    for(int r = 0; r < renderer.size; r++) {
        if(item[r] != null) {
            renderer.get(r).setView(cam.getCam().combined, item[r].distance, 0, item[r].getWidth(), item[r].getHeight());
            renderer.get(r).render();
        }
    }
}

public void updateMap(CamHandler cam) {
    if(mapOut(cam)) {
        number++;
        if(number > 2)
            number = 0;
        loadMap(number);
    }
}

/**
 * Check if camera reach the current distance, then build new map
 * @param cam
 * @return
 */
private boolean mapOut(CamHandler cam) {
    float x = cam.getCam().position.x + cam.getCam().viewportWidth / 2;
    Utils.log("pos cam x "+x+" current distance "+currentDistance);
    return x >= currentDistance;
}

private void loadMap(int map) {
    AssetsManager.loadMap(map);
    if(item[map] != null) {
        renderer.set(map, new OrthogonalTiledMapRenderer(AssetsManager.map));
        item[map].set(TileHelper.getMapWidth(AssetsManager.map, layer), TileHelper.getMapHeight(AssetsManager.map, layer), currentDistance);
    } else {
        renderer.add(new OrthogonalTiledMapRenderer(AssetsManager.map));
        item[map] = new ItemMap(TileHelper.getMapWidth(AssetsManager.map, layer), TileHelper.getMapHeight(AssetsManager.map, layer), currentDistance);
    }

    oldDistance = currentDistance;
    currentDistance += TileHelper.getMapWidth(AssetsManager.map, layer);
    callback.onLoad();
    Utils.log("load new map "+map+" distance "+currentDistance);
}

public Array<OrthogonalTiledMapRenderer> getRenderer() {
    return renderer;
}

public Array<Body> getBodies(World world) {
    return new MapBodyBuilder().buildShapes(AssetsManager.map, world, oldDistance);
}

private ItemMap[] item;

private class ItemMap {
    private float distance, mapWidth, mapHeight;

    ItemMap(float w, float h, float distance) {
        mapWidth = w;
        mapHeight = h;
        this.distance = distance;
    }

    private void set(float mapWidth, float mapHeight, float distance) {
        this.mapWidth = mapWidth;
        this.mapHeight = mapHeight;
        this.distance = distance;
    }

    private float getWidth() {
        return mapWidth * Constants.WORLD_TO_SCREEN;
    }

    private float getHeight() {
        return mapHeight * Constants.WORLD_TO_SCREEN;
    }
}

private Callback callback;

public interface Callback {
    void onLoad();
}

public void startOver() {
    clear();
    currentDistance = number = 0;
    loadMap(number);
}

private void clear() {
    for (OrthogonalTiledMapRenderer render : renderer) {
        render.dispose();
    }
}

}

With above class, I can display and load new map on screen when camera reaching the map end. But the tile layer texture keeps wrong position. Please give me an advice.


texts: Libgdx import bin/xml/json from physics editor

texts:
I'm using Libgdx. I did a simple json file in Physics Body Editor and I don't have any idea how could I import it into my physic world in libgdx.

Any idea will be appreciated.

P.S: Sorry if there are question with the same subject, I didn't find any of them.


texts: Voxel traversal intersection float position

texts:
I have a 3D grid of cubes, and using the algorithm from this paper http://www.cs.yorku.ca/~amana/research/grid.pdf I've been able to get the integer coordinates of the first tile intersected by a random line.

My question is, is there any simple way to get the intersection floating point position? I've been able to get the normal, but not the position...


texts: How can I reduce a bezier curve using a slider till all points converge to it's original midpoint

texts:
I am using the code from the question here to create bezier curves (I didn't think it was necessary to repost the code here since I haven't made any significant changes to it yet).

I have a symmetric bezier curve (please see image) that I want to reduce till all points converge at the midpoint of the original curve. I would like to preserve it's symmetry while it moves.
I would like achieve this using a  float slider (with values from 0 to 1) in editor mode.


texts: Why doesn't the animtor animate in unity5?

texts:
I have a player consisting of 20 different body parts which I have animated into a walking cycle. When I play the animation in an 'animation' component it works as intended, but when I try to play it from an animator nothing happens.

The player is animated when the animation component is checked.

It does not animate when only the animator component is checked.

It is however running the animation, yet nothing happens in the scene.
I have no scripts attached.


texts: Procedural terrain in the Style of "Zelda: A Link to the Past"

texts:
I am working to create a system that randomly generates pseudo-3d terrain on a tile grid using the methods used in the legend of zelda games between link to the past and minish cap.

I have created a tileset for it, and after manually making some maps and getting a feel for what the tile placement algorithm needs to do, I've implemented one of four possible layer-transitions. There are still some special edge-cases which will likely need special tiles, but the image shows a fully procedural map using it. My implementation keeps track of the altitude of each vertex (not center) of a tile. By comparing the altitudes at each corner, and in some cases those around the focused tile, I can determine which sprite to use.

This system needs to be "infinite" in that I can generate chunks adjacent to existing ones using the same noise function. I have plans to make a worldmap system similar to a LOD system too, which wouldn't be too hard with perlin noise, but alternative suggestions should keep this in mind.

I have several questions about this system. The first is this: How I can make my noise more like the example, preferring to line up edges which are nearby (but only to a degree)? How can I make it prefer less complex shapes, more similar to octagons than realistic messy hills?

The second is about how I can connect the layers: for altitude changes greater than 1 level, I want to require the player to use ramps. Unfortunately I don't have a solid example of this in my current tileset, but essentially, two disconnected altitudes should have a "slope" (really just the neutral tile) between them... I could use A* or similar, but how do I detect where it needs to be used? Or is there a better way to ensure connectivity?

Excuse the programmer ""art"" please

What I have:

What I want:


texts: Why is the distance from object to eye irrelevant in illumination models?

texts: For example in Phong model and Blinn model, the light intensity does not change depending on how far away the camera is. Why is that?


texts: How to Instantiate an array of Prefabs in a chequerboard pattern

texts:
I need to instantiate an array of 2 elements that is floors of black and white color in an alternating pattern so it looks like a chess board. It is for my game that has 2D Dungeon Generation.

This is my current code:

public enum TileType
{
    Wall, Floor,
}

public GameObject[] floorTiles;
public GameObject[] wallTiles;
public GameObject[] outerWallTiles;

private TileType[][] tiles;
private Room[] rooms;
private Corridor[] corridors;
private GameObject boardHolder;

void InstantiateTiles()
{
    for (int i = 0; i < tiles.Length; i++)
    {
        for (int j = 0; j < tiles[i].Length; j++)
        {
            InstantiateFromArray(floorTiles, i, j);

            if (tiles[i][j] == TileType.Wall)
            {
                InstantiateFromArray(wallTiles, i, j);
            }
        }
    }
}

void InstantiateFromArray(GameObject[] prefabs, float xCoord, float yCoord)
{
    int randomIndex = Random.Range(0, prefabs.Length);
    Vector3 position = new Vector3(xCoord, yCoord, 0f);
    GameObject tileInstance = Instantiate(prefabs[randomIndex], position, Quaternion.identity) as GameObject;
    tileInstance.transform.parent = boardHolder.transform;
}

}

So this is how it looks right now (just random positions of floor prefabs):

And this is what I am trying to achieve (alternating):


texts: Why when using Mathf Lerp the speed is not changing according to Time.deltatime?

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

public class DetectCollision : MonoBehaviour
{
    public Transform player;
    public Transform target;
    public bool turnOnOffPlayerAnimator = false;

    float timeElapsed = 0;
    float lerpDuration = 3;
    float startValue = 1;
    float endValue = 0;
    float valueToLerp = 0;

    private Animator playerAnimator;
    private bool entered = false;
    private bool prevFacing = false;
    private Rigidbody rigidbody;
    private bool stopped = false;

    // Start is called before the first frame update
    void Start()
    {
        rigidbody = player.GetComponent<Rigidbody>();

        playerAnimator = player.GetComponent<Animator>();

        if (turnOnOffPlayerAnimator)
            playerAnimator.enabled = false;
    }

    // Update is called once per frame
    void Update()
    {
        var currFacing = IsFacing(target);
        if (currFacing != prevFacing)
        {
            // here you switched from facing to not facing or vise verca.
            timeElapsed = 0;
        }
        prevFacing = currFacing;

        var distance = Vector3.Distance(player.position, target.position);

        if (IsFacing(target))
        {
            if (entered && distance > 30)
            {
                if (timeElapsed < lerpDuration)
                {
                    valueToLerp = Mathf.Lerp(startValue, endValue, timeElapsed / lerpDuration);
                    playerAnimator.SetFloat("Forward", valueToLerp);
                    timeElapsed += Time.deltaTime;
                }
                playerAnimator.SetFloat("Forward", valueToLerp);

                valueToLerp = 0;
            }
        }
        else
        {
            if (valueToLerp < 0.9f)
            {
                if (timeElapsed < lerpDuration)
                {
                    valueToLerp = Mathf.Lerp(endValue, startValue, timeElapsed / lerpDuration);
                    playerAnimator.SetFloat("Forward", valueToLerp);
                    timeElapsed += Time.deltaTime;
                }
                playerAnimator.SetFloat("Forward", valueToLerp);
            }

            Mathf.Lerp(valueToLerp, 0, Time.deltaTime * 0.0001f);
        }

        if(turnOnOffPlayerAnimator)
        {
            playerAnimator.enabled = false;
        }
        else
        {
            playerAnimator.enabled = true;
        }
    }

    private void OnTriggerEnter(Collider other)
    {
        entered = true;

        Debug.Log("Entered !");
    }

    private void OnTriggerExit(Collider other)
    {
        entered = false;

        Debug.Log("Exited !");
    }

    private bool IsFacing(Transform target)
    {
        Vector3 forward = player.TransformDirection(Vector3.forward);
        Vector3 toTarget = target.position - player.position;
        return Vector3.Dot(forward, toTarget) > 0;
    }
}

I tried first 0.1f but it didn't change the lerp speed.
I want that if the player is pressing the W key and moving the player forward and then stop pressing the key W it will smooth slow will lerp to 0. and it does but I also wanted to control the lerp speed.
I want that when the player is starting moving backward direction if the player leave the W key the player should stop slowly to 0. This should be the line :
Mathf.Lerp(valueToLerp, 0, Time.deltaTime * 0.0001f);

but the Time.deltaTime does not seems to affect the lerp at all.
the lerp is working fine I just wanted to control the lerping speed too.


texts: Vertex shader in OpenGL/GLSL - transformation of the interior of a textured quad

texts:
I have a LWJGL project and ran into a problem with a vertex shader I wrote.
In my scene I am rendering a map whose ground consists of rectangular tiles.
On top of that there are other objects (I used tiny white balls here).
Here is a screenshot of my scene:

screenshot of my scene http://110.imagebam.com/download/0-Ktu6XjdWSMpKytTr3Trg/34736/347358711/scene_static.jpg

You can also click here to see the image.

Each of the four larger rectangles at the bottom is one huge quad drawn in one piece.
Every one of them contains four coordinates (the corners: top-left, top-right, bottom-right, bottom-left).
Their interior is filled with a texture.

The small white balls on top are single game objects each drawn by itself.
Note that I aligned them with the vertical edges of the underlying rectangles.

I used the following vertex shader to render the scene:

/* default shader */
#version 120

void main()
{
    gl_TexCoord[0] = gl_MultiTexCoord0;
    gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;
}

Now imagine the scene getting covered with water.
I modified the shader adding a little water effect:

/* water shader */
#version 120

uniform float amplitude;
uniform float phase;

void main()
{
    gl_TexCoord[0] = gl_MultiTexCoord0;

    // transform x
    vec4 a_position = gl_Vertex;
    a_position.x = a_position.x + amplitude * sin(phase + a_position.x);

    gl_Position = gl_ModelViewProjectionMatrix * a_position;
}

An animated image of my scene can be found here or here.

You can see that the borders of the rectangles keep aligned with the white balls on top of them. However, vertices inside the rectangles (I marked the most distinct areas red) suffer a displacement relative to the white balls. In the last rectangle you can even see the balls cross the white line in the middle.

I need the interior of my textured rectangles to be transformed exactly like the white balls on top and move uniformly when being animated by my shader.
Please let me know if my problem is clear and if any other information is needed.

Thank you very much for your help.
Greetings Xoric


texts: Unity 5.3 Webgl Build not working on Google Chrome

texts:
I am testing a game I build it on webgl and opened it on Google Chrome but nothing showed up just a screen with unity logo and no loading screen, then I tried on Firefox and it ran smoothly without any issues I am using unity 5.3.3f1 and Chrome 48 what can be the issue?
I am really looking forward for your replies, I searched on internet but in vain and not too many people answered this question on internet.


texts: How to "properly" display a 2d sprites in a 3d environment?

texts:
I would like to show "the classic" missile lock viewfinder (the target symbol) of a war aircraft.
So the target symbol must follow the enemy, and became red when "lock" it.
So i thought simply to Show the 2d sprite centered on screen (x and y = screen.height and width /2 )  but, depending of the Z , the sprite became bigger (near camera) or smaller (far from the camera).

How to display a 2d sprite indipendent from Z axis ?

Thanks


texts: Picking random monster cards from a deck

texts:
What is the best way to go about making user defined classes (monsters, items, loot, armor, weapons, spell types, etc) and then calling them later during an encounter? Looking at the entire card list for a trading card game is intimidating, and I would love some advice on tackling this before I go about it the wrong way.

class Card(object):
def __init__(self, name, value, type, power):
    self.name = name
    self.value = value
    self.type = type
    self.power = power
    self.expan = 'Base'

class Monster(Card):
def __init__(self, name, value, type, power):
    self.active = False
    Card.__init__(self, name, value, type, power)
    #monsterlist.append((self.name, self.value, self.type, self.power))

Is it ideal to just make a random number and create the monster like this (there's over a thousand cards, so this doesn't seem optimal to me):

def pickMonster():
    chance = random.randint(1,2)
    if chance == 1:
        goblin = Monster('goblin', 8, 'animal', 'run')
    if chance = 2:
        troll == Monster('troll', 8, 'troll', 'smash')

Can I define monsters in a list/dictionary somehow and pull them at random from there?  I was trying to use this method to make the code easier to read, but I'm having a hard time figuring out exactly how to do it that way (as I'm not even sure it's possible to put more than 2 values into a list, and dictionaries are the bane of my existence -- I'm fairly new to python).


texts: How should I develop my Android game efficiently?

texts:
I have attached a image of a flow chart that I made in paint.

The image shows how I want to develop my game. I want a game that runs great with smart coding that is easy to update and ad features over time. My target platform is the Android smartphone and all code will be written in java with XML inflated resources, if that matters. I am not looking for hard code,although pseudo code will help, I would more so prefer suggestions and advise from the pros.

My questions are :

Is this a good way to program a game or are there better ways to do this? Are there any modifications that need to be made? Any suggestions would be useful because I am not experienced in game programming so I would prefer the advice from someone who has written several games and knows from experience how one should go about setting their code up to run efficiently.


texts:
I´ve been following this tutorial : http://www.dyn4j.org/2010/01/sat/ to help me understand and implement the SAT for collision detection in my games as I want to add a support for polygons. However, I´m facing troubles with the overlap function(to determine whether two projections overlap or not). Pieces of code:

class Polygon {
    public:
        std::vector<vec2> vertices;
        std::vector<vec2> edges;
        std::vector<vec2> axes;

        Polygon(){}

        Polygon(std::vector<vec2> list) :
            vertices(list)
        {
            init();
        }

        void init() {

            for (std::size_t i = 0; i < vertices.size(); i++) {

                vec2 edge = vertices[i] - vertices[i + 1 == vertices.size() ? 0 : i + 1];

                edges.push_back(edge);

                axes.push_back(edges.back().perp()); // its just (x,y) => (y,-x)
            }

        }

The projecting function:

    vec2 project(vec2& axis) {

        double min = axis.dot(vertices[0]);
        double max = min;

        for (std::size_t i = 1; i < vertices.size(); i++)
        {
            double p = axis.dot(vertices[i]);

            if (p < min)
                min = p;
            else if (p > max)
                max = p;
        }

        return vec2(min, max);
    }

And finally a function to determine if they collide or not:

bool collide(Polygon& poly1, Polygon& poly2)
{
    for (std::size_t i = 0; i < poly1.axes.size(); i++)
    {
        vec2 proj1 = poly1.project(poly1.axes[i]);
        vec2 proj2 = poly2.project(poly1.axes[i]);

        if (!proj1.overlap(proj2))
            return false;
    }

    for (std::size_t i = 0; i < poly2.axes.size(); i++)
    {
        vec2 proj1 = poly1.project(poly2.axes[i]);
        vec2 proj2 = poly2.project(poly2.axes[i]);

        if (!proj1.overlap(proj2))
            return false;
    }

    return true;
}

How would you implement the overlap function? I found someone elses solution using this overlap function :

bool overlap(const vec2& vector) {

    vec2 diffVector(x - vector.x, y - vector.y);

    if (diffVector.magnitude < magnitude)
        return true;
    else
        return false;
}

but its not working correctly. Is the error somewhere else or?
Also im using for tets :

std::vector<cd::vec2> vertices{ {-2.0f,2.0f},{ -1.0f,0.0f },{ 2.0f,0.0f },{2.0f,2.0f },{ -1.0f,3.0f } };
cd::Polygon poly1(vertices);

std::vector<cd::vec2> vertices2{ { 0.0f,-2.0f },{ 0.0f,-3.0f },{ 2.0f,-3.0f },{ 2.0f,-2.0f },{ 1.0f,1.0f } };
cd::Polygon poly2(vertices2); And it ouputs me they don´t collide even when they should collide. Thanks!

Edit1
(due to the first answer)
Adding a small screenshot showing a situation where green and red polygons just touch eachother, however the algorithm says they do not collide.


texts:
I am doing a study in modern games graphics, and as part of the study it would be really helpful to be able to replay a sequence in the game multiple times.
For example, recording a series of inputs to get the exact video sequences, but being able to replay them in different computers or different graphics configurations.

I want to do this study with a couple of existing commercial games with sophisticated graphics (something released in the last 1 or 2 years if possible). I was thinking on hooking with detours or something similar, calls to time() or srand() to fix all pseudo-number generated results. It would be ideal to have a general solution that works with any game. Since admittedly that is pretty ambitious, I would be happy just having 2 or 3 games in which it is known that I can get deterministic output for a given input.

In the end, I will be comparing video output, so I want to avoid noise generated by differences on each execution caused by non-determinism.
Any sugestions?


texts: How can I port my Gear VR app (Java, OpenGL ES) to Unity?

texts:
I want to port my Gear VR app (created in Java using the official framework) to Unity, so I can also support Microsoft's new-ish VR headsets (not talking about the Hololens!).

In my current app I'm using OpenGL ES to draw everything I need (the app reads coordinates and additional information about what it has to draw from a .txt file), which is:

GL_LINE_STRIP: The .txt file gives it a bunch of coordinate triples (x, y and z, so single vertices), it then has to automatically connects them (usually without loops)
Kind of plane: Either display a rectangular plane with a texture (using the Gear VR framework's "GVRSceneObject") OR create an outline (usually first point = last point) that then gets filled in a specific color (GL_TRIANGLE_FAN) AND that is a little bit transparent - if it includes concave areas, it's using GL_TRIANGLES and the .txt file has coordinates for single triangles that have to be displayed at the same time and filled (it's still a single object/mesh!)

What I need Unity to do (with 1. and 2.):

Display a couple of 1. (could be up to 50 or more) and 1 of 2. at the same time (there'll never be more than 1 of type 2.!)
Remove all of 1. (that are displayed at the same time) or 2. from the scene and/or replace them with a couple of different 1. or another 2.
Group a couple of 1. together, so you can remove them at the same time (which would make stuff a lot easier)
Read .obj files (including their texture) from internal storage (Android) or the HDD (Windows) and display it/them instead of 2. (the .txt file includes the path to the file and texture)

Everything has to happen at runtime, since the app doesn't come with any .txt files or pre-imported .obj scenes/objects!

My question is:

How can I do this with Unity, targeting Windows and Android?


texts: Make bones in blender work corectly in XNA

texts:
So, I am trying to connect bones with vertex groups in blender, but I keep failing. if I move a bone in XNA, it doesnt also move those vertecis that are connected to this bone(vertex groups). What I have done is following:

-I made a model made up of four cuboids(seperate meshes).

-then I have created vertex groups for each of the mesh and assign vertecis to those groups.

-now I have added two bones(armatures).

-I renamed some of the vertex groups to the name of the first bone(not armature): "Bone".

-for the second bone "Bone2" I have made a vertex groups in all of the meshes, this vertex group contains all of the  vertecis of that mesh.(because, if not all the vertecis are connected to at least one bone, XNA throws an error)

-then I exported if to .fbx format, checking: XNA Strict Options, XNA Rotation Animation Hack.

Thank you in advance!

EDIT:
Ok, I have fixed the boneWeightCollection problem by unchecking Apply Modifiers in export menu. In blender now everything works great, if I move the bones in their POSE mode they deform the mesh. But they do not work in xna(if I move them, they do not deform the mesh)


texts: Programming and drawing to deal with different screen sizes and resolutions

texts:
I started making an XNA game years ago and picked it up recently.

I'm looking later to convert it to use Monogame so that it can be deployed on various mobile devices and OS, though I have a sinking feeling that a lot of the sprites and code will be broken by the changing screen sizes when I move outside of the emulator.

The game is currently hard coded to to 800x480 and the level placements and sprite sizes were all done to fit that at the time.

So question:

What do I need to ensure this works and displays properly on a variety of screens and devices?


texts: Do meshes marked "shadows only" require light maps to block light?

texts:
I want to use an .fbx mesh to block light from entering a room (except for holes cut for windows). The mesh itself must stay invisible. I know marking it "shadows only" will hide it from the camera, but light still passes through it unless I mark the mesh as "lightmap static" as well. The problem is that this is a huge mesh that doubles the number lightmaps required, and it won't even be seen.  Is there a better way to do this?

I am using the Lightweight Render Pipeline in Unity 2019.1.4f1 on Windows 10. Using CPU to render on an Intel Core i5 laptop.


texts: Image drawing then blackscreen on AVD using cordova

texts:
I have an issue on my android JS based game, the game displays well for 1 second then total blackscreen.

    window.requestAnimFrame = (function(){
      return  window.requestAnimationFrame       ||
              window.webkitRequestAnimationFrame ||
              window.mozRequestAnimationFrame    ||
              window.oRequestAnimationFrame      ||
              window.msRequestAnimationFrame     ||
              function(/* function */ callback, /* DOMElement */ element){
                window.setTimeout(callback, 1000 / 60);
              };
    })();

    (function() {
        var game = {
            canvas : document.getElementById('canvas'),
            frameWidth : 1280,
            frameHeight : 720
        };
        game.context = game.canvas.getContext('2d'),
        game.canvas.setAttribute('height', game.frameHeight);
        game.canvas.setAttribute('width', game.frameWidth);
        game.screens = {
            splash : new Image()
        }
        game.screens.splash.src = "src/img/splash.jpg";
        render(game);
    }());

    function render(game){
        game.context.drawImage(game.screens.splash, 0, 0, 1260, 720, 0, 0, 1260, 720);
        requestAnimFrame(function(){render(game)});
    }

The game works well on CocoonJS, I don't have any build error with Cordova. I tried to draw a rectangle instead of the image and it works.

I'm really sure it's a drawImage() issue.


texts: Display two characters with same tag in unity 3d

texts:
I'm developing a bowling game in which I'm currently working on the winner loose scene. I have a parent gameobject which contains two character models having the same gameobject tags. For the two player game I'm using the same tag for both the players for their individual turns. Now as in the end of the game I have to display both the characters at the same time having to play the winner and the defeat animation using the same tag. How can this be done or is there any other way this can be done?

To obtain all the child characters from parent tag, this is what I've tried at runtime:

modelcontainer = GameObject.FindGameObjectWithTag("modelcontainer");

        findgameobjects = new GameObject[modelcontainer.transform.childCount];

        for (int i = 0; i < modelcontainer.transform.childCount; i++)
        {
            findgameobjects[i] = modelcontainer.transform.GetChild(i).gameObject;
        }

But it doesn't store the child gameobject which is not active at current time as per my game logic.


texts: Textures have lines between them when zoomed out

texts:
These are two screenshots from my new game, a top-down RTS with tiles. The first one is from a normal view with no zoom, the second one is a zoomed out view of the whole map:

In the first image, the tiles are rendered perfectly. However, when I zoom out, some of the tiles are rendered with lines in between them, while others clump into larger groups with their own lines. Here is the code that draws the tiles:

            Rectangle rect;

            if ((int)(32 * gameInfo.Game.ZoomFactor) > 0)
            { rect = new Rectangle(0, 0, (int)(32 * gameInfo.Game.ZoomFactor), (int)(32 * gameInfo.Game.ZoomFactor)); }
            else
            { rect = new Rectangle(0, 0, 1, 1); }

            Texture2D buffer = new Texture2D(this.GraphicsDevice, rect.Width, rect.Height);

            for (int x = 0; x < gameInfo.Game.TileMap.GetLength(0); x++)
            {
                for (int y = 0; y < gameInfo.Game.TileMap.GetLength(1); y++)
                {
                    rect.X = (int)(gameInfo.Game.ZoomFactor * ((x * 32) - gameInfo.Game.ViewOffset.X));
                    rect.Y = (int)(gameInfo.Game.ZoomFactor * ((y * 32) - gameInfo.Game.ViewOffset.Y));
                    buffer = EnvironmentTextures.ENTileTextures[gameInfo.Game.TileMap[x, y].TileType];
                    spriteBatch.Draw(buffer, rect, Color.White);
                }
            }

The gameInfo.Game.ZoomFactor is a Single which is modified when the scroll wheel is changed, in increments of 0.2f. Has anyone had this problem before, and how can I fix it?


texts: How to translate the accelerometer input by specific angle?

texts:
I have an orthographic camera set on position(0,0,-10), rotation(0,0,0) and it's parent - CameraHolder with a transform:

which gives an isometric feel:

Now, I need to move the ball with the accelerometer so here's how the FixedUpdate() looks like:

   void FixedUpdate ()
     {
         if (SystemInfo.deviceType == DeviceType.Desktop)
         {
             // Player movement in desktop devices
             // Definition of force vector X and Y components
             float moveHorizontal = Input.GetAxis("Horizontal");
             float moveVertical = Input.GetAxis("Vertical");

             // Building of force vector
             Vector3 movement = new Vector3 (moveHorizontal,0.0f,moveVertical);
             // Adding force to rigidbody
             rigidbody.AddForce(movement * speed * Time.deltaTime);
         }
         else
         {
             // Player movement in mobile devices
             // Building of force vector
             Vector3 movement = new Vector3 (Input.acceleration.x, 0.0f, Input.acceleration.y);
             // Adding force to rigidbody
             rigidbody.AddForce(movement * speed * Time.deltaTime);
         }
     }

The movement looks like this:

And I want it to move like:

I need to translate the movement by 45 degrees, but I have no idea how.

If anyone has a clue, I'd be grateful for help!