texts: Large game statistics database management

texts:
I am making a management game in Java with a farming theme. I am rather beginner in software development and every steps requires lots of thoughts. I am at a point now that I want to log and keep every lots of statistics of what happens in the game. For example every time a task is completed, state of every crop field and animal  at the end of every day and so on. So I learned how to use some basic feature of Log4j2 and got a text file to log a new line every time I want to log an event. I noticed that after just 3 game days with a tiny farm size the file is already over 10kB (1KB zipped). I suspect that it will quickly become rather large for long games, bigger farm size, more complex farms... It made me wonder if it was not the best way of doing such a thing. I still have to implement a parsing method to read the text files, process the data and visualize it.

So is there a better approach? Should I write my events in a list and serialize it in binaries(I have never done that in fact I use gson for my saved games). Then again I would not want multiple hundreds of MB of data loaded up in RAM all the time. Since my project is rather small compared to many others I suspect there is a better way.


texts: I'm trying to simulate a ball coming at the screen with a projectile motion arc in 2d space. Is there a set of equations to deal with this.  I would imagine the equation would need to take in the  initial vertical and horizontal angles of the projectile as well as it's initial velocity and the desired start and end scale of the projectile.


texts: Problem with Blender model imported to Unity (Lighting problems)

texts:
I made a simple box in blender and imported it to unity. Now I'm facing with this weird lighting problem:

I've been messing around with normals, duplicated vertex, lots of things, even lightning properties but still I'm not getting any results at all. Why does this happen and how can I solve it?

Source blend file: https://drive.google.com/open?id=1Ze1JBRFBvhnnY-w36U2KDe7Q2zcfXsmf


texts:
I have heard that in OGL and in DX9 D3DPOOL_MANAGED mipmap layers are pulled to the GPU memory on demand. As in If I pull from layer 4 of a mipmap, that layer and all smaller layers are pulled into the GPU memory, but larger mipmap layers are not.

I have tried to test this by creating a scene which requires more textures than the GPU has room for, but never getting close enough to any object such that it's larger mipmaps are required.In OGL I don't hit a performance cliff, and as best I can tell with gDebugger I don't fill the GPU memory.In D3DPOOL_DEFAULT I actually get a DX9 error cause I run out of GPU memory space.

At such a high level of abstraction I can't conclusively say what's happening. But I was hoping someone here could confirm or deny the partial mipmap rumor I've heard, as that would make my tests make sense.


texts: What's the correct way to move 2d sprites in opengl 2.1?

texts:
I'm getting into Opengl 2.1 and wanted to know how can I move 2d sprites.
I already created my vbo and ibo, and the vertex data is already there. But, how can I move a sprite once it's already drawn?

Should I update the vertex data with glBufferSubData(I don't think that's efficient), or whould I use glTranslate3f? If I use glTranslate I move all the sprites in the screen.

Any help appreciated, thanks!


texts: a simple 2D rectangle collision algorithm that also determines which sides that the rectangles collide?

texts:
I initially tried out implementing rectangular intersection, which works well. However, when I have to apply the physics system, such as velocity, acceleration, and directional vectors, I would have to find a way to determine which side of the rectangles collide. Now, in my system, there is no rotated rectangle, so this simplified the problem. However, I couldn't find an easy way to determine which rectangle side collided. I have once deal with this problem before but failed miserably.

What I did in the past is determine the distance between each parallel rectangular sides and check if the distance is close to 0 (use some initially defined distance range) or is 0. However, for floating-point arithmetic, this proves to be unstable because of unknown time elapse. Sometime, the rectangles would actually intersect each other before it meets the defined range.

On the other hand, I was thinking about spawning multiple rectangles, each rectangle for each sides. However, after thinking again, it would be the same thing as having a parallel side with distance range checking, just that that distance range is the width of each mini-rectangle.

Therefore, any suggestion to this problem?


texts: If I have two levels that I have made separate in HTML5 how may I combine them so one comes after another?.


texts:
Heres the code:

void Update() {
    Debug.DrawLine(attackSpot.position, attackSpot.TransformDirection(Vector3.forward * distance), Color.red);
    Debug.DrawLine(transform.position,  transform.TransformDirection(Vector3.forward * distance), Color.green);
}

I'm drawing 2 lines, one is coming from attackSpot and one is coming from own transform.

Reason of this because my Raycast doesn't worked properly, so I decided to see visually to check.

Of course, attackSpot is pointing front direction.

Rotation of attackSpot in screenshot is local rotation. But when the play game, line coming from attackSpot doesn't go straight, it moves lower direction.

I also tried

Debug.DrawLine(attackSpot.position, attackSpot.forward * distance, Color.red);

But has same result. Why my ray doesn't go straight? What am I missing?


texts: How do I make a pop-up window with Scene2D?

texts:
I have a main-menu screen with a logo and a bunch of buttons. When the Login-button is pressed, I pop up a dialogue asking for a username and password.

This works fine, other than the "popping up". At the moment the new the dialogue box just shifts everything about, but I'd want to position it over the current scene.

I'm just learning Scene2D.


texts: jumping and movement with rigidbody2d.velocity, gravity problem

texts:
i'm making a 2d platformer and i move my character with rigidbody2d.velocity swiping up to jump and moving while holding the left or right side of the screen.

the problem is that when i jump and i try to move left or right in the air, my character falls very slowly. i've read that the reason why that happens is because rb.velocity overrides gravity at every frame, is there a way to move left or right in the air with normal gravity?

my full code is

{
 Rigidbody2D rb;
public float speed = 1f;
public float jumpforce = 3.5f;
private Vector3 mouseDownPos;
private float startTime = 0f;
public float holdTime = 0.15f;

void Start()
{
    rb = GetComponent<Rigidbody2D >();
}

void Update()
{

 if (Input.GetMouseButtonDown(0))
    {

        mouseDownPos = Input.mousePosition;
        startTime = Time.time;
    }

    if (Input.GetMouseButtonUp(0))
    {

        if ( startTime + holdTime > Time.time & Input.mousePosition == mouseDownPos)// tap
        { Debug.Log("T A P");}

    if (Input.mousePosition.y > mouseDownPos.y + 100 )//jump
        {

            rb.velocity = new Vector2(rb.velocity.x, jumpforce);
        }

    }

    if (Input.GetMouseButton(0) & startTime + holdTime <= Time.time)///move while grounded
    {
        if (Input.mousePosition.x < Screen.width / 2)
        {
            Debug.Log("Left click");
            rb.velocity = transform.right * speed;

        }
        else if (Input.mousePosition.x > Screen.width / 2)
        {
            Debug.Log("Right click");
            rb.velocity = transform.right * speed;

        }

        if (Input.mousePosition.x < Screen.width / 2)/// move while in the air
        {
            Debug.Log("Left click");

            rb.velocity = new Vector2(-speed, rb.velocity.y);

        }
        else if (Input.mousePosition.x > Screen.width / 2)
        {
            Debug.Log("Right click");

            rb.velocity = new Vector2(speed, rb.velocity.y);

        }

    }

}

the rigidbody2d of my character is


texts: Unity - How to serialize / show private fields and custom types in Inspector?

texts: By default, Unity only serializes public fields. How can I serialize private fields and custom types to show them in inspector?


texts: Set new forward directions based on camera position

texts:
I have a 3rd person camera which can rotate around the player.

When I look at the back of the player and press forward, player goes forward. Then I rotate 360 around the player and "forward direction" is tilted for 90 degrees. So every 360 turn there is 90 degrees of direction change.

For example when camera is facing the right side of the player, when I press button to move forward, I want player to turn to the left and make that the "new forward".

I have Player object with Camera as child object. Camera object has Camera script. Inside Camera script there are Player and Camera classes. Player object itself, has Input Controller.

Also I'm making this script for joystick/ controller primarily.

My camera script so far:

using UnityEngine;
using System.Collections;

public class CameraScript : MonoBehaviour
{
    public GameObject Target;
    public float RotateSpeed = 10,
    FollowDistance = 20,
    FollowHeight = 10;
    float RotateSpeedPerTime,
    DesiredRotationAngle,
    DesiredHeight,
    CurrentRotationAngle,
    CurrentHeight,
    Yaw,
    Pitch;
    Quaternion CurrentRotation;

    void LateUpdate()
    {
        RotateSpeedPerTime = RotateSpeed * Time.deltaTime;

        DesiredRotationAngle = Target.transform.eulerAngles.y;
        DesiredHeight = Target.transform.position.y + FollowHeight;
        CurrentRotationAngle = transform.eulerAngles.y;
        CurrentHeight = transform.position.y;

        CurrentRotationAngle = Mathf.LerpAngle(CurrentRotationAngle, DesiredRotationAngle, 0);
        CurrentHeight = Mathf.Lerp(CurrentHeight, DesiredHeight, 0);

        CurrentRotation = Quaternion.Euler(0, CurrentRotationAngle, 0);
        transform.position = Target.transform.position;
        transform.position -= CurrentRotation * Vector3.forward * FollowDistance;
        transform.position = new Vector3(transform.position.x, CurrentHeight, transform.position.z);

        Yaw = Input.GetAxis("Right Horizontal") * RotateSpeedPerTime;
        Pitch = Input.GetAxis("Right Vertical") * RotateSpeedPerTime;
        transform.Translate(new Vector3(Yaw, -Pitch, 0));
        transform.position = new Vector3(transform.position.x, transform.position.y, transform.position.z);

        transform.LookAt(Target.transform);
    }
}

My player script:

using UnityEngine;
using System.Collections;

public class PlayerScript : MonoBehaviour
{
    public float RotateSpeed = 10,
    MoveSpeed = 10;
    float DeltaTime;
    public Transform cameraTransform;

    void Update()
    {
        DeltaTime = Time.deltaTime;
        transform.Rotate(0, Input.GetAxis("Right Horizontal") * RotateSpeed * DeltaTime, 0);
    }
}


texts: Fast Occlusion Discovery in 3D Point Cloud

texts:
I am trying to find occluded objects given a view point at x,y,z in the scene. For instance in the example below all the points constructing trees should be returned as occluded objects (because of the building).

Is there any better approach than tracing rays and querying occupancy of every voxel on those rays within the Octree? This approach doesn't look efficient as the complexity significantly grows with number of voxels and distance from P(x,y,z) in the scene.


texts: How much does joystick axis resolution matter?

texts:
While developing, I started integrating joysticks into my framework, and had some questions since different OSs handle joysticks differently.  My framework may potentially be opened to the public at a later date, so I thought I'd ask these for consideration:

What's the minimum amount of resolution a framework should offer to developers?  While watching the values of the axes, I can get a reasonably smooth range from my joystick; however I can't think of too many use cases for the higher resolutions.

Are there any real benefits of having high resolution vs a lower one?  I was thinking about having just a 3-bit resolution for my games, (standing, creeping, walking, running, plus one bit for the opposite direction).

I can only see high resolutions being useful on driving or airplane simulator games, so are there reasons to use them in other types of games?  Personally, I still see having three, or even four bits for such games as enough.

Thanks.


texts: Combine flat and smooth shading with a single model geometry

texts:
I need to be able to switch between smooth and flat shading interactively.  Is there a way to do this efficiently with a single geometry?

For example, smooth shading does not require duplicate vertices, whereas flat shading does.  If I load an arbitrary model, would I need to rebuild the geometry such that each triangle has it's own set of 3 vertices, or is there a better way to accomplish this?


texts:
How do I calculate color intensity if I have a image sample of RGB?

The sample is of a float3 of red, green, blue. I'm trying to do a bilateral blur and have to not change the image if the color intensity is the same so it will preserve edges.

 float4 BilateralFiltering(VertexOut input) : SV_Target
{

 const float pixel = 0.01f;

     float4 centralColor;
     float gaussianWeightTotal;
     float4 sum;
     float4 sampleColor;
     float distanceFromCentralColor;
     float gaussianWeight;
     float distanceNormalizationFactor = 1.0;
     centralColor = gDiffuseMap.Sample(samAnisotropic, input.Tex.xy + float2(0,0));
     gaussianWeightTotal = 0.18;
     sum = centralColor * 0.18;

     sampleColor = gDiffuseMap.Sample(samAnisotropic,  input.Tex.xy + float2(-pixel,-pixel));
     distanceFromCentralColor = min(distance(centralColor, sampleColor) * distanceNormalizationFactor, 1.0);
     gaussianWeight = 0.05 * (1.0 - distanceFromCentralColor);
     gaussianWeightTotal += gaussianWeight;
     sum += sampleColor * gaussianWeight;

     sampleColor = gDiffuseMap.Sample(samAnisotropic,  input.Tex.xy + float2(-pixel,0));
     distanceFromCentralColor = min(distance(centralColor, sampleColor) * distanceNormalizationFactor, 1.0);
     gaussianWeight = 0.09 * (1.0 - distanceFromCentralColor);
     gaussianWeightTotal += gaussianWeight;
     sum += sampleColor * gaussianWeight;

     sampleColor = gDiffuseMap.Sample(samAnisotropic,  input.Tex.xy + float2(-pixel,pixel));
     distanceFromCentralColor = min(distance(centralColor, sampleColor) * distanceNormalizationFactor, 1.0);
     gaussianWeight = 0.12 * (1.0 - distanceFromCentralColor);
     gaussianWeightTotal += gaussianWeight;
     sum += sampleColor * gaussianWeight;

     sampleColor = gDiffuseMap.Sample(samAnisotropic,  input.Tex.xy + float2(0,-pixel));
     distanceFromCentralColor = min(distance(centralColor, sampleColor) * distanceNormalizationFactor, 1.0);
     gaussianWeight = 0.15 * (1.0 - distanceFromCentralColor);
     gaussianWeightTotal += gaussianWeight;
     sum += sampleColor * gaussianWeight;

     sampleColor = gDiffuseMap.Sample(samAnisotropic,  input.Tex.xy + float2(0,pixel));
     distanceFromCentralColor = min(distance(centralColor, sampleColor) * distanceNormalizationFactor, 1.0);
     gaussianWeight = 0.15 * (1.0 - distanceFromCentralColor);
     gaussianWeightTotal += gaussianWeight;
     sum += sampleColor * gaussianWeight;

     sampleColor = gDiffuseMap.Sample(samAnisotropic,  input.Tex.xy + float2(pixel,-pixel));
     distanceFromCentralColor = min(distance(centralColor, sampleColor) * distanceNormalizationFactor, 1.0);
     gaussianWeight = 0.12 * (1.0 - distanceFromCentralColor);
     gaussianWeightTotal += gaussianWeight;
     sum += sampleColor * gaussianWeight;

     sampleColor = gDiffuseMap.Sample(samAnisotropic,  input.Tex.xy + float2(pixel,0));
     distanceFromCentralColor = min(distance(centralColor, sampleColor) * distanceNormalizationFactor, 1.0);
     gaussianWeight = 0.09 * (1.0 - distanceFromCentralColor);
     gaussianWeightTotal += gaussianWeight;
     sum += sampleColor * gaussianWeight;

     sampleColor = gDiffuseMap.Sample(samAnisotropic,  input.Tex.xy + float2(pixel,pixel));
     distanceFromCentralColor = min(distance(centralColor, sampleColor) * distanceNormalizationFactor, 1.0);
     gaussianWeight = 0.05 * (1.0 - distanceFromCentralColor);
     gaussianWeightTotal += gaussianWeight;
     sum += sampleColor * gaussianWeight;

     return sum / gaussianWeightTotal;

     }


texts: Creating state machines to handle multiple aspects of a game?

texts:
So first off, I'm not sure if it matters but I am using SFML and C++. I've been wanting to write a game and I've read a lot on FSMs and what they do/make things easier for managing games, etc. What I gathered so far is that a state machine can be set up for each entity as well as the overall game so we are transitioning between states. What I am having trouble with is actually starting off and making a basic implementation of this. So I'd appreciate it if someone can point me in the right direction.

  How do I implement multiple state machines to handle different aspects of the game? For example for characters, for menu/loading/splash/credits etc. If I understood it correctly I would need something like an entity class, and then derive/inherit from it in order to make characters/mobs with various AIs? Is that the right way? Can I do it in a simpler fashion?
  How do I handle transitions if I don't want to use a switch statement? It seems like a naive approach if a more object oriented method exists. What is going to do the switching, do I have to remember the previous state or only know next state?

Thank you in advance!


texts: How do I determine if a tiled shape is closed, but without checking diagonal connections?

texts:
This is a follow-up to a similar question Determine if a set of tiles on a grid forms an enclosed shape.  My needs are similar, but I do not need to check diagonal connections.  I am also using Unity.

I’ve been in the process of trying to workout if a shape is closed.  I decided to use VB.net as my language of choice.

Red = walls
Light Blue = water
Black = Towers
Dark Blue = Fill

I’ve workout the code for filling the shape using the following website

lodev.org/cgtutor/floodfill.html

As far as I’m aware the graph formula is taken from here:

  Tarjan strongly connected components algorithm

I’ve seen versions that have a list of connecting nodes in a node.  The problem with that is not all sides could be connected (e.g. a node has four sides top, right, bottom, left edges these can have a connection to another node).

Although the list will only have a maximum of four connections the order could be all over, with a list depending on what order they where inserted (yes you could order them) it’s an overload that I wanted to mitigate if all possible then I though to make this easy on checking for connections each node could have four connection variables e.g. TopConnection, RightConnection, BottomConnection and LeftConnection, this would greatly simplify checking.

Please can you let me know if I’m on the correct track, if you still think the other ways is best please can you make it in layman’s terms or I’ll get lost before you start.


texts: How do I efficiently send RTS unit selections over the network?

texts:
I have a multiplayer RTS game with every unit assigned an ID.

How can I efficiently send across a network the units selected by a player? For example, Starcraft 2 has upwards of 200 units per player and each player can select a maximum of 255 units at a time. How can I implement such a system with reasonably low response time and bandwidth?

Should I bother sending IDs? Should I perhaps send a bitmask with each bit defining whether each unit is selected?


texts:
I am a beginner shader worlds, it is much difficult to learn(anyhow i try sometime).I am searching a shader that can sense collision/intersection with other objects so that i can stop its rendering at that intersection point. I currently get this shader it allow to detect the intersection(don't know how) but its mesh rendering doesn't stop.

Shader "Custom/IntersectionHighlights"
{
    Properties
    {
        _RegularColor("Main Color", Color) = (1, 1, 1, .5) //Color when not intersecting
        _HighlightColor("Highlight Color", Color) = (1, 1, 1, .5) //Color when intersecting
        _HighlightThresholdMax("Highlight Threshold Max", Float) = 1 //Max difference for intersections
    }
    SubShader
    {
        Tags { "Queue" = "Transparent" "RenderType"="Transparent"  }
        Pass
        {
            Blend SrcAlpha OneMinusSrcAlpha
            ZWrite Off
            Cull Off

            CGPROGRAM
            #pragma target 3.0
            #pragma vertex vert
            #pragma fragment frag
            #include "UnityCG.cginc"

            uniform sampler2D _CameraDepthTexture; //Depth Texture
            uniform float4 _RegularColor;
            uniform float4 _HighlightColor;
            uniform float _HighlightThresholdMax;

            struct v2f
            {
                float4 pos : SV_POSITION;
                float4 projPos : TEXCOORD1; //Screen position of pos
            };

            v2f vert(appdata_base v)
            {
                v2f o;
                o.pos = mul(UNITY_MATRIX_MVP, v.vertex);
                o.projPos = ComputeScreenPos(o.pos);

                return o;
            }

            half4 frag(v2f i) : COLOR
            {
                float4 finalColor = _RegularColor;

                //Get the distance to the camera from the depth buffer for this point
                float sceneZ = LinearEyeDepth (tex2Dproj(_CameraDepthTexture,
                                                         UNITY_PROJ_COORD(i.projPos)).r);

                //Actual distance to the camera
                float partZ = i.projPos.z;

                //If the two are similar, then there is an object intersecting with our object
                float diff = (abs(sceneZ - partZ)) /
                    _HighlightThresholdMax;

                if(diff <= 1)
                {
                    finalColor = lerp(_HighlightColor,
                                      _RegularColor,
                                      float4(diff, diff, diff, diff));
                }

                half4 c;
                c.r = finalColor.r;
                c.g = finalColor.g;
                c.b = finalColor.b;
                c.a = finalColor.a;

                return c;
            }

            ENDCG
        }
    }
    FallBack "VertexLit"
}

Current effect of this shader is

The marked area by arrow should not need to be render


texts: How to create a Ghost Replay feature in a game?

texts:
When you set a personal best lap time in a console racing game, you have the option
to compete against your ghost.

How can this feature be created for a single player casual type game?


texts:
How to model the physics of a car in a racing game?

In real life, vehicle movement is inherited from the wheels. But after reading a few articles on the subject (a lot of which are 10 years old), I realize that the 'real world' physics is in fact often faked with various equations and constants.

I want to create custom driving model to learn about it mostly, but I don't want to start wrong so that's why I am here.


texts: OpenGL - Changing blending modes using sprite batching

texts:
I'm working on a game which uses sprite batching to render sprites efficiently where each sprite gets batched with its VBO data into a VAO every frame (containing vertex coordinates, texture data and color data). So far so good. I'm sorting them on the CPU and ordering the batch before each draw call according to render order to simulate z-ordering.

However, there's one problem: what do I do when I want to draw particles, for instance, which require a blending mode change? All of the sprites are drawn using glDrawArrays use the same blending mode, but for my particle data I want to change the blending mode. If I put the particles in the same batch then I won't have the ability to change it necessarily. My goal is to switch from normal blending (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) to additive blending (GL_SRC_ALPHA, GL_ONE).

1st solution: use a separate draw call for every sprite and don't batch them at all. then for each call I can change the mode appropriately

2nd solution: add a z-coordinate to each sprite to do z-ordering automatically on the GPU using depth testing (this means I can render particles separately in their respective batches with ~2 calls -> +1 for sprites & +1 for particles) which will allow me to change blending modes.

Is there another way of approaching this problem? What am I missing?


texts:
How do I draw a point in world coordinate space (where the camera is currently looking at, so that would be view*projection correct?)

I would think I would need to do something like:

PositionInWorld = MousePositionInNDC * view * projection?


texts:
I'm currently working on a multiplayer game. I've looked at a number of multiplayer services(player.io, playphone, gamespy, and others) but nothing really hits the mark. They are missing features, lack platform support or cost too much. What I'm looking for is a simple poor man's version of steam or xbox live. Not the game marketplace side of those two but the multiplayer services.

User accounts, profiles, presence info, friends, game stats, invites, on/offline messaging. Basically I'm looking for a unified multiplayer platform for all my games across devices.

Since I can't find what I'm planning to roll my own piece by piece. I plan to save on server resources by making most of the communication p2p. Things like game data and voice chat can be handled between peers and the server keeps track of user presence and only send updates when needed or requested. I know this runs the risk of cheating but that isn't a concern right now. I plan to run this on a Amazon ec2 micro server for development then move to a small to large instance when finished.

I figure user accounts would be the simplest to start with. Users can create accounts online or using in game dialog, login/out, change profile info. The user can access this info online or in game. I will need user authentication and secure communication between server and client. I figure all info will be stored in a database but I dont know how it can be stored securely and accessed from webserver and game services.

I would appreciate and links to tutorials, info or advice anyone could provide to get me started. Any programming language is fine but I plan to use c# on the server and c/c++ on devices. I would like to get started right away but I'm in no hurry to get it finished just yet. If you know of a service that already fits my requirements please let me know.


texts:
I'm trying to create random level platforms like this:

 public Level(int platfromsInLevel, Texture2D sprite, int screenWidth)
    {
        rnd = new Random();
        this.screenWidth = screenWidth;

        for (int i = 0; i < platfromsInLevel; i++)
        {
            if (i == 0)
            {
                Platform platform = new Platform((new Vector2(0, 0)), (new Vector2(0, 0)), sprite);
                Platformlist.Add(platform);
            }
            else
            {
                int CurrentX = (int)Platformlist[i - 1].getPos().X + Platformlist[i - 1].getTex().Width;
                int CurrentY = (int)Platformlist[i - 1].getPos().Y + Platformlist[i - 1].getTex().Height;

                int xRand = rnd.Next(CurrentX + 100,(CurrentX + 100) + 150);
                int yRand = rnd.Next(CurrentY + 200, (CurrentY + 200) + 200);

                if (xRand <= screenWidth || xRand >= 0)
                {
                    Platform platform = new Platform((new Vector2(0, 0)), (new Vector2(xRand, yRand)), sprite);
                    Platformlist.Add(platform);
                }
            }
        }
    }

Can anyone help with the random logic? I only want them to appear on the screen that is visible on the X axis, but the y axis is infinite it can go as high as needed. The width of the screen is stored in screenWidth. I also don't think my random logic is taking into account the whole screen width, it only adds positive values. Finally I've tried to add some logic that says a platform can only be a certain height and distance away from another one whilst taking into account the previous platforms position, but its not really working.

Anyone got any ideas to tidy this up a little bit?


texts:
Is there a way to change the color of a specific pixel in C++? I've made an example project where I used graphics.h's bar to change every pixel on the screen:

#include <graphics.h>

int main( )
{
    initwindow(600, 600, "Example");
    for (int x = 0; x <= 600; x++) {
        for (int y = 0; y <= 600; y++) {
            bar(x,y,1,1);
        }
    }
    while (!kbhit( ))
    {
        delay(200);
    }
    return 0;
}

But this takes way to long like maybe 30 seconds. I was wondering if there was a way to do it faster, under a second. btw I'm using dev-c++.


texts: Compress / make Blender .obj file smaller

texts:
I have been learning the basics of blender for the best part of the day, and I still cannot figure out how to make models(imported) smaller in file size(where their original file size is 2MB+).

The reason why I want to make the files smaller is because I am trying to use them in my iPhone application, however the app crashes when the .obj files are over 1MB.

Could anybody please help me I have been at this for hours..


texts: C++ OpenGL - 2D Lighting Around Object in a Pitch-Black Environment

texts: I am making a 2D game in C++ with OpenGL where a maze is generated and you have to move the character through the maze and get it to the end. I have achieved all this, but now I want to make it more challenging by having everything pitch-black but a small light around the character. How can I achieve this? I don't want the light to be complicated and I don't want it to only go through the tunnels. I just want a simple light around the character to illuminate that area of the maze.


texts: How do I copy the depth buffer to CPU memory in Direct3D 9?

texts:
I have code in OpenGL that uses glReadPixels to copy the depth buffer to a CPU memory buffer:

glReadPixels(0, 0, w, h, GL_DEPTH_COMPONENT, GL_FLOAT, dbuf);

How do I achieve the same in Direct3D?

I have looked at a similar question which gives a solution for copying the color buffer. I've tried to write similar code to copy the depth buffer:

IDirect3DSurface9* d3dSurface;
d3dDevice->GetDepthStencilSurface(&d3dSurface);

D3DSURFACE_DESC d3dSurfaceDesc;
d3dSurface->GetDesc(&d3dSurfaceDesc);

IDirect3DSurface9* d3dOffSurface;
  d3dDevice->CreateOffscreenPlainSurface(
  d3dSurfaceDesc.Width,
  d3dSurfaceDesc.Height,
  D3DFMT_D32F_LOCKABLE,
  D3DPOOL_SCRATCH,
  &d3dOffSurface,
  NULL
);

// FAILS: D3DERR_INVALIDCALL
D3DXLoadSurfaceFromSurface(
  d3dOffSurface,
  NULL,
  NULL,
  d3dSurface,
  NULL,
  NULL,
  D3DX_FILTER_NONE,
  0
);

// Copy from offscreen surface to CPU memory ...

The code fails on the call to D3DXLoadSurfaceFromSurface. It returns the error value D3DERR_INVALIDCALL.

So, is something wrong with my code? How can I copy the depth buffer contents?


texts: Collision Detection algorithms with early Collision exit

texts:
I'm using collision detection in Monte Carlo simulations and at the moment I'm using GJK which is quite fast. I can't help to think it could be done even faster though. In the simulations, about 70% of the time GJK is run, it detects a collision. Thus collisions are more than non-collisions in my case. Most collision detection algorithms I know have an early non-collision exit test.

Are there any collision detection algorithms that have an early collision detect instead of non-collision and could be potentially faster than GJK in case of collision?


texts:
I am trying to implement a simple 2D camera in LWJGL3.

The camera has an orthographic projection and can move in 2D space.

This is run once at game start-up:

GL11.glMatrixMode(GL11.GL_PROJECTION);
GL11.glLoadIdentity();
GL11.glOrtho(0, graphics.window().width(), graphics.window().height(), 0, 1, -1);
GL11.glMatrixMode(GL11.GL_MODELVIEW);
GL11.glLoadIdentity();

This is run as part of the draw loop:

GL11.glMatrixMode(GL11.GL_PROJECTION);
GL11.glPushMatrix();
GL11.glTranslatef(-position.x(), -position.y(), 0f);

// Draw stuff

GL11.glPopMatrix();

Everything looks fine until I move the view, after which everything seems to be closer to the top left (0, 0) than it should be. It seems to be off by a scalar of the window size - the factor is greater in x than y.

How have I misunderstood the OpenGL commands?


texts: Confusion about systems implementation of ECS

texts:
For reference I am mostly imitating the architecture in this tutorial, the "Entity System" section: http://www.raywenderlich.com/24878/introduction-to-component-based-architecture-in-games

NOTE: the tutorial is in objective-c but I am using C++. Also, I only code the "happy case" for now because I am not sure if this is the architecture I am going with; I am simply experimenting.

Quick background: every time a system's update() function is called, the relevant system calls a helper method in EntityManager, getEntitiesWithProperty(), that returns a vector of all entities which possess a component(s) type that the system operates on.

template <class T>
std::vector<unsigned int> getEntitiesWithProperty()
{
    std::vector<unsigned int> ret;
    auto key = std::type_index(typeid(T));
    std::unordered_map<unsigned int, PProperty*> map = data[key];
    for(auto i = map.begin(); i != map.end(); i++)
    {
        ret.push_back(i->first);
    }
    return ret;
}

The system then iterates through this vector, calling yet another helper method in EntityManager per each element in the entity vector. This method returns a pointer to the component that is associated with the particular entity that is being iterated over, and the system performs its logic on the entity:

void SRender::update(EntityManager& entM, float frameTime)
{
    auto ids = entM.getEntitiesWithProperty<Image>();
    for(auto i = ids.begin(); i != ids.end(); i++)
    {
            Image* img = entM.getProperty<Image>(*i);
            draw(img);
    }
}

After I implemented this ECS I "stress-tested" it by simply drawing 300 sprites at differing x and y values, and was only able to get around 80 average fps doing absolutely nothing besides rendering.

I then altered the SRender system class and update method so that, instead of calling getEnt..() every frame, it only calls it upon system initialization and every time the EntityManager's component data structure changes size (i.e. entity deleted or created), and stores a vector of relevant components locally within the system as a member variable, like so:

   class SRender : public SSystem
   {
       private:
           ...
           std::vector<Image*> components
   }

Without update() calling the helper function every frame, rendering the same 300 sprites every frame I get an increase of 150 average fps. 1k sprites yield 100 fps; 20 fps faster the prior implementation.

My problem with this new approach is that there is no longer a separation of data from function, and that there are more pointers to deal with spread over systems instead of all being contained within the EntityManager, and it overall is just messier to deal with and more bug prone. But I don't know how else to increase performance. NOTE THAT there is nothing flawed from a performance standpoint regarding my rendering pipeline; I did the same initial test WITHOUT actually rendering anything, but simply iterating over each element returned by the helper method, and the fps was exactly the same (around 80 fps average) as it was making draw calls.

What other approaches can I take to improve performance? I have seen other ECS approaches doing the same thing as in the tutorial (returning relevant data structures from the entity manager on every update() call), so I don't understand why my implementation of it has poor performance. Maybe I am overlooking something, or misunderstanding the tutorial (I'm unfamiliar with objective-c)?


texts: Binding and unbinding, what would you do?

texts:
Let's assume the following example

creation:

glBindVertexArray(vao)
   glBindBuffer(GL_ARRAY_BUFFER, vbo)
   glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indices)

   // Filling up buffers

   glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0)
   glBindBuffer(GL_ARRAY_BUFFER, 0)

glBindVertexArray(0) // Unbinding vertex array

This looks great from a code-beauty perspective. Each bind-unbind-pair is like parenthesis, so {[()]} (I am also actually using these indentions)

But it also results in a more code for rendering, because the buffers are unbound in the vao, they need to be rebound during rendering, which kind of defeats the purpose of a vao which represents a certain state you can just use whenever you need to.

Rendering would need to look like:

glBindVertexArray(vao)
    glBindBuffer(GL_ARRAY_BUFFER, vbo)
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indices)
        // Do your drawing
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0)
    glBindBuffer(GL_ARRAY_BUFFER, 0)
glBindVertexArray(0)

so it would be better to

glBindVertexArray(vao)
   glBindBuffer(GL_ARRAY_BUFFER, vbo)
   glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indices)

   // Filling up buffers

glBindVertexArray(0) // Unbinding vertex array
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0)
glBindBuffer(GL_ARRAY_BUFFER, 0)

Just to make sure the buffers are not bound for another write or anything.
Code-wise this looks kind of ugly.

But rendering then is just

glBindVertexArray(vao)
 // Do your drawing
glBindVertexArray(0)

Regarding the cost, the second one uses less (un)bindings, but also it could happen that the vao is already unbound (during rendering) but the vbo and element-buffer is not, so one could write messy data in there.

Am I missing something? Which way is more error-prone? Are the costs for un/binding neglect-able and is the beauty of code worth it?


texts: Why are clicks not corresponding correctly to XY positions?

texts:
I'm trying to make custom buttons in LibGDX (I really only wanted to use it for the Android/Desktop portability, not for any of its features, like Scene2D)

The issue I'm having is that the clickable area and the texture don't have a 100% overlap. I can click some places in the texture that don't respond to my isClicked method, and there are places outside the texture that do. I just don't understand what's happening.

Here's my button  class.

public class btn
{
private Texture btnTexture;

private int x;
private int y;

private int width;
private int height;

public btn(String btnTexturePathSet, int xSet , int ySet)
{
    btnTexture = new Texture(btnTexturePathSet);
    x = xSet;
    y = ySet;
    width = btnTexture.getWidth();
    height = btnTexture.getHeight();

}

public void render(SpriteBatch sb)
{
    sb.begin();
    sb.draw(btnTexture, x, y);
    sb.end();
}

public boolean isClicked()
{
    if (Gdx.input.justTouched())
    {
        if (Gdx.input.getY() >= y && Gdx.input.getY() <= y + height && Gdx.input.getX() >= x && Gdx.input.getX() <= x + width)
        {
            return true;
        }

    }
    return false;
}
}


texts: How can I grab the script component of a collided object without knowing what script it is?

texts:
CalculateDamage() is an animation event called at a point during the character's animation in my 2D game. The commented out code is before I realized that not all of my pirates will be of class MeleePirateUnit, so I'm trying to do things more generically here. My order of inheritance is like so:

MonoBehaviour > Unit > MeleePirateUnit, RangedPirateUnit.

So sometimes, the collidedobj is a MeleePirateUnit, sometimes it's a RangedPirateUnit, etc etc. How do I set pirateUnit to the correct type of the script component of my gameObject? I thought just getting component of type monobehaviour would work since RangedPirateUnit and MeleePirateUnit both derive from monobehaviour but I'm getting an error of

Assets/Scripts/Combat Scene/RangedPirateUnit.cs(72,56): error CS1061: Type UnityEngine.MonoBehaviour' does not contain a definition forhealth' and no extension method health' of typeUnityEngine.MonoBehaviour' could be found (are you missing a using directive or an assembly reference?)

public void CalculateDamage(){
        if (!isDestroyed){
            var pirateUnit = collidedObj.GetComponent<MonoBehaviour>();
            //MeleePirateUnit pirateUnit = collidedObj.GetComponent<MeleePirateUnit>();
            pirateUnit.health = pirateUnit.health - (damage - pirateUnit.defence);
            if (pirateUnit.health<=0){
                Destroy(pirateUnit.gameObject);
                isDestroyed = true;
                didAttack = false;
            }
        }
    }


texts:
I was wondering if anyone had any links to good reads or books in regards to things to think about when developing a RTS game, I would have been reading things like this and this but would like to read more into it.

Also I have development experience and soon would like to start building the skeleton myself but if anyone has any additional articles about the process (not in programming, but more on planning) that would be great help.


texts: In Unity, what does the camera script's "Behaviour missing" error mean?

texts:
I started in Unity few days ago and made a cube with a tank control style. Now I'd like to create controls similar to 3D fighting games (Gunz, Blade Symphony, …): Control body direction with the mouse and walk with WASD.

However, the Camera is giving me a error called "Behaviour missing" each time I try, with all the cameras scripts I saw. I think that is a error with tagging the character movement in the camera, but I don't know how to do that.

What might be the problem?


texts: How can I pass an array of floats to the fragment shader using textures?

texts:
I want to map out a 2D array of depth elements for the fragment shader to use to check depth against to create shadows. I want to be able to copy a float array into the GPU, but using large uniform arrays causes segfaults in openGL so that is not an option. I tried texturing but the best i got was to use GL_DEPTH_COMPONENT

glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, 512, 512, 0, GL_DEPTH_COMPONENT, GL_FLOAT, smap);

Which doesn't work because that stores depth components (0.0 - 1.0) which I don't want because I have no idea how to calculate them using the depth value produced by the light sources MVP matrix multiplied by the coordinate of each vertex.

Is there any way to store and access large 2D arrays of floats in openGL?


texts:
For an html5 engine I'm making, for speed I'm using a path poly. I'm having trouble trying to find ways to get collision with the walls of the poly. To make it simple I just have a vector for the object and an array of vectors for the poly. I'm using Cartesian vectors and they're 2d.

Say poly = [[550,0],[169,523],[-444,323],[-444,-323],[169,-523]], it's just a pentagon I generated.

The object that will collide is object, object.pos is its position and object.vel is it's velocity. They're both 2d vectors too.

I've had some success to get it to find a collision, but it's just black box code I ripped from a c++ example. It's very obscure inside and all it does though is return true/false and doesn't return what vertices are collided or collision point, I'd really like to be able to understand this and make my own so I can have more meaningful collision. I'll tackle that later though.

Again the question is just how does one find a collision to walls of a poly given you know the poly vertices and the object's position + velocity? If more info is needed please let me know. And if all anyone can do is point me to the right direction that's great.


texts: How do games on Windows locate libraries?

texts:
I've always wondered how games handle libraries. What if you want to use a dynamic library in a game, let's say OpenGL.

You could just put it inside the /lib folder on Linux(-like), and have everything working properly; even better, on Debian systems you could just set it as a dependency.

How does this work on Windows?
There is no clear /lib directory, where do you put it?

Obviously you cannot ask the user to manually install the libraries!
Do you simply create a folder for it somewhere and add that to the PATH environment variable?
Or do you first check where other programs might have put it?

Is there a 'standard' to do this?


texts: What is the best way to handle "Fangame" licensing?

texts:
( I understand that this is a subjective question. My goal is obtaining some personal feedback from other game designers )

I wish to develop a digital version of an existing board game.
What would be the "best" course of action regarding contacting the original game designer?

Some additional information:

This is not a question about copyright. My understanding is that this is something that I can do as long as I do not use copyrighted material.
I have a recently obtained a  masters in informatics and computing engineering and have a serious interest in pursuing a career in game design and development.
The game in question is a board game for which there is no digital version on my medium of choice.


texts: How feasible is it to integrate a personality system such as the MBTI into a game?

texts:
Specifically, how difficult would it be for an indie developer to implement a system similar to the MBTI so that the player character's dialogue, actions, and choices will change, according to the assigned MBTI type?

This may be limited to the snarkiness of the player character's responses, the character being more reluctant to go to a social event, how well the character will respond to criticism, etc.

It would help to reference games that have done this or something similar.

EDIT: For those that don't know, the Meyers Briggs Type Indicator is a way of measuring someone's personality based on 5 variables, (the last of which is usually ignored) in order to get 16 (or 32, including the last variable) different archetypes.

Extraversion vs. Introversion determines if you 'regain energy' by interacting with others, being the centre of attention, etc. or by being alone, doing such activities as walking, reading, and introspection.

Sensing vs. iNtuition determines if you prefer to absorb new information by focusing on facts, statistics, and details, preferring ideas with practical applications, or imagining the possibilities, exploring concepts for their own sake, and looking at deeper meaning.

Thinking vs. Feeling determines if you make decisions using logic, value justice, enjoy finding flaws and playing devil's advocate, or base decisions on personal values, and are more about how things should be.

Judging vs. Perceiving determines if you use T/F attributes to interact with the world around you, or S/I attributes.

Perception tends to make people want to keep their options open, and make external dealing decisions on the spot, rather than in advance, while Judging tends to be linked to making a plan and sticking with it.

Then, there's Assertive vs. Turbulent, which determines confidence in decisions. Assertive individuals supposedly are less affected by stress, which has the side effect of it not affecting their performance that much, whereas Turbulence is related to perfectionism, completionism, and panicking.

People cannot be fitted neatly into 32 different categories, as many people are near the centre for some of the variables, and it is therefore better to consider these archetypes than actual categories that everyone falls into. If as well as left and right there was also a 'middle ground' classification, instead of 32 personalities, there would be 243.

The personality system in question would not have to be the Meyers Briggs, and indeed it probably should deviate from it in a few areas for copyright reasons. The purpose of giving the PC an in-game personality is so that the player can relate to them, not so they can emulate the player, so the Forer effect actually works in the Game Designer's favour.

How feasible is it, therefore, to integrate a system such as this into a game such as an RPG?


texts:
I have rendered a spinning model in LWJGL. I have calculated normals and enabled lighting. Now I make a light:

float lightpos[] = {0, 0, 0, 0};
FloatBuffer lightposb = BufferUtils.createFloatBuffer(8);
lightposb.put(lightpos);
glLight(GL_LIGHT0, GL_POSITION, lightposb);
float light[] = {10, 10, 10, 1};
FloatBuffer lightb = BufferUtils.createFloatBuffer(8);
lightb.put(light);
glLight(GL_LIGHT0, GL_SPECULAR, lightb);
glLight(GL_LIGHT0, GL_DIFFUSE, lightb);
glLight(GL_LIGHT0, GL_AMBIENT, lightb);

The model, instead of being lit up, is a dark gray. Also, no color appears on the model, even though I set its color to cyan:

    float color[] = {0,1,1,1};
    FloatBuffer colorb = BufferUtils.createFloatBuffer(8);
    colorb.put(color);
    glMaterial(GL_FRONT, GL_AMBIENT, colorb);

UPDATE: Even though I have calculated normals and set them with glNormal3f, the model still appears to be shaded flat.

UPDATE: I HAVE done glEnable(GL_LIGHTING) and glEnable(GL_LIGHT0); that is NOT the problem.

UPDATE: I reversed the order of the light code and the model code and now the model flashes white, then goes dark grey and stays there.


texts: Why do I get an unexpexted token error while compiling this shader?

texts:
I get the following error

  syntax error unexpected token vertex

I am still learning shaders so I can't really understand the reason for this error.  How can I make this shader work?

enter Shader "Custom/VertAnimShader"
{
    Properties
    {
        _MainTex("Texture", 2D) = "white" {}
        _PosTex("Position texture", 2D) = "black" {}
        _NmlTex("Normal texture", 2D) = "white" {}
        _Length("Animator lengh", float) = 1
        _DT("Delta time", float) = 0
    }

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

            #define ts _PosTex_TexelSize

            struct appdata
            {
                float2 uv : TEXTCOORD0;
            };

            struct v2f {
                float2 uv : TEXTCOORD0;
                float3 normal: TEXTCOORD1;
                float4  vertex : SV_POSITION;
            };

            sampler2D _MainTex, _PosTex, _NmlTex;
            float4 _PosTex_TexelSize;
            float _Length, _DT;

            v2f vert(appdata v, uint vid: SV_VertexID)
            {
                float t = (_Time.y - _DT) / _Length;
                t = fmod(t, 1.0);
                float x = (vid + 0.5) * ts.x;
                float y = t;
                float4 pos = tex2Dlod(_PosTex, float4(x, y, 0, 0));
                float4 normal = tex2Dlod(_NmlTex, float4(x, y, 0, 0));
                v2f o;
                o.vertex = UnityObjectToClipPos(pos);
                o.normal = UnityObjectToWorldNormal(normal);
                o.uv = v.uv;
                return o;
            }

            half4 frag(v2f i) : SV_TARGET
            {
                half diff = dot(i.normal, float3(0,1,0))*0.5 + 0.5;
                half4 col = tex2D(_MainTex, i.uv);
                return diff * col;
            }
            ENDCG
        }
    }
}


texts:
I made this 3D model of sonic in Blender complete with its own rig for animating. I would like to use this for testing 3D movement in unity along with the animator tool. However, when I export the fbx file to my unity project it shows up as intended with the armature and the mesh, however, moving the individual components of the rig have no effect on the mesh? I'm not sure why this isn't working like blender, any help  in regards to reading material or any options I have left unchecked that prevent this from working would be greatly appreciated!
I know I havent given much information here, but I havent been able to find a good tutorial on any of this that doesnt involve importing animations from another program, I just want to be able to rig and animate a model I made in blender using Unitys animator tool.


texts: OpenGL Slow rendering of half a million points on Windows

texts:
How can I speed up the drawing of my points in OpenGL on Windows?

I have an Qt 5.9.1 app that shows real time Lidar data, so at a certain frequency I add points to my buffer (which I've overloaded to act as a circular buffer.)

On linux, everything is great, all my renderers combined (my lidar points, my 3D models, etc) render in a small fraction of a 60 FPS frame.  On Windows however, rendering the lidar points takes almost the time of two 60 FPS frames.  I measured this put inserting glFlush() and glFinish() after the glDrawArrays() calls.

My buffer size is about ~1/2 a million points.  I'm trying to show points that could span several km, but are usually confined to 1 km - I mention this because right now I'm not doing any explicit frustum culling.

My process is:

Load new points from a vector into my overloaded circular OpenGL buffer.  Each point is 20 bytes (position, intensity, ..)
Write all my uniform variables (MVP matrix, etc)
Call glDrawArrays
Then there's a vertex shader that just passes data through
A geometry shader that instances the points for each viewport (3)
A fragment shader that colours the points by elevation.

Explicitly:

Initialize:

auto LidarRenderer::initPointShaders() -> void
{
    point_opengl_buffer_.setUsagePattern(QOpenGLBuffer::DynamicDraw);
    initializeOpenGLFunctions();

    // Setup our vertex buffer object.
    point_opengl_buffer_.create();

    render_program_ = make_unique<QOpenGLShaderProgram>();

    // Vertex shader pretty much just passes points through
    render_program_->addShaderFromSourceFile(QOpenGLShader::Vertex,   vertex_shader_);
    render_program_->addShaderFromSourceFile(QOpenGLShader::Geometry, geo_shader_);
    render_program_->addShaderFromSourceFile(QOpenGLShader::Fragment, fragment_shader_);

    render_program_->link();
    render_program_->bind();

    // Store the vertex attribute bindings for the program.
    {
        // Create our QOpenGLVertexArrayObject
        vao_.create();
        QOpenGLVertexArrayObject::Binder vaoBinder(&vao_);

        // Bind out buffer
        point_opengl_buffer_.bind();

        glEnableVertexAttribArray(0);
        // Vertex position data, send to location = 0, 3 floats per position,
        // not normalized, stride of 20 bytes, no offset
        glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 20, 0);

        glEnableVertexAttribArray(1);
        // Vertex intensity data, send to location = 1, 1 int, stride of 20
        // bytes, 12 byte offset
        glVertexAttribIPointer(1, 1, GLint, 20, 12);

        // ...

        point_opengl_buffer_.release();
    }

    render_program_->release();
}

Load new points (write to buffer):

auto LidarRenderer::loadNewPoints() -> void
{
    if (!point_opengl_buffer_.bind()) return;

    auto point_count = tmp_buffer_.size();

    // Transform the points into the proper frame
    std::transform(tmp_buffer_.begin(), tmp_buffer_.end(), tmp_buffer_.begin(),
        [&my_nav_offset_vector_](const RegisterPoint& p) { return p - my_nav_offset_vector_; });

    point_opengl_buffer_.write(&tmp_buffer_[0], static_cast<unsigned int>(point_count * sizeof(RegisterPoint)));
    point_opengl_buffer_.release();

    // Clean our vector
    tmp_buffer_.clear();
}

Paint:

auto LidarRenderer::paintGL() -> void
{
    QOpenGLVertexArrayObject::Binder vaoBinder(&vao_);
    render_program_->bind();

    // Draw all the ground points in the buffer
    glDrawArrays(GL_POINTS, 0, static_cast<GLsizei>(point_opengl_buffer_.CountVertices()));

    render_program_->release();
}

Does anything in that code look wrong?  Is there a way to possibly speed up the rendering? (I should mention that I'm still an OpenGL beginner.)


texts: opengl offscreen rendering in linux is slow

texts:
My opengl application runs at about 110 fps. The moment I add off-screen rendering, it slows down to 15 fps. I am using frame buffer objects and glReadPixels to render off-screen. I have searched on net and found that GPU memory to CPU memory data transfer is slow and vice versa is fast. I have ATI Mobility Radeon™ X2300 with 128MB video memory.
So my questions are
1) Is there is way to increase VRAM to CPU ram data transfer speed?
2) Are there any GPUs in market optimized for better read speed?


texts: How do I make an arrow line up with a bow when rotating them?

texts:
I am trying to create a bow and arrow animation in which the player can drag downwards to increase the bow strength (see the image) and release it to hit a target. I can't get the arrow to align with the bow when the arrow's height is changed (third image). I am rotating both the bow and arrow around their respective origins (w/2, h/2).

What is the correct way to do it?


texts:
I'm curious because I was thinking that displacement mapping is done in the shader file only inside the domain shader. Am I correct or is it both implemented in the rendering section of the mesh and shader? So, if I make a cube for an example, I would have to read out the displacement map file then tell what vertices get positioned inside the render or only in the shader file? I'm a bit stuck on that concept.

These are the snap shots done inside the game editor of a plane. I believe the issue lies within the texture but you can always correct me.

This texture was created for the box inside 3DS Max and the UV Mapped, then baked the image.

When I load a sphere, not so much crazy gaps but it's still hasty.


texts: Pixel-perfect collision against rotated sprite in Flixel

texts:
I've got a roughly 500x50 graphic of a lockpick that I need to be able to rotate very finely while doing pixel-perfect collision detection against the lock object.

There's no way to do pixel perfect collision detection in Flixel, so I'm using the Power Tools' FlxCollision class to accomplish this. The problem is that this class only works with rotated sprites if they were loaded with loadRotatedGraphic.

...the problem with that is that it only allows you to rotate to discrete angles. You pass it how many angles you need to be able to rotate to and it, I think, pre-prepares all the frames for you.

And the reason that's a problem is because I need such fine rotation. I need at least 128 different angle values, but when I do that I get Error 2015: Invalid Bitmap, which I'm assuming is because the resulting 128 frames of a 500x50 lockpick results in a bitmap larger than AS3's limit. I can load the graphic using loadGraphic instead, which I think just calculates the rotated image real-time, but then FlxCollision won't notice that it's been rotated. Another problem is that with the pre-rotated graphics, you can't rotate about a specific point, and I need the lockpick to rotate around the tip of its handle.

...so how the heck do I do pixel perfect collision against a rotated sprite? I'm trying to mod FlxSprite so that FlxCollision will see the rotated sprites even when they're calculated in real time, and to do this I Ctrl+F'd through the class looking for appearances of "angle", the variable that you set to rotate a sprite, but all I can find is some obscure calculation in it's used to compute a frame number, and I can't find a single call to any function that looks like it's doing real-time bitmap rotating.

So, I was able to solve this problem. All FlxSprites hold the bitmap for their currently visible frame in an internal variable called framePixels. If you load a graphic using loadGraphic, then you can do real-time rotation: in this case, the draw() function rotate s framePixels "at the last minute", right before rendering it. Meaning the rotated bitmap is not stored, and FlxCollision has no way of seeing it. FlxCollision runs its collision checks against the unrotated bitmap.

So this is what need to be done:

Get the sprite to store its rotated graphic somewhere rather than just sending it to the renderer and then abandoning it.
Get FlxCollision to use that stored rotated graphic rather than framePixels.

This is summarized in the following diagram. Flixel's default logic is in black, my changes are in red.

I applied all of this in a sub-class of FlxSprite that I called PerfectCollisionSprite.

Here's my code.


texts: I am thinking of making 3d games with 2d pixels feel. So far, i have been playing around in tiled and monogames. I learned some xml and managed to import and render tmx into my game. This is maybe a dumb question. How do you convert tmx into 3d texture? What kind of software do you need?


texts:
I try this:

workspace.Terrain:FillRegion(Region3.new(Vector3.new(2048, -256, 2048), Vector3.new(-2048, -512, -2048)):ExpandToGrid(4), 4, Enum.Material.Basalt)

I get the error Region cannot be empty. What gives? Of course the region is empty, I am trying to change that. Is :FillRegion() broken?


texts:
I am learning jMonkeyEngine by making some small games with it. I have a simple rectangular cube that I want the player to be able to roll around the game world.

When he presses the arrow keys, the cube should make a roll in the direction of the key press. (So, for instance, pressing the right arrow key makes the cube roll 1 WU to the right.)

The problem isn't how to move the cube (I can do that with the move() method), but with how to make this rotation effect so it doesn’t look like the cube is moving to the destination, but is actually rolling.

The rolling effect should be like the cube in Bloxorz. (Here's a gameplay video.)

UPDATE

After I got some good help below, I have come up with a test solution, which I want to share with you.

Box box1 = new Box(1,1,1);
Geometry boxGeom = new Geometry("Box", box1);
Material mat1 = new Material(assetManager, "Common/MatDefs/Misc/Unshaded.j3md");
mat1.setColor("Color", ColorRGBA.Blue);
boxGeom.setMaterial(mat1);

//attach the cube to the pivot node
pivot = new Node("pivot");
pivot.setLocalTranslation(0.0f, 0.0f, 0.0f);
rootNode.attachChild(pivot); // put this node in the scene

pivot.attachChild(boxGeom);

//Translate the box so the pivot node is at the bottom right edge of the box
boxGeom.move(-1.0f, 1.0f, 0.0f);

And then rotate it like this.

@Override
public void simpleUpdate(float tpf) {
    //rotate along z-axis
    pivot.rotate(0.0f, 0.0f, -0.001f);
}


texts: What good books are there on level design?

texts:
I am trying to learn a bit of level design. The type of game I am most interested is 2D puzzle games similar to Cut The Rope for iPad. However, literature on general level-design for different genres would be very welcomed.

A internet quick search brings.

http://www.amazon.com/Art-Game-Design-book-lenses/dp/0123694965/ref=pd_sim_b_5

http://www.amazon.com/Game-Level-Design-Development/dp/1584503696

Anyone can recommend those or any other resources? books, recorded conferences, examples, tutorials, slides..


texts: I'm a single developer making a game made of blocks. Can I make 3d characters made of blocks without looking like Minecraft?

texts: I would like to differentiate the look as much as I can but yet it has to be within the limits of what is reasonable for a single programmer can do.  I have alot of ideas that would make the game itself different but I'm afraid the look of the blocky world and blocky characters are going to be too much like Minecraft.  I've toyed around with the idea of giving the characters big heads, or skinny bodies, or elbows and knees.


texts:
I built out my project to Android to do some testing and stuff, but I can't get any further than the main menu scene. I built it out previously and it was running fine. Now as I try loading level0 it crashes with no error messages from adb logcat. Just exits the game and that's it. It works fine in the editor.

I tried several things. I changed the color space back and forth, I built my addressables, tried development built and non development one, and the Split application binary checkbox is false as well...

Unity 2019.2

My adb catlog output


texts: In Unity, how do I render a chromatic aberration effect?

texts:
I'd like to replicate the effect used in Teleglitch:

In this scene, an object is rendered more than once at different position with different color.

This game uses this shader effect to create impact. Whenever an object with high velocity moves or hits, this distortion is rendered to give more weight to the moment.

If I had complete control over rendering cycle, I would have re-drew all the in-game objects with different color and position.

However, in Unity, rendering is done via Renderer and I am not sure how to apply this effect to all objects in the game (except the world, so I cannot do post processing).

How can I do this?


texts: drag and drop a specific image to a specific panel and picture should not drop anywhere else except in that panel

texts: hi guys i'm building a drag and drop in unity and I have panels and images so for example I want the bank image to drop in the panel that has bank text in it and that image shouldn't drop anywhere else please help


texts: Allowing a player to walk up and down slopes without resistance

texts:
I am trying to implement a platformer where both the player and the level are made up of arbitary polygons. One requirement is that the player can stand still on slopes, and walk up and down them freely without resistance.

For collision detection, I have been using the Separating Axis Theorem (SAT) to calculate overlap between the player and environment. The problem is with the resolution phase. The SAT gives the axis of minimum overlap and the amount you need to move an object along the normal in order to resolve this overlap. This method leads to the player sliding downwards when gravity is applied on a slope, or encountering resistance when moving horizontally into a slope.

To solve this, I want to resolve the collision by applying the minimum y-offset:

And an answer to a similar question here seems to provide some of the ground work of how to do it, but I don't feel I have all the information I need. How would such a method work for arbitary polygons? From which point do I need to be calculating the overlap from? Do I have all the information I need already from calculating the separating axis or do I need to compute further values?


texts:
I've designed and textured a house, and I now want to port it over to ArmA 3. I'm using blender to design it.
When looking at tutorials, everyone seems to emphasize the LOD, which means Level of Detail. (Shown on the right) I have no clue what settings to use for a structure. The only tutorials i've seen are creating a weapon, which I'm assuming would need a low LOD since its in 1st person, but no one mentions the LOD settings of buildings, what value should I use?


texts: How to efficiently organise all object in a large space

texts:
I've just about started with a project I've had in mind for ages. I don't quite know how to start such big projects (bigger than Pong, anyway), so I thought I would get started by making a basic organization.

Now, in games like Freelancer and X feature large, open spaces. I ma aware that these have to be organised, to ensure collision testing don't happen continuously anywhere but only where the player can see it.

I thought first about a general scene graph, I am familiar with those, but it would just have almost all objects directly in the root node. The next idea was a Quad/Octree, but the objects are not quite static, and I don't know if it would make sense if you have to change the tree's organisation every second frame.

So, how is this done in real games? I'm using C# with XNA, if that matters, and would like to run the game on the XBox as well.


texts: If my camera does not change position but rotates, Does adding lerp do anything?

texts:
If my camera does not change position but rotates, Does lerp do anything?

        cameraposition = Vector3.Lerp(Camera.main.transform.position, Camera.main.transform.position, Time.deltaTime * cameraLerp);
        Camera.main.transform.position = cameraposition;
        Camera.main.transform.LookAt(gameobject.transform.position);


texts: LibGdx: search through text file without lots of String garbage

texts:
I'm reading a text file from Gdx.files.internal in LibGdx. This is essentially streaming a file from a compressed Jar file so random access is not possible.

I want to search through the text file line by line until I get to the bit I want. That's easy enough, but I want to do it without generating loads of Strings and leaving lots for the GC to clean up.

Whats the best way of scanning through the file without creating object garbage?


texts: Why does my camera break mouse position targeting?

texts:
I made a short video of this.

Basically, when the screen scrolls with the camera, the character begins firing at the incorrect mouse position. You can see where I am clicking the whole time. As we move towards the right edge (the more we scroll), you'll notice the distance away from the correct position increases. The shooting mechanic worked just fine before I added the camera.

I'm using a translation matrix to implement my camera.

What could be causing this?


texts: Why does transforming a Vector3 by a Quaternion result in reversed Z?

texts:
I'm trying to transform the vector (1, 0, 0) by an orientation unit quaternion, which in XNA should be:

Vector3 v = Vector3.Transform(Vector3.Right, Orientation);

But this results in the Z value reversed from its expected value—for example, transforming Vector3.Right by Orientation (0.6532815, -0.270598, 0.270598, 0.6532815) results in the vector (0, 0.7071, -0.7071) when it should result in the vector (0, 0.7071, 0.7071).

I found another implementation here:

Quaternion o = Orientation;
Vector3 oV = new Vector3(o.X, o.Y, o.Z);
Vector3 v = 2 * Vector3.Cross(oV, Vector3.Right);
v = Vector3.Right + o.W * v + Vector3.Cross(oV, v);

But that results in the same problem. Reversing the Z value is trivial, but I'm worried that if I don't find a solution to this now the problem will manifest some other way down the road. Especially since, up until now, I thought I was playing by XNA's rules in my game engine (same coordinate system, same handedness).

For reference, this code I wrote does produce the expected result in my engine:

Vector3 v;
Quaternion o = OrientationGlobal;
double y = Math.Atan2(2 * (o.W * o.Z + o.X * o.Y), 1 - 2 * (o.Z * o.Z + o.Y * o.Y)); // yaw about global Z axis
v.Z = MathHelper.Clamp(2 * (o.W * o.Y - o.Z * o.X), -1, 1);
double m = Math.Sqrt(1 - v.Z * v.Z);
v.X = (float)(m * Math.Cos(y));
v.Y = (float)(m * Math.Sin(y));

What am I missing?


texts:
I'm currently using the Google Cardboard SDK for Unity to build a fighter pilot simulator. What I'm currently trying to do is recenter the view(CardboardHead) smoothly over time when the user looks away from the screen. This is because I want to put HUD elements out of the main central view that can be quickly seen with a "head jerk". I don't want to let the camera be free from constraints because I feel piloting is much better when the view is fixed and doesn't wobble about with every slight movement of the player's head. The Head already has a horizontal constraint that does not allow any later movement, but now I want to put a semi-constraint on the vertical axis so that the player can quickly look up or down to see something like i.e. a fuel economy indicator and then have the view quickly "follow his gaze" and recenter itself.

I noticed that the Cardboard plugin already does this type of constraint on the Head roll input when playing "in editor" and works as follows:
When you press and hold Ctrl and move the mouse left/right the  view rolls left/right. Upon release of Ctrl the view smoothly rolls back to 0.
This is the code in the Cardboard script:

bool rolled = false;
if (Input.GetKey(KeyCode.LeftControl) || Input.GetKey(KeyCode.RightControl)) {
      rolled = true;
      mouseZ += Input.GetAxis("Mouse X") * 5;
      mouseZ = Mathf.Clamp(mouseZ, -80, 80);
    }
    if (!rolled && autoUntiltHead) {
      // People don't usually leave their heads tilted to one side for long.
      mouseZ = Mathf.Lerp(mouseZ, 0, Time.deltaTime / (Time.deltaTime + 0.1f));
    }
    var rot = Quaternion.Euler(mouseY, mouseX, mouseZ);
    var neck = (rot * neckOffset - neckOffset.y * Vector3.up) * NeckModelScale;
    headView = Matrix4x4.TRS(neck, rot, Vector3.one);
  }

How could I implement this for vertical rotation of the Head?

In the Update method of the script that controls the Head it simply does transform.localRotation = Cardboard.SDK.HeadRotation;

This is what I've tried but it doesn't really do anything except some jerky movements:

transform.Rotate(new Vector3(Mathf.Lerp(rot.eulerAngles.x, 0, Time.deltaTime / (Time.deltaTime + 0.1f)),0,0));

(I put this in the same Update function for the Head after the above line)

Any ideas??


texts:
I have an RPG game where players can fight monsters limitless, and can get drops from these monsters.

Currently I store in my database a table called monster_drops with find_rate column which is a number between 1 to 10,000.  Whenever a player kill a monster, a number is generated and if it's lower from the current number stored in the monster find_rate column, he gets the item.

For example, if the find_rate of the item will be 10k, he will get the item every monster.
If the find_rate will be 1k, there is 10% chance he will get it.

My question- is there any better way, maybe simpler, or more accuarate, to calculate and set item drops?


texts: Why is the sprite so offset from the physics body?

texts:
I'm trying to make a sprite object that has physics, but once the game runs the physics body is drawn at an unknown offset from the sprite, which varies based on the size of the sprites texture.

Physics Sprite class:

public class PhysicsSprite extends Sprite {
World world;
public Body body;

public PhysicsSprite(Texture texture, World PhysicsWorld, float x, float y){
    super(texture);
    this.world = PhysicsWorld;
    setPosition(x,y);
    setOrigin(getX(),getY());
    InitializeBody();
}

private void InitializeBody(){
    BodyDef bd = new BodyDef();
    bd.position.set((getX())/GameMain.PPM,(getX())/GameMain.PPM);
    bd.type = BodyDef.BodyType.DynamicBody;

    body = world.createBody(bd);

    PolygonShape shape = new PolygonShape();
    shape.setAsBox(getWidth()/2f/GameMain.PPM,getHeight()/2f/GameMain.PPM);

    FixtureDef fd = new FixtureDef();
    fd.density = 1;
    fd.shape = shape;
    Fixture fixture = body.createFixture(fd);

    System.out.println(body);
}

private void updateSprite(){
    setPosition(body.getPosition().x*GameMain.PPM,body.getPosition().y*GameMain.PPM);
    setRotation((float)Math.toDegrees((double) body.getAngle()));
}

@Override
public void draw(Batch batch){
    updateSprite();
    super.draw(batch);
}
}

physics world/rendering scene class:

public class TestLevel implements Screen {
World world = new World(new Vector2(0f,0f),true);

OrthographicCamera camera = new OrthographicCamera(GameMain.WIDTH/GameMain.PPM, GameMain.HEIGHT/GameMain.PPM);
Box2DDebugRenderer debugR = new Box2DDebugRenderer();
PhysicsSprite s;
GameMain game;
SpriteBatch batch;

public TestLevel(GameMain g){
    game = g;
    batch = g.batch;
    s = new PhysicsSprite(new Texture("badlogic.jpg"),world,300,500);
}
@Override
public void show() {

}

@Override
public void render(float delta) {

    Gdx.gl.glClearColor(.4f,0.4f,.4f,1);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

    batch.begin();
    s.draw(batch);
    batch.end();

    debugR.render(world,camera.combined);
    world.step(Gdx.graphics.getDeltaTime(),6,2);
}

@Override
public void resize(int width, int height) {

}

@Override
public void pause() {

}

@Override
public void resume() {

}

@Override
public void hide() {

}

@Override
public void dispose() {

}
}

I've followed this tutorial and he mentions the sprite being offset but nothing occurs to him like whats happening here. I've tried to find someone with a similar issue but failed. Can someone help me out?


texts: calculating occlusion in cube voxel engine

texts:
This is more a conceptional (approach) question then the search for an implemented solution, since I was unable to find proper hints via google or similar.

The problem is as follows:

Given you have a 3D world that is encoded as voxels. So basically you have your 3D matrix were each position in the matrix is either solid or void ( for simplicity ). Now you look with your camera onto this cloud form a given ( in my case fixed for an isometric perspective ) angle. For each non void coordiante I draw an isometric projected block ( due to my choosen fixed camera angle ), while leaving void coordinates empty.

Of corse I want ot omit to draw coordiantes that are not vissible, so I alread exclude coordiantes that the camera would not see. But I also want to omit coordinates that would be hidden by other blocks, which are in the perspective closer to the camera.

I currently solve this by choosing a specifc camera angle that ensures that a block at coordiantes 0,0,0 would occlde a block at -1,-1,-1; -2,-2,-2; -3,-3,-3; and so on ( is that clear enought or should I add an image to explain? ). This is a rather cheap trick but it works and makes rendering faster as I have only to do a trace for each visible coordiante on the screen and draw the first non void coordinate in that trace. I saw this solution also used in Gnomoria for instance.

But I am wondering, if anyone has some keywords or hints if there is a more general approach to solve this occlusion problem without falling back using cheap camera tricks.


texts: What are some techniques used for mouse tracking, with a bit of "emulated lag"?

texts: I am trying to implement a system, where the cursor (in my case the player's avatar) is always about 1.5 seconds (a configurable interval) behind where the mouse actually is. If I change the cursor's location every time through, I get an emulated mouse cursor with no delay, I'm wondering if there are any pre-canned type of solutions I can throw at this before I "roll-my-own." Source code or even just basic steps you've used would be helpful.


texts: How to allow to slide rectangle to not colliding with corners between two rectagles?

texts:
I am detecting each side of collision between two rectangles, and wen I collide them, lets say, with the left side, it also detects collision on the top side when I move to the top, and the downside when I move to the bottom. I think that is because it is detecting also the top/bottom corners.

How I can prevent this corner collision to allow to the player to slide?

Currently, my code is the next one (using xMove (-1 or 1) and yMove (-1 or 1) to know the player movement direction.

    if (collider.intersects(mapCollider)) {

            if (direction == Direction.WEST || direction == Direction.EAST) {
                // Right collision
                if (collider.x + collider.width >= mapCollider.x) {
                    isCollisionRight = true;
                }
                // Left collision
                else if (collider.x <= mapCollider.x + mapCollider.width) {
                    isCollisionLeft = true;
                }
            }

            if (direction == Direction.NORTH || direction == Direction.SOUTH) {
                // Top collision
                if (collider.y + collider.height >= mapCollider.y) {
                    isCollisionTop = true;
                }
                // Bottom collision
                else if (collider.y <= mapCollider.y + mapCollider.height) {
                    isCollisionBottom = true;
                }
            }

Best regards,
Thank you in advance.


texts: Moving CCNode with constant speed in cocos2d

texts:
I want to move the object (CCNODE) with constant speed in any direction , what i have did till now is applied a force to object at start to get it moving and set elasticity as 1 and friction as 0 to every object which it will collide .

After some time speed goes on increasing , is there any way so i can check if speed increased so that i can control it or to apply velocity instead of force .  Thanks !


texts: Using XAudio2 to Process Microphone Input

texts: I am trying to come up with a solution to process microphone input for a game. Not entirely sure where to start. I was looking into using XAudio2, but it doesn't seem to have support for microphone processing? Is this correct? What do most companies in the industry currently use?


texts: why is my (from example) shader appearing as black?

texts:
I have the following (very simple) shader:

#pragma kernel CSMain
RWTexture2D<float4> Result;

[numthreads(8,8,1)]
void CSMain (uint3 id : SV_DispatchThreadID)
{
    Result[id.xy] = float4(1,0,0,1);
}

Here is the dispatcher code:

using UnityEngine;
using System.Collections;

public class SkyShaderDispatcher : MonoBehaviour {

    public ComputeShader shader;
    public RenderTexture output;
    void Start(){
//      RenderTexture output = new RenderTexture(256,256,24);
//      output.enableRandomWrite = true;
//      output.Create();

    }
    void Update(){
        RunShader();
    }
    void RunShader()
    {
        int kernelHandle = shader.FindKernel("CSMain");
        shader.SetTexture(kernelHandle, "Result", output);
        shader.Dispatch(kernelHandle, 256/8, 256/8, 1);
    }
}

which is the default red shader (it makes the texture red).
However, when I put the texture in a material and give that to an object, then that results in the object being black. Anyone seeing what I'm doing wrong?

As the shader is the default example right now it should work suggesting that maybe something is wrong with the texture?

Edit:
Trying to fit the same code on a skybox also fails. I have changed the dispatcher code into:

using UnityEngine;
using System.Collections;

public class launchClouds : MonoBehaviour {

    public ComputeShader shader;
    private RenderTexture output;
    void Start(){

    }
    void Update(){
        RunShader();
    }

    void RunShader()
    {
        int kernelHandle = shader.FindKernel("CSMain");
        RenderTexture output = new RenderTexture(256,256,24);
        output.enableRandomWrite = true;
        output.Create();
        Material mat = gameObject.GetComponent<Skybox>().material;
        mat.SetTexture("_FrontTex",output);
        mat.SetTexture("_BackTex",output);
        mat.SetTexture("_LeftTex",output);
        mat.SetTexture("_RightTex",output);
        mat.SetTexture("_UpTex",output);
        mat.SetTexture("_DownTex",output);
        shader.SetTexture(kernelHandle,
                          "Result", output);
        shader.Dispatch(kernelHandle, 256/8, 256/8, 1);
    }
}

but that turns the sky black rather then making the sky red. This is using unity 5 32 bits with DirectX11.


texts:
John Carmack has a tweet:
"Triple buffering adds latency and jitter; it should be avoided. The Answer is non-isochronous display updates."
Can anyone explain what he meant by adds latency and jitter?


texts: What's the most efficient way to find the intersection point of a missile and a bitmap terrain?

texts:
Following up on my earlier question about finding the slope of a 2D bitmap terrain I now need to know the best way of finding the point on the 2D terrain that the missile hit. Obviously, I can see if any pixels under the missile intersect terrain, but say it has moved quite deep into the terrain.

What is the best way to step back to find where it initially collided? I could move back X pixels at a time towards the missile's previous position, but what would be a good value of X? And is there a smarter way? Maybe moving half the distance, then a quarter etc?


texts: How do I draw video frames onto the screen permanently using XNA?

texts:
I have an app that plays back a video and draws the video onto the screen at a moving position. When I run the app, the video moves around the screen as it plays. Here is my Draw method...

    protected override void Draw(GameTime gameTime)
    {
        Texture2D videoTexture = null;

        if (player.State != MediaState.Stopped)
            videoTexture = player.GetTexture();

        if (videoTexture != null)
        {
            spriteBatch.Begin();
            spriteBatch.Draw(
                    videoTexture,
                    new Rectangle(x++, 0, 400, 300),  /* Where X is a class member */
                    Color.White);
            spriteBatch.End();
        }

        base.Draw(gameTime);
    }

The video moves horizontally acros the screen. This is not exactly as I expected since I have no lines of code that clear the screen. My question is why does it not leave a trail behind?

Also, how would I make it leave a trail behind?


texts: Touching screen not working for move object or print message

texts:
It's simple, i want to move an object when i touch the screen, but code's not working, i tried to just put a console printing on it, but nothing happens:

void Update()
{
   if (Input.touchCount > 0)
   {
     Debug.Log("Touch");
   }
}

What am i doing wrong ?, thanks in advance !!


texts: What is causing these visual artifacts on my OpenGL sprites?

texts:
What could be the cause of the defects in my characters sprite? I am using OpenGL ES 2.0. I draw my sprites in a sprite batch that uses UV coordinates from one large texture atlas. If you look around the character' edges, you'll see two noticeable problems:

The invisible alpha background is not invisible, but shows a strange static-like background.
There are unwanted streaks  where the character nears the edge of the frame (but only in some frames of the animation, this happened to be one of them).

Any idea what could be causing these? I will provide related code if asked for, but I'll try to avoid just dumping the entire project and expecting someone to look through it all.

EDIT: Here's a bit of code:

This is how I generate my UV coordinates:

private float[] createFrameUV(int frameWidth, int frameHeight, int x, int y){

    float[] uv = new float[4];

    if(numberOfFrames>1){
        float width = (float)frameWidth / (float)mBitmap.getWidth();
        float height = (float)frameHeight / (float)mBitmap.getHeight();
        float u = (float)x / (float)mBitmap.getWidth();
        float v = (float)y / (float)mBitmap.getHeight();

        uv[0] = u;
        uv[1] = v;
        uv[2] = u + width;
        uv[3] = v + height;
    }else{
        uv[0] = 0f;
        uv[1] = 0f;
        uv[2] = 1f;
        uv[3] = 1f;
    }

    return uv;
}

These are some OpenGL settings:

GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_LINEAR);
    GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_LINEAR);
    GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_S, GLES20.GL_CLAMP_TO_EDGE);
    GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_T, GLES20.GL_CLAMP_TO_EDGE);


texts: Centre of mass not recalculated after scaling

texts:
I am spawning a prefab object at runtime (actually, in the Start() method of another object), and I need to apply a scaling to the object. I made a little component to handle this:

public class Spawner : MonoBehaviour {

  public Transform SpawnPrefab;
  public Vector3 Scale;

    void Start () {
      var spawn = Instantiate(SpawnPrefab, Vector3.zero, Quaternion.identity);
      spawn.localScale = Vector3.Scale(spawn.localScale, Scale);
      // spawn.GetComponent<Rigidbody>().ResetCenterOfMass();  // Has no effect
    }
}

The pivot point of the prefab I am spawning does not coincide with the centre of mass of the object. Therefore, the rescaling means that the centre of mass location relative to the pivot will change. However, it's not being updated automatically, so my spawned object has unexpected physics.

I tried adding a call to GetComponent<Rigidbody>().ResetCenterOfMass() immediately after the call to Scale()  (the commented-out line above), but this has no effect.

However, if I put the call to ResetCenterOfMass() in the Start() method of a separate little component added to the spawned object, e.g.

public class COMReset : MonoBehaviour {
  void Start() {
    GetComponent<Rigidbody>().ResetCenterOfMass();
  }
}

this does cause the centre of mass to be recalculated correctly. However, the spawned object appears to have already been through at least one physics update with the wrong COM by this time, and so has already acquired some unexpected momentum.

Why isn't the COM being automatically recalculated, without me having to call ResetCenterOfMass() explicitly? And if I must trigger it manually, can I do that immediately after the calls to Instantiate() and Scale(), rather than deferring like this?


texts: How to programmatically change sprite sheet sub-sprite name

texts:
I am trying to change the name of the sub-sprites of a sprite sheet. I have searched and tried everything I can think of and cannot get it to work, which makes me think it can't be done at this point in time.

Let's say I have a sprite sheet that has already been split up into individual sprites inside of Unity.

I am attempting to change the sub-sprite names programmatically.

I tried using

AssetDatabase.RenameAsset (...)

on the sprite sheet asset, which only changes the sprite sheet name and not sub-sprites.

I then thought to obtain a sub-sprite and attempt to change its name using the below code.

            if (AssetDatabase.IsSubAsset (subSprite))
            {
                AssetDatabase.RenameAsset (AssetDatabase.GetAssetPath (subSprite), "newSprite" + i.ToString ());
            }

However, this too only changes the sprite sheet name.

I'm not sure where else I can take this to achieve my desired outcome, apart from programmatically copying the original sprite sheet and using that to create a copy. But even then, I still am unable to alter the sub-sprite names.

I also tried changing subSprite.name, but this just changes the internal name and not the asset name.

Any ideas?


texts: Mahjong solitaire - navigating between open tiles

texts:
I am looking for an algorithm to help me navigate between 'open' tiles in a Mahjong solitaire game. The game is to be played on a limited device with only left-right-up-down buttons and I want to speed up the time it takes to reach the appropriate tile. Toward this goal, I have made the movement work between 'open' tiles (tiles that you could move).

For example, pressing down will find the closest open tile below the one you are on, etc... The problem is that some tiles are really tough to get to. I am sure there are some known algos for this soft of things, but I can't find anything online since searching for 'Mahjong' returns 10 pages of free flash games.

Anyone has any idea?


texts: How can I have an RPG character redirect / glance off stationary objects and keep going?

texts:
I am attempting to create an effect in a game that is identical to the effect I've shown in the attached gifs. Essentially, the character, when they are running or walking and hit an object that is stationary, if it's possible, (meaning there is a valid path for continuation) they should glance off the side of said object and keep going.

In this first GIF I am only holding the UP directional key, notice how the character glances to their right:

In this second GIF I am only holding the DOWN directional key, notice how the character glances to their left:

In this third GIF I am only holding the UP directional key, notice how the character glance first to their left and then to their right:

Could someone describe the process that I would need to follow in order to do this type of collision detection into redirection?


texts: Efficient Algorithm for Recording gameplay's objects positions

texts:
So, I have a game idea in mind, and for that I need to record the game around the player. I'me not talking about recording it as video, but rather recording the scene objects, and their positions within the game, and then render them, giving the player the ability to go back and forth, to stop time and move around.

I've made a prototype with some data structures in C#, since this is going to be the programming language we'll be using in our game, but if we want the player to be able to go back just five minutes back with the data of just 100 NPC's, it takes almost 1GB of RAM.

Right now, I'm just storing a Doubly linked list, each item with the object position. In the game, I'll need to store even more data in each node, so I need something even more ligher. Of course, this algorithm is zero optimized, but still, that is a lot.

The alternatives would be create the NPC's that aren't really important to the game when the user is viewing the past, but I don't really like it very much for the sake of realism.

I wonder if there is a better way to store this?

Thanks in advance,
Scorch


texts: When pressing both the key then releasing any1 key then the anination is not played

texts:
i give the running animation to the character and created a flip script...when press A then player move and flip to leff and animation is played ....when press D then player move and flip to write and animation is played.. ..when i press both A and B Simultanious then animation is played but when pressing both at the same time and release one key the player moves in that direction but the animation is not playing
Here are the script of the player:
[SerializeField] float _xSpeed = 10f;
[SerializeField] float _jumpForce = 10f;

private Rigidbody2D _rb;
private float _movement;
private float _extraJumps;
private bool _isFacingRight;

void Start()
{
    _rb = GetComponent<Rigidbody2D>();
}

void Update()
{
    _movement = Input.GetAxisRaw("Horizontal");
}

void FixedUpdate()
{
    _rb.velocity = new Vector2(_movement * _xSpeed ,_rb.velocity.y);
    {
        if(_isFacingRight == true && _movement > 0.1f)
        {
            Flip();
        }
        else if(_isFacingRight == false && _movement < -0.1f)
        {
            Flip();
        }
    }

    if(Input.GetKeyDown(KeyCode.Space))
    {
        _rb.velocity = new Vector2(_rb.velocity.x,_jumpForce * Time.deltaTime);

    }

}

void Flip()
{

    _isFacingRight = !_isFacingRight;
    transform.Rotate(0,180f,0);

}

And here is the script for the animation:
[SerializeField] Transform _player;
private Animator _animator;

void Start()
{
    _animator = GetComponent<Animator>();
}

void Update()
{
    transform.position = _player.position;
    if (Input.GetKeyDown(KeyCode.D))
    {
        _animator.SetBool("Running", true);
    }
    else

    if (Input.GetKeyDown(KeyCode.A))
    {
        _animator.SetBool("Running", true);
    }
    else

    {
        _animator.SetBool("Running", false);
    }
}


texts: Can I achieve a torchlight effect (lighter area around a light source) in a 2D game?

texts:
I am thinking of writing myself a simple 2D game. It will not shine with perfect graphics or gameplay at first, but I'd consider it my first step in PC game development. So, imagine such simple sprite-based 2D game (like Heroes IV or Startcraft BroodWar).

I want the gameplay to support day/night with the according lighting changes and at the same time it will be madness to have to create sprites for every lighting nuance. So, I decided adding a semi-transparent layer on top of other objects will be enough.

The issue with this solution is if I have a light source object in the game (like the hero wearing a torch, or a burning building), there must be a lighter area around it, right? Since I am putting my semi-transparent layer over everything, how would you suggest to achive the torchligt visual effect I want? Maybe redraw that layer adding 'gaps' or differently colored areas based on the lighting effect?


texts: How can I rotate RigidBody and not violate physics?

texts:
I'm trying to create a game that we have a falling ball and an spinning object that spin based on user mouse position. user should rotate the object and hit the ball on time to throw the ball into sky.
The problem is that if user move his finger too fast. the game object moves too fast and goes past through the ball. This is my code so far:

 void Update () {
         if (Input.GetMouseButtonDown(0)) {
             startPos = Input.mousePosition.x;
             startRot = obj.transform.localEulerAngles;
             lastDist = 0;
         }

         if (Input.GetMouseButton(0)) {
             float dist = Input.mousePosition.x - startPos;

             obj.MoveRotation(Quaternion.Euler(startRot + new Vector3(0, 0, -dist)));

             for (int i = 0; i < obj.transform.childCount; i++)
                 obj.transform.GetChild(i).GetComponent<Rigidbody>().MoveRotation(Quaternion.Euler(startRot + new Vector3(0, 0, -dist)));
         }
 }

How can I achieve this behavior for my game. The user should be able to spin the game object as fast as possible.

Thanks in advance.


texts: How can I implement smart scripting, in my game?

texts:
I'm developing a game engine. It is supposed to be an entity/components based one. For developing my game, itself, I thought to use some scripting language to actually create the entities.

For example, if I want to add a kind of monster that is aggressive to the player, it will be an entity with several components; those components will change with the monster type, so if I have one hundred different types of monsters, in my game, I will not have to create a new method for each of them straight in my game code.

Should I use a scripting language to describe this entity, in term of components or is there something else that would work better? More generally, how should I use scripting, in my game?


texts: I am writing a game in a c++ console application. I would like to detect whether or not there is a collision between two objects, and displace them accordingly. All sprites are simply strings drawn on screen (Ex. a sprite with x 5, y 5, width 3, height 3 and the image "XXXXOXXXX" would create a 3-by-3 box of X's with a O in the middle). All objects have a x, y, length, and width which can aid in looking for potential collisions; however I would like to look at the actual string for finer collision detection. I am relatively new to the concept of continuous collision detection and I am having trouble finding the answer via Google. Does anybody know how I would go about doing this? Thanks in advance.