texts:
How would I accomplish multi-textured terrain? I need to know how to write the HLSL shader for it. The world already UV maps itself and I can get it to do 1 texture at a time. But I want more than 1 texture being displayed on my screen.

Here is my vertex declaration.

D3DVERTEXELEMENT9 Decl[] =
    {
        {
            0,
            0,
            D3DDECLTYPE_FLOAT3,
            D3DDECLMETHOD_DEFAULT,
            D3DDECLUSAGE_POSITION,
            0
        },
        {
            0,
            0,
            D3DDECLTYPE_FLOAT3,
            D3DDECLMETHOD_DEFAULT,
            D3DDECLUSAGE_TEXCOORD,
            0
        },
        {
            0,
            0,
            D3DDECLTYPE_FLOAT3,
            D3DDECLMETHOD_DEFAULT,
            D3DDECLUSAGE_TEXCOORD,
            1
        },
        D3DDECL_END()
    };

I am also using D3DFVF_XYZ and D3DFVF_TEX2

My variables for for each vertex are X, Y, Z, U1, V1, W1, U2, V2, W2


texts: How to design the attack class in an RPG game?

texts:
I am in the planning phase of a small RPG style game.

The character will have have a set of attributes, like strength, agility, etc which are represented as integers. The character also will have a set of attacks represented as an attack class.

On each attack I want it to do damage based on the characters attributes, eg: the attack "sword slash" will do 10 dmg + the value of the characters strength.

The way I was thinking to do this is to have an abstract attack class, which has an abstract Attack method, and for each attack I create one class that implements the Attack method.

public class SwordSlash:Attack
{
    public void Attack(Character attacker, Character defender)
    {
        defender.DoDamage(10 + attacker.Strength);
    }
}

I see that this will make it a nightmare to maintain.

Does anyone have an idea of how I can accomplish this in a nicer way?

What I think is the main problem is how to input the correct attribute, based on the attack.


texts: x axis detection issues platformer starter kit

texts:
I've come across a problem with the collision detection code in the platformer starter kit for xna.It will send up the impassible flag on the x axis despite being nowhere near a wall in either direction on the x axis, could someone could tell me why this happens ?

Here is the collision method.

  /// <summary>
    /// Detects and resolves all collisions between the player and his neighboring
    /// tiles. When a collision is detected, the player is pushed away along one
    /// axis to prevent overlapping. There is some special logic for the Y axis to
    /// handle platforms which behave differently depending on direction of movement.
    /// </summary>
    private void HandleCollisions()
    {
        // Get the player's bounding rectangle and find neighboring tiles.
        Rectangle bounds = BoundingRectangle;
        int leftTile = (int)Math.Floor((float)bounds.Left / Tile.Width);
        int rightTile = (int)Math.Ceiling(((float)bounds.Right / Tile.Width)) - 1;
        int topTile = (int)Math.Floor((float)bounds.Top / Tile.Height);
        int bottomTile = (int)Math.Ceiling(((float)bounds.Bottom / Tile.Height)) - 1;

        // Reset flag to search for ground collision.
        isOnGround = false;

        // For each potentially colliding tile,
        for (int y = topTile; y <= bottomTile; ++y)
        {
            for (int x = leftTile; x <= rightTile; ++x)
            {
                // If this tile is collidable,
                TileCollision collision = Level.GetCollision(x, y);
                if (collision != TileCollision.Passable)
                {
                    // Determine collision depth (with direction) and magnitude.
                    Rectangle tileBounds = Level.GetBounds(x, y);
                    Vector2 depth = RectangleExtensions.GetIntersectionDepth(bounds, tileBounds);
                    if (depth != Vector2.Zero)
                    {
                        float absDepthX = Math.Abs(depth.X);
                        float absDepthY = Math.Abs(depth.Y);

                        // Resolve the collision along the shallow axis.
                        if (absDepthY < absDepthX || collision == TileCollision.Platform)
                        {
                            // If we crossed the top of a tile, we are on the ground.
                            if (previousBottom <= tileBounds.Top)
                                isOnGround = true;

                            // Ignore platforms, unless we are on the ground.
                            if (collision == TileCollision.Impassable || IsOnGround)
                            {
                                // Resolve the collision along the Y axis.
                                Position = new Vector2(Position.X, Position.Y + depth.Y);

                                // Perform further collisions with the new bounds.
                                bounds = BoundingRectangle;
                            }
                        }
                       //This is the section which deals with collision on the x-axis
                        else if (collision == TileCollision.Impassable) // Ignore platforms.
                        {
                            // Resolve the collision along the X axis.
                            Position = new Vector2(Position.X + depth.X, Position.Y);

                            // Perform further collisions with the new bounds.
                            bounds = BoundingRectangle;
                        }
                    }
                }
            }
        }

        // Save the new bounds bottom.
        previousBottom = bounds.Bottom;
    }


texts:
I'm using this code to load a tiled map, composed of 1000x1000 32x32px tiles:

map = new TmxMapLoader().load("levels/xyz.tmx");

camera = new OrthographicCamera();

camera.setToOrtho(false, Constants.WORLD_WINDOW_SIZE.x / 32,
            Constants.WORLD_WINDOW_SIZE.y / 32);

renderer = new OrthogonalTiledMapRenderer(map, 1 / 32f);

renderer.getSpriteBatch().disableBlending();

renderer.setView(camera);

And this code for rendering:

camera.update();
renderer.setView(camera);
renderer.render();

However, I have huge performance issues. How can I optimize this code ? Will splitting the map in multiple submaps help?

Greetings, TM3P


texts:
I'm developing a 2D platformer game using the Cocos2d-x Engine, i can load correctly the animations according in which action the player is(running, jumping, standing, etc).

Now i'm trying to add the attack action to the player, and i need some advice about the best way to handle the corresponding animation for this new action.

The first thing that comes to my mind is to create new states for the player and his corresponding animation. For example, JumpRightAttack, JumpLeftAttack, and so on. But handling this that way seems to be a mess, and if i have more than one weapon it will become even more messy.

On the other hand, i can have only one attack animation and attach the current weapon, but i'm a little lost of how to attach the weapon in the correct spot(i.e. player's hand)

Which method would you recommend??


texts: How do you add equipment to a 3D character model using XNA/Blender?

texts:
I've watched quite a few Blender tutorials, but I have yet to see examples of how to swap out sub-models. So my question is, how do you swap out equipment on a character model? Specifically I’d like to be able to dynamically add/swap clothing and items held by a character model in XNA. Ideally the items would follow the bone structure of the character model.

For example; starting with a naked character in XNA, I’d like to be able to have the character hold an axe and wear chainmail that follows the character’s animations. I’d also like to be able to switch this equipment for a sword and plate mail at any time during the game. I’d rather not create a model for each equipment combination. Is there some way to just add the bones (say a sword bone) and meshes of one model to another model bone (say a right hand bone)?

Thanks…


texts:
I am converting between coordinate systems where Z is the vertical axis in one, and Y in another. I have the rotation values represented as a quaternion.

I see this related issue but it's switching the handedness (DirectX and OpenGL): Switch axes and handedness of a quaternion?

How would I go about swapping these values? I'd prefer not to convert to a vector3, modify and convert back again.


texts: Is it only possible to display 64k vertices on the monitor with 16bit?

texts:
I did the first 3D tutorial over at riemers.net and stumbled upon that my graphic card only supports Shader 2.0 (Reach profile in XNA) which means I can only use Int16 to store the indices (triangle to vertex).

This means that I can only store 2^16 = 65536 vertices. Also I read on the internet that you should prefer 16-bit over 32-bit because not all hardware (like mine) does support 32-bit.

Yet, I am wondering: Do really all game scenes get along with only so little vertices? I though already faces of people used a lot of polygons (which are made up of vertices?).

It’s not relevant for me yet, but I am interested:

Do game scenes use only 65536 vertices?
Do you use some trade-off to display more (e.g. 64k in GPU buffer rest on RAM)
Is there some method to get more into the GPU buffer? I already read on some other posts that there seems to be a limit of 64k per mesh too, so maybe you can compact stuff to meshes?


texts: How can I find the "end" vertices on an open-ended mesh?

texts:
I was looking at a video of a system that extrudes meshes along a curve, connecting them end to end but adjusting the vertices for a smooth connection. It does this with a mesh that as far as I know is guaranteed to have open ends that are later capped with a separate mesh.

Here is a video showing the effect I am trying to reproduce.

Let's suppose I have a mesh, then, that is open like in the picture below. How can I find the vertices that are on one edge only of this mesh? For example the ones that are selected here.

Previously I used a plain cylinder with open caps as an example, and finding edges that were only used for one face might have been able to do the job, but in a case like this, it would end up selecting any vertices in the middle along the bottom as well, which I don't want.

I want to be able to find the ends of a particular side like those that are selected in the picture. Theoretically I can then manipulate these into new positions if I wanted to, for example, string cylindrical segments into a curved cable structure.

For what it's worth, I'm trying to accomplish this in Unity with C#, but it's the algorithm I need help with.


texts: Why does GLM only have a translate function that returns a 4x4 matrix, and not a 3x3 matrix?

texts:
I'm working on a 2D game engine project, and I want to implement matrices for my transformations. I'm going to use the GLM library.

Since my game is only 2D, I figured I only need a 3x3 matrix to combine the translation, rotation and scale operations. However, glm::translation is only overloaded to return a 4x4 matrix, and never a 3x3.

I thought a translation could be performed by using a 3x3 matrix; why does GLM only have a translate function that returns a 4x4 matrix, and not a 3x3 matrix?


texts: Good baseline size for an A* Search grid?

texts:
I'm working on a grid based game/prototype with a continuous open map, and are currently considering what size to make each segment. I've seen some articles mention different sizes, but most of them is really old, so I'm unsure how well they map to the various platforms and performance demands common today.

As for the project, it's a hybrid of 2D and 3D, but for path-finding purposes, the majority of searches would be approximately 2D. From a graphics perspective, the minimum segment size would be 64x64 in the XZ plane to minimize loaded segments while ensuring full screen coverage. I figure pathfinding would be an important indicator of maximum practical size.

Addendum:

I realize I was a bit unclear when talking about sizes and segments.

Each segment is a cubical map of blocks, e.g. 64x64x64 blocks. These represent both geometry, but also if an actor can move into that location and is thus a potential node in the graph.

Each of these segments again combine to a larger square or cubical world map. Neighboring segments are to be loaded dynamically to ensure a seamless local map.

Therefore how many blocks fit into the screen space when rendered, sets a practical minimum for the segments, but we would probably want to have larger segments than the absolute minimum. However, since a block also represents a potential node, the segment size also affects the size of the graph, which have to be considered when choosing a segment size.


texts: Detect a collision between a CharacterController and a 3D Object?

texts:
I am making an XR game, and I am stuck with a part. Does anyone know a function that would detect this?
OnCollisionEnter and OnTriggerEnter don't appear to work with a CharacterController. Can anyone help?


texts: In Unity, Image to show icon works on one scene but not the other

texts:
I am trying to show an icon on the UI when the player is looking at an enemy. The raycasting code, etc all works, but on one scene, the icon shows successfully, the other, it doesn't. I have tried copying, recreating, using different Sprites, none of it works.

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

public class CursorAffordance : MonoBehaviour
{
    [SerializeField] private Sprite _combatAffordance;

    private CameraRaycaster _raycaster;

    private Image _image;
    // Use this for initialization
    void Start ()
    {
        _raycaster = FindObjectOfType<CameraRaycaster>();
        _image = FindObjectOfType<Image>();
    }

    // Update is called once per frame
    void LateUpdate () {
        if (Input.GetMouseButton(0))
        {
            print(_raycaster.layerHit);
        }

        switch (_raycaster.layerHit)
        {
            case Layer.Enemy:
                _image.sprite = _combatAffordance;
                _image.enabled = true;
                break;
            default:
                _image.sprite = null;
                _image.enabled = false;
                break;

        }
    }
}

The only thing i can find from debugging is _combatAffordance is somehow null the second run through , and stays null from then on, although in inspetor it still shows my Target sprite.


texts: Does anyone know of (or have) an experience selling an indie title through Desura? How does it compare with other typical indie game distribution avenues?


texts:
I'm not sure if this is intended or not, if it is, I'd like to know a way of preventing this: I've got this image (which is for testing purposes, the actual one has a texture, but I'm not using it right now):
Zoomed in, it looks like this in the JFrame:

These small 'arrangements' are what bothers me, because the image itself should be plain green, just as it is when viewing the tile image with a separate viewer
(like that:)

OOO
--O--
O--O

In the end, drawn as a tilemap, it looks like this (I'm changing the rgb values, that's why it's coloured differently on the left):

My Code:
(It draws 15 horizontal tiles and 10 vertical tiles, the orange ones are another piece of code which is irrelevant right now)

BufferedImage singleTile;
    try {
        singleTile = ImageIO.read(new File(filename));
    } catch (IOException e) {
        e.printStackTrace();
        return;
    }
    BufferedImage finalImg = new BufferedImage(tilesX*scaledTileSize, tilesY*scaledTileSize, singleTile.getType());
    for(int i = 0; i < tilesX; i++){
        for(int j = 0; j < tilesY; j++){
            finalImg.createGraphics().drawImage(singleTile, i*scaledTileSize, j*scaledTileSize, scaledTileSize, scaledTileSize, null);
        }
    }


texts:
I am building a MMO game server for a 2D game and am currently implementing the collision detection, and I am would like to know what I should do.

Lets say I have 1000 players playing and 10,000 objects, should I just iterate over them all to determine if colliding? This seems a bit pricey.

I could separating the world into chunks and iterating every object for each player in it's chunk.

I would like to know some other ideas or what is standard. What's the best way for a MMO server to handle collision detection with static objects?


texts:
I am new to XNA and I am having problems with collision detection when I rotate my sword. I am using a rectangle bounding box approach and I don't know how I can rotate my rectangle together with the sword sprite.

http://picpaste.com/pics/f10268c108e885498a4ae603ab030a60.1328941784.png

Any suggestions on how can i solve my problem is really appreciated. Thanks!


texts: I know fundamental programming. But how do I get started in game development now?

texts:
I'm a 20 year old programming student. I know fundamental programming in BASIC, C, C++ and JAVA. What I wanted to ask is, where do I go from here? Are there any books that the community can mention that will help me develop a game or at least learn game development? I've had a lot of ideas and really want to make some sort of prototype to see if I'm suited for the industry.

I really don't mind learning any new languages but I need to know what I should begin with. A good book that will help with a little more understanding as I go up will be very helpful. Maybe a tutorial to develop some basic 2D games like a side-scroller, snake or pocket tanks in an easy to understand SDK?

I know that to get some credit under your belt, you need to be able to make a few games on your own.

Also, what platform should I start on? The PC, iOS or Android (as an introduction) for now. I don't want to get into high level game design just yet. Just something a bit basic to help out in future development.

Anything pointing me in the right direction will be  really really helpful.

Edit: Also, I want to say that I'm looking towards this from a game designer's point of view more than a game programmer. I want suggestions on any SDKs or easy to use programs I can use to understand game design. Then delve deeper into the programming after that.

Not as employment but as developing your own games (for now).


texts:
I'm trying to reproduce a post-effect with unity seen in the answer here.

Chromadepth answer

For the moment I just manage to reproduce the wave effect with a quick edge detection.
I tried multiple textures but can't find one that fit do the same effect.

I am using this texture

The result for far.

Shader "Unlit/ChromaDepthEdge"
{

    Properties
    {
        _MainTex ("Texture", 2D) = "white" {}
        _Ramp ("Texture", 2D) = "white" {}
        _Threshold("Threshold", Float) = 0.1
    }
    SubShader
    {
      Pass
      {
          ZTest Always Cull Off ZWrite Off
          CGPROGRAM
          #pragma vertex vert
          #pragma fragment frag
          #pragma target 3.0
          #include "UnityCG.cginc"

          struct appdata
          {
              float4 vertex : POSITION;
          };

          sampler2D _MainTex;
          sampler2D _Ramp;
          // Request camera depth buffer as a texture.
          // Incurs extra cost in forward rendering, "just there" in deferred.
          sampler2D _CameraDepthTexture;
          float4 _MainTex_TexelSize;

          float4x4 _InverseViewMatrix;

          float _Threshold;

          void vert (
              float4 vertex : POSITION,
              out float4 outpos : SV_POSITION)
          {
              outpos = UnityObjectToClipPos(vertex);
          }

          fixed4 frag (UNITY_VPOS_TYPE screenPos : VPOS) : SV_Target
          {
              // Convert pixel coordinates into screen UVs.
              float2 uv = screenPos.xy * (_ScreenParams.zw - 1.0f);

              //uv.y = (uv.y *-1) + 1;
              // Depending on setup/platform, you may need to invert uv.y
              // Sample depth buffer, linearized into the 0...1 range.
              float depth = Linear01Depth(
                    UNITY_SAMPLE_DEPTH(tex2D(_CameraDepthTexture, uv)));

              float2 uvDist = 3 * _MainTex_TexelSize.xy;

              float depthUp =  Linear01Depth(UNITY_SAMPLE_DEPTH(tex2D(_CameraDepthTexture, uv + uvDist * float2(0, 1))));
              float depthDown =  Linear01Depth(UNITY_SAMPLE_DEPTH(tex2D(_CameraDepthTexture, uv + uvDist * float2(0, -1))));
              float depthLeft =  Linear01Depth(UNITY_SAMPLE_DEPTH(tex2D(_CameraDepthTexture, uv + uvDist * float2(-1, 0))));
              float depthRight =  Linear01Depth(UNITY_SAMPLE_DEPTH(tex2D(_CameraDepthTexture, uv + uvDist * float2(1, 0))));

              float mean = ((depthUp - depth) + (depthDown - depth) + (depthLeft - depth) + (depthRight - depth)) / 4;

              // Compressing the range, so we get more colour
              // variation close to the camera.
              depth = saturate(2.0f * depth);
              depth = 1.0f - depth;
              depth *= depth;
              depth = 1.0f - depth;
              //return depth;

              // Use depth value as a lookup into a colour
              // ramp texture of your choosing.
              fixed4 colour = tex2D(_Ramp, depth * 6 * _Time.y * 4);

              return lerp(colour, colour * 6, mean > _Threshold);
          }
          ENDCG
      }

    }
}

What did I miss ?

Thanks in advance.


texts: When I exit the pause menu of my game the gun fires

texts:
When The player exits the pause menu in my game the gun will fire. I figured out that it happens when the player clicks when the game is paused.

Basically i the player goes to the pause menu and exits without clicking the gun will not fire, but if they go to the pause menu and click then exit the gun will fire. Here are my scripts:

public class Shooting : MonoBehaviour
{
    Animator anim;
    public float FireRate = 15f;
    private float NextTimeToFire = 0f;
    // Start is called before the first frame update
    void Start()
    {
        anim = GetComponent<Animator>();
    }
    // Update is called once per frame
    void Update()
    {
        if (Input.GetButton("Fire1") && GetComponentInParent<PlayerController>().moving == false && Time.time >= NextTimeToFire)
        {
            NextTimeToFire = Time.time + 1f / FireRate;
            Shoot();
        }
    }
}

/

public class PauseMenu : MonoBehaviour
{
    public static bool GameIsPaused = false;
    public GameObject HUDPanel;
    public GameObject PauseMenuPanel;
    public GameObject OptionsPanel;

    private void Start()
    {
        Time.timeScale = 1f;
        GameIsPaused = false;
    }

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Escape))
        {
            if (GameIsPaused)
            {
                Resume();
            }
            else
            {
                Pause();
            }
        }
    }

    void Resume()
    {
        Cursor.lockState = CursorLockMode.Locked;
        Cursor.visible = false;
        PauseMenuPanel.SetActive(false);
        OptionsPanel.SetActive(false);
        HUDPanel.SetActive(true);
        Time.timeScale = 1f;
        GameIsPaused = false;
    }

    void Pause()
    {
        Cursor.lockState = CursorLockMode.None;
        Cursor.visible = true;
        PauseMenuPanel.SetActive(true);
        HUDPanel.SetActive(false);
        Time.timeScale = 0f;
        GameIsPaused = true;
    }
}


texts: Game shifts to edge of screen when clicking Play button in Unity

texts:
I’m attempting to help my young daughter who is trying to learn Unity. I know very little about the program.
Recently, she developed a basic game consisting of a dragon and a person.
When she presses the play button, the game shifts to the edge of the screen and does not start.
I have attempted to research the issue but with my limited knowledge on the subject I could not find anything. Any help or suggestions would be appreciated!
09/22 - After reading the comment and following the recommendations  I do believe it’s a camera issue. I’ve attempted to move the camera around using the X, Y and Z axis is but I can’t get it to actually change the view. See the attached screenshot.

10/02/2020 - My daughter went back and redid the game from the start. The issue is that the game will not allow her to enter play mode until she places the dragon. However, as soon as she places the dragon and presses play the game moves the camera. So the issue apparently occurs prior to or at the time she places the dragon but because she can't enter play mode prior to this point I'm not sure where the issue occurs.


texts: OnDrag does not work, but OnMouseDown works

texts:
There is a code:

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

public class DragAndDropGame : MonoBehaviour, IBeginDragHandler, IDragHandler
{

    Camera MainCamera;

    void Awake()
    {
        MainCamera = Camera.allCameras[0];
        Debug.Log(MainCamera);
    }

    public void OnBeginDrag(PointerEventData eventData)
    {
        Debug.Log("OnBeginDrag");
    }

    public void OnDrag(PointerEventData eventData)
    {
        Vector3 newPos = MainCamera.ScreenToWorldPoint(eventData.position);
        newPos.z = 0;
        transform.position = newPos;
    }

    void OnMouseDown()
    {
        Debug.Log("OnMouseDown");
    }
}

OnMouseDown fulfills, but the implementation ofIBeginDragHandler, IDragHandler - not. What can be wrong?


texts:
I use CUDA 7.5 to learn the basics of raytracing. So far I've done nothing but constant color no-lighting spheres-only raytracing. But my delta time is already 14 - 16 ms for 800x600 resolution - 1 ray for each pixel.

Some pc specs, if needed:
GPU - nvidia titan black,
CPU - intel core i7...,
enough RAM.

Here is the kernel:

__global__ void runKernel(Camera* cam, SphereData* objs, uint* size, uchar* out_img)
{

vec3 pos = cam->getPos();
rs::Rectangle rec = cam->genNearPlaneRectangle();
vec3 start = rec.center - rec.right - rec.up;
float pixelsizex = 1.0F / cam->getWidth();
float pixelsizey = 1.0F / cam->getHeight();
uint width = cam->getWidth();

uint id = threadIdx.x + blockIdx.x * blockDim.x;
uint i = id % width;
uint j = id / width;

vec3 pixelW = start + rec.right * 2 * (pixelsizex / 2 + pixelsizex*i) + rec.up * 2 * (pixelsizey / 2 + pixelsizey*j);
vec3 dir = (pixelW - pos).normalize();

Ray ray = Ray(pos, dir);

vec3 resColor = Tracer::rayTraceSpheres(ray, objs, *size);

out_img[4 * width * j + 4 * i + 0] = 255 * resColor.x();
out_img[4 * width * j + 4 * i + 1] = 255 * resColor.y();
out_img[4 * width * j + 4 * i + 2] = 255 * resColor.z();
out_img[4 * width * j + 4 * i + 3] = 255;

}

I have a really basic standart setup for OpenGL, I use it to render a fullscreen texture of raytracing results.

Main loop's update and render functions:

void Graphics::update()
{
cameraUpdate();

//println(camera.genLookingRay().dir.toString());

uint objSize = objs.size();
cudaMemcpy(cudaData.d_cam, &camera, sizeof(Camera), cudaMemcpyHostToDevice);
cudaMemcpy(cudaData.d_objs, objs.getArray(), sizeof(SphereData)*objs.size(), cudaMemcpyHostToDevice);
cudaMemcpy(cudaData.d_size, &objSize, sizeof(uint), cudaMemcpyHostToDevice);

uint threadsPerBlock = 128;
uint blocks = ((uint)(width*height) + threadsPerBlock - 1)/threadsPerBlock;

runKernel <<< blocks, threadsPerBlock >>>(cudaData.d_cam, cudaData.d_objs, cudaData.d_size, cudaData.d_out_img);

// Check for any errors launching the kernel
cudaError cudaStatus = cudaGetLastError();
if (cudaStatus != cudaSuccess) {
    fprintf(stderr, "addKernel launch failed: %s\n", cudaGetErrorString(cudaStatus));
}

cudaStatus = cudaDeviceSynchronize();

cudaMemcpy(image, cudaData.d_out_img, sizeof(uchar)*4*width*height, cudaMemcpyDeviceToHost);

RenderFullScreen::setupTexture(width, height, image, 0);
RenderFullScreen::build();

}

void Graphics::render()
{
glClearColor(0,0,0,1);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

Shader::setCurrent(Shader::SHADER_HUD);
Shader::getCurrent().enable();
Shader::getCurrent().setUniformMat4f("P", camera.getMatOrthographic());
RenderFullScreen::render();
Shader::getCurrent().disable();

glfwSwapBuffers(window);
}

Function "rayTraceSpheres(...)":

__CUDA__ vec3 Tracer::rayTraceSpheres(Ray& ray, SphereData* objs, uint size)
{
    vec3 color(0,0,0);
    float tmin = INFINITY;

    for(size_t i = 0; i < size; i++)
    {
        Sphere obj = Sphere(objs[i]);

        float ct = tmin;
        vec3 cc(0,0,0);
        bool res = obj.hit(ray, ct, cc);

        if(ct < tmin) {
            color = cc;
            tmin = ct;
        }
    }

    return color;
}

__CUDA__ bool Sphere::hit(Ray& ray, float& tmin, vec3& color)
{
    float t;
    vec3 temp = ray.start - center;
    float a = ray.dir * ray.dir;
    float b = temp * 2 * ray.dir;
    float c = temp * temp - radius * radius;
    float disc = b * b - 4 * a * c;

    if(disc < 0){
        return false;
    }
    else
    {
        float e = sqrt(disc);
        float denom = 2 * a;
        t = (-b - e)/denom;
        if(t > 0){
            tmin = t;
            color = this->color;
            return true;
        }
        t = (-b + e)/denom;
        if(t > 0)
        {
            tmin = t;
            color = this->color;
            return true;
        }
    }
    return false;
}

What could be the issue ?


texts: Optimized algorithm for line-sphere intersection in GLSL

texts:
Well, hello then!

I need to find intersection between line and sphere in GLSL. Right now my solution is based on Paul Bourke's page and was ported to GLSL this way:

// The line passes through p1 and p2:
vec3 p1 = (...);
vec3 p2 = (...);

// Sphere center is p3, radius is r:
vec3 p3 = (...);
float r = ...;

float x1 = p1.x; float y1 = p1.y; float z1 = p1.z;
float x2 = p2.x; float y2 = p2.y; float z2 = p2.z;
float x3 = p3.x; float y3 = p3.y; float z3 = p3.z;

float dx = x2 - x1;
float dy = y2 - y1;
float dz = z2 - z1;

float a = dx*dx + dy*dy + dz*dz;
float b = 2.0 * (dx * (x1 - x3) + dy * (y1 - y3) + dz * (z1 - z3));
float c = x3*x3 + y3*y3 + z3*z3 + x1*x1 + y1*y1 + z1*z1 - 2.0 * (x3*x1 + y3*y1 + z3*z1) - r*r;

float test = b*b - 4.0*a*c;

if (test >= 0.0) {
  // Hit (according to Treebeard, "a fine hit").
  float u = (-b - sqrt(test)) / (2.0 * a);
  vec3 hitp = p1 + u * (p2 - p1);
  // Now use hitp.
}

It works perfectly! But it seems slow... I'm new at GLSL. You can answer this questions in two ways:

Tell me there is no solution, showing some proof or strong evidence.
Tell me about GLSL features (vector APIs, primitive operations) that makes the above algorithm faster, showing some example.

Thanks a lot!


texts: Opengl texture rendered as solid color,why?

texts:
her is my vertex array and texture coordinate..

float POS[]=
{
    -0.5,-0.5,-1.0,
    0.5,-0.5,-1.0,
    0.5,0.5,-1.0,
    -0.5,0.5,-1.0
};

float texCoords[] = {
0.0,0.0,
1.0,0.0,
1.0,1.0,
0.0,1.0
};

here is my texture creation

stbi_set_flip_vertically_on_load(1);
    openglTexBuff=stbi_load("lena.jpg",&w,&h,&c,0);

    glGenTextures(1,&TexID);
    glActiveTexture(GL_TEXTURE0);
    glBindTexture(GL_TEXTURE_2D,TexID);
    glTexImage2D(GL_TEXTURE_2D,0,GL_RGB,w,h,GL_FALSE,GL_RGB,GL_UNSIGNED_BYTE,openglTexBuff);
    glGenerateMipmap(GL_TEXTURE_2D);
    glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_S,GL_REPEAT);
    glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_T,GL_REPEAT);
    glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_NEAREST);
    glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_NEAREST);

    glBindTexture(GL_TEXTURE_2D,0);
    stbi_image_free(openglTexBuff);'

and these are my shaders

#shader vertex
#version 330 core

layout(location = 0) in vec4 positions;
layout(location = 1) in vec2 texCoords;
uniform mat4 translation_matrix; //inactive shader variables..
uniform mat4 rotation_matrix;

mat4 model_matrix; //
mat4 projection_matrix;
out vec4 pos;
out vec2 frag_TexCoord;

void main()
{

rotation_matrix;

gl_Position=rotation_matrix*translation_matrix*positions; //translation matrix operated with POS vector..
pos=positions;
frag_TexCoord=texCoords;
translation_matrix;

}

#shader fragment
#version 330 core

layout(location=0) out vec4 color;
in vec4 pos;
in vec2 frag_TexCoord;rag_TexCoord;
uniform float col;
uniform sampler2D  a_texture;
void main()
{
col;
a_texture;

color=texture(a_texture,frag_TexCoord);

}

when i use (solid)color instead of texture in shader..everything works fine but when i use shader it gives solid color instead of texture..It seems like my whole tex is super-zoomed to output single color

here is draw call

glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
    box.shader.setUniformat4x4("translation_matrix",translation);
    //box.shader.setUniformat4x4("rotation_matrix",rotation_arr);
    box.shader.setUniform1f("col",1.0);
    glBindTexture(GL_TEXTURE_2D,TexID);
    box.shader.setUniform1i("a_texture",0);
    box.render();

box.render

void render()
    {
        vertices.bind();
        indices.bind();
        shader.bind();
        glDrawElements(render_As,vertices.getSize(),GL_UNSIGNED_INT,NULL);
        vertices.unbind();
        indices.unbind();

    }


texts: Textures drawn with visible missing lines of pixels

texts:
I am making a game in monogame and have encountered the following problem:

The black arrows mark the places where the rendering is "off". As you can see the gray lines aren't "flush" or "smooth". Instead they have a "cut".

The two cuts at the top is at the same height, suggesting that an error happens with the positioning during drawing in that height. The two topmost cuts are 1 pixel off (from the cut and down) and the bottom cut is 1 pixel off  compared to the texture but 2 pixels in total (again from cut and down). Furthermore, the cuts are always in the same place. The topmost cuts and the bottom cut are part of two different "draws" and happens even if the other is removed.

The background experiences this too some other places, but vertically and not horizontally as with the HUD.

This only happens in the resolution of 1920x1080 and not in any other I've tried. The problem fixes itself in fullscreen though.

What causes this and how do I fix it?

EDIT

The resolution is certainly 1920x1080. I've double checked that.

This is how i draw the gray frame at the top

spriteBatch.Begin(SpriteSortMode.FrontToBack, BlendState.AlphaBlend);

spriteBatch.Draw(txtExpFrameLeft, new Vector2(0, 7), null, Color.White, 0f, Vector2.Zero, 1f, SpriteEffects.None, 0.81f);

spriteBatch.End();

No resizing at all.

EDIT 2

Here is the result from the checker board:

As said, there are missing lines spread evenly around. When i move the gamecursor onto one of those "lines", it itself is also affected. Everything is still fine in fullscreen


texts: With Slick, how to change the resolution during gameplay?

texts:
I am developing a tile-based strategy game using Java and the Slick API.

So far so good, but I've come to a standstill on my options menu. I have plans for the user to be able to change the resolution during gameplay (it is pretty common, after all).

I can already change to fullscreen and back to windowed, this was pretty simple...

//"fullScreenOption" is a checkbox-like button.
if (fullScreenOption.isMouseOver(mouseX, mouseY)) {
   if (input.isMouseButtonDown(Input.MOUSE_LEFT_BUTTON)) {
      fullScreenOption.state = !fullScreenOption.state;
      container.setFullscreen(fullScreenOption.state);
   }
}

But the container class, contrary to my previous beliefs, does not seem to have any resolution-change functions! And that's pretty much the situation...I know it's possible, but i don't know how to do it, nor what is the class responsible!

The AppGameContainer class, used on the very start of the game's initialization as of Slick's examples and tutorials, is the only place with any functions for changing the display-mode that I've found so far, but it's only used at the very start, and i haven't found a way to travel back to it from my options menu.

  //This is my implementation of it...
  public static void main(String[] args) throws SlickException {
    AppGameContainer app = new AppGameContainer(new Main());
//    app.setTargetFrameRate(60);
    app.setVSync(true);
    app.setDisplayMode(800, 600, false);
    app.start();
  }

I can define it as a static global on the Main, but it's probably a (very) bad way to do it...


texts: Particles/instancing groups in an Entity/Component system

texts:
I've been playing with an entity/component/system design recently, and I've come across a couple of stumbling blocks.

Instancing

Let's say I have a few hundred "things" (asteroids, chickens, whatever) that are being drawn with instancing. In a classic component hierarchy, I'd have a game object that keeps the individual instance index and vertex buffers, as well as the second dynamic vertex buffer for the instance data (collection of matrices, etc.). That object would be responsible for checking collisions with other objects and between the instances themselves.

In an ES system, I'd like to track each instance as an individual entity, but I don't want to give up simplicity and performance of instancing. The first thing that occurred to me was to create an "instance group" component, with a field that defines a group ID to enable handling of multiple types of instanced geometry.

An "Instance System" would collect those components and maintain the instance vertex buffer. My entity manager already notifies systems when an entity is created or destroyed which makes this part pretty easy to implement.

My confusion comes from how to cleanly integrate that with the rendering system. If each instance appears as a separate entity with a "renderable" component/attribute, the render system will process them individually.

I could:

Include a special case for entities that have both a "renderable" and an "instanced" component, but that seems messy and feels like starting down the path of having a huge render system with tons of special cases.
Have the render system maintain a collection of instance vertex buffers, query the entity list for "instanced" entities, filter based on a group ID, etc., and render as appropriate, so the render system becomes responsible for maintaining instance collections, but that seems like the wrong place to put that sort of logic.
I could also include a single entity in addition to the instances with, say, an "InstanceOutput" component/attribute and a Renderable component, and remove the Renderable component from the individual instance entities, giving a single render point for all of the instances. This component would probably also server as a place to keep the geometry and persistent instance/vertex buffer.

Is there a better way?

Rendering

I have several types of renderable entities. Some have procedural geometry and textures, some are just sprites, some are text displays. What's the best way to differentiate these from the point of view of the rendering system without having to write a massive switch statement? In a game object hierarchy, each of these types would have their own Draw() method, but moving the logic into a Render System doesn't seem to provide a lot of flexibility in terms of different effect parameters, etc.


texts: How do I generate a 2D tile map from an array like in this tutorial for XNA ? I basicly want to generate a static map based on my tile prefabs.


texts:
Right now I'm using the Crytek vegetation bending technique, vertex colors control how much force is applied to the branches, leafs and trunks. I have it working and it looks nice but I'm just using random wind so it's all over the place.

Here is the code I use for the wind on the CPU, this gets passed of the vertex shader where the bending happens:

    // Change wind every second, and smoothly interpolate to the new strength/direction.
    Dim timeEllapsed As Single = CType(gametime.ElapsedGameTime.TotalSeconds, Single)
    _Time += timeEllapsed
    timeSinceLastThing -= timeEllapsed
    If timeSinceLastThing < 0F Then
        lastWindSpeed = newWindSpeed
        Dim x As Single = CType(random.NextDouble(), Single)
        x = CType(Math.Pow(x, 3), Single)
        Dim y As Single = CType(random.NextDouble(), Single)
        y = CType(Math.Pow(y, 3), Single)
        newWindSpeed = New Vector2(x * 2.0F - 1.0F, y * 2.0F - 1.0F)
        newWindSpeed *= 0.9F
        timeSinceLastThing += 1.0F
    End If
    currentWindSpeed = Vector2.SmoothStep(newWindSpeed, lastWindSpeed, timeSinceLastThing)

It's nice and flowy so that's not an issue, it just doesn't really gust and stuff the same way wind does. I'm just wondering if anyone knows of a better way of making nice swaying wind? Or will I just have to tweak it till I find what I'm after?


texts: Extracting blend values from uint32 not working as expected

texts:
I have the following shader configuration code :

uint gBlendValue = 0xffffff00;
Terrain.Effect.GetVariableByName("gBlendValue").AsScalar().Set(gBlendValue);

And I have the following shader code :

// extract blend weights from gBlendValue - produces bVn values in the range [0,1]
float bV1 = ((gBlendValue >> 24) & 0xff)/255.0;
float bV2 = ((gBlendValue >> 16) & 0xff)/255.0;
float bV3 = ((gBlendValue >> 8)  & 0xff)/255.0;
float bV4 = (gBlendValue & 0xff)/255.0;

// sum lerped blends
float3 finalColor = float3(0,0,0);
finalColor += lerp(float3(0,0,0), float3(1,0,0), bV1);
finalColor += lerp(float3(0,0,0), float3(0,1,0), bV2);
finalColor += lerp(float3(0,0,0), float3(0,0,1), bV3);

// return finalColor
return float4(finalColor,1);

But this doesn't behave as expected. The geometry is a dark red, when it should be white. What the turtle is going on here.


texts: Unity C# Invoke Function Freezes Program

texts:
if(Input.GetKeyDown(KeyCode.G) && ammo <= 9)
        {
            ableS = false;
            while(ammo <= 9)
            {
                Invoke("bulletplus", 0.5f);
            }
            ableS = true;
        }

This is the main part I am having trouble with.
Down there is ALL my code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class gun : MonoBehaviour
{
    Vector2 rotation = new Vector2 (0, 0);
    public float rot = 3;
    public Vector3 pos;
    public Rigidbody Orb;
    public Text ammoT;
    public int ammo = 10;
    bool ableS = true;

    void Update () {
        // Ammo
        if(ammo >= 7)
        {
            ammoT.GetComponent<Text>().color = Color.green;
        } else if(ammo >= 4)
        {
            ammoT.GetComponent<Text>().color = Color.yellow;
        } else {
            ammoT.GetComponent<Text>().color = Color.red;
        }

        // Rotation
        rotation.x += -Input.GetAxis ("Mouse Y");
        rotation.x = Mathf.Clamp(rotation.x, -70, 70);
        rotation.y += Input.GetAxis("Mouse X");
        transform.eulerAngles = (Vector2)rotation * rot;
        pos = new Vector3(transform.position.x, transform.position.y, transform.position.z);

        // Shoot Choklats
        if(Input.GetMouseButtonDown(0) && ammo >= 1 && ableS)
        {
            ammoT.text = "Ammo: " + ammo.ToString();
            ammo -= 1;
            Rigidbody projectile = Instantiate(Orb, pos, transform.rotation);
            projectile.velocity = transform.forward * 50f;
        }

        // Reload
        if(Input.GetKeyDown(KeyCode.G) && ammo <= 9)
        {
            ableS = false;
            while(ammo <= 9)
            {
                Invoke("bulletplus", 0.5f);
            }
            ableS = true;
        }
    }

    void bulletplus()
    {
        ammo += 1;
        ammoT.text = "Ammo: " + ammo.ToString();
    }
}


texts: What sort of GDC pass (if any) is best for a cash-strapped indie?

texts:
I'm doing a web game startup with one other person. We support ourselves with contract programming. I'm considering attending GDC for the first time, but we're really tight on cash. Money spent on passes and plane tickets slows our startup's growth.

Some say GDC is a good way to meet clients, but fortunately we have plenty of client interest, so I don't consider that a major concern. Still, it's generally good to network, and it's healthy for us as designers and developers to learn from the rest of the community.

Which type of pass should we invest in?


texts:
I am new to Unity, game-making, etc.

I have downloaded the trial version of Avatar Maker and a similar Unity plugin called Didimo Editor, with the hope of using their features to make game characters that look like real people, using photographs. They both do more or less what I want.

However, both tools output only heads, and do not connect them to 3D bodies. Avatar Maker has another plugin that allows for this, but it is only for male bodies and most of its features are not to my liking.

So my question is: how can I put these heads on working 3D bodies?

The trailer for Didimo Editor seems to confirm that it can, at least, and Avatar Maker is able to export its heads to OBJ, FBX and Prefab, so I'm assuming maybe there is a way to do that too.


texts: Tool for editing sprites contour pixel alpha value

texts:
I have seen that most games uses sprites that have a transparent contour, that is, the pixels that belongs to the contour of the object in the WxW sprite image is below 255. It is not perfectly opaque, so that when you render it on screen, you avoid aliasing effects.

Is there a tool that automatically loads N .png sprites and process them in order to make their contours semi-transparent?


texts:
Is there a correct way to calculate the exact proportions for drawing a tree sprite for an RPG. These are the types of trees I am aiming to create(sorry for the huge picture, I dont how to scale it down):

The tutorial here, http://cyangmou.deviantart.com/art/Pixel-Art-Tutorial-3-The-perfect-crate-311089437, perfectly describes how to create an object using the 3/4 perspective but when I apply this method when drawing a tree it doesn't quite work. Is there a different method that I could use for creating non-rectangle shaped objects like a tree or other strangely shaped objects, or am I going about it wrong?

Thank you in advance :D.


texts: How to make a stereoscopic 3D Game with SDL for iOS

texts:
I was looking up google for an answer the whole night but didn't find anything. Yesterday I found some VR demos and games on the AppStore, with stereoscopig (dual rendered) screens. So you put your phone into a google cardboard and experience a oculus rift like feeling.
But how is that possible using C++ and SDL?
Thank you very much.


texts: In Box2D, how do I make a flexible pole?

texts:
I would like to replicate the behavior of a flexible pole as used for pole vault.

Can somebody give me some inspiration how to simulate that with Box2D?
Should I connect multiple objects with flexible joints, or is there another way?


texts: Why when destroying objects when quitting the game it's destroying the objects only in hierarchy?

texts:
In one script i did:

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

public class GameManager : MonoBehaviour
{
    public LevelGenerator levelGenerator;

    // Use this for initialization
    void Start ()
    {

    }

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

    }

    private void OnApplicationQuit()
    {
        levelGenerator.DestroyNodes();
    }
}

Then in the other script:

public void DestroyNodes()
    {
        GameObject[] nodes = UnityEngine.GameObject.FindGameObjectsWithTag("Node");

        if (nodes.Length == 0)
        {
            //Debug.Log("No nodes to destroy found");
        }
        else
        {
            for (int i = 0; i < nodes.Length; i++)
            {
                DestroyImmediate(nodes[i]);
            }
        }
    }

But the Nodes still exist in the Hierarchy and in the Game and Scene views.

I used a breakpoint it's getting to the OnApplicationQuit

And it's getting to the line:

DestroyImmediate(nodes[i]);

There are 100 objects and it's doing the line for each object.
But then when i make continue they are still exist.

I want that when i quit the game stop the play all the gameobjects to be destroyed.


texts: Why is the "bind pose" one with outstretched arms?

texts:
Something I've often wondered about is the "bind pose". The bind pose for human skeletons is one where their legs are straight, and their arms are perpendicular to their body:

My question is: why? Is such a pose easier for the animators to work with, or the programmers, or both? As far as I understand the math, the bind pose doesn't make a difference to the outcome.


texts:
I'm a student at Ohio State, I hope to be a game developer one day, and I'm on track to be enrolled in the BS Computer Information and Science program in the Arts and Sciences department, but there's another major in the engineering department called Computer Science and Engineering. As you can see, they're virtually the same, except that CSE requires several courses in engineering and higher level math, whereas CIS requires more GE classes, like foreign language. CSE is also accredited, whereas CIS is not.

So I'm wondering, if I want to be a game developer, how important is a knowledge of engineering, if at all? Should I try and get into the CSE program or will I be fine in CIS?


texts: Using a Higher Precision (than 8-bit unsigned integer) Buffered Image for Heightmaps in Java

texts:
I am generating a heightmap for every quad in my quadtree in openCL. The way I was creating the image is as follows:

DataBufferInt dataBuffer =
            (DataBufferInt)img.getRaster().getDataBuffer();
      int data[] = dataBuffer.getData();
      //img is a bufferedimage
        inputImageMem = CL.clCreateImage2D(
        context, CL_MEM_READ_WRITE | CL_MEM_USE_HOST_PTR,
        new cl_image_format[]{imageFormat}, size, size,
        size * Sizeof.cl_uint, Pointer.to(data), null);

This works ok but the major issue is that as the quads get smaller and smaller the 8-bit format of the buffered image starts to cause intolerable "stepping" issues as seen below:

I was wondering if there was an alternate way I could go about doing this?

Thanks for the time.


texts:
I'm using bullet to create a 2D topdown game. In my physics proof of concept, I can walk around and push a box. However, if I walk too fast the character goes through the box, instead of colliding with it. See gif:

This seems like a common thing to me. However, I cannot find other people having the same problem, so that's why I'm asking a question directly. I'm using a DiscreteDynamicsWorld with two rigid bodies which I step through at 60Hz.

Why does this happen?
Is there a way to tune bullet to support higher speeds and prevent this issue?

Help is very much appreciated.

Edit

Regarding the question about how I setup collision shapes:

btConvexHullShape shape;
shape.addPoint({-size, size, 0.0f});
shape.addPoint({size, size, 0.0f});
shape.addPoint({size, -size, 0.0f});
shape.addPoint({-size, -size, 0.0f});


texts:
I was wondering if there's any way to know if the "player" is signed in or not?

Something like this:

if (GamePad.GetState(PlayerIndex.Two).IsConnected && !Gamer.PlayerTwo.IsSignedIn)

So that the controller is connected and it can be used, but the player is not signed in to an account. Something like a guess.


texts: What's the best way to save scores per level in android?

texts:
I'm in the middle of programming a tile based puzzle game, then i realized i don't have any good ways to save data. For the moment i'm using these long combined strings for sharedpreferences and i'm very sure SharedPreferences isn't designed to keep all my per level scores.

I've got 63 levels, spread into 7 difficulties, and all scores(stars granted) is saved like this:

prefs.edit().putInt("achievedstars"+current_difficulty+"_"+current_level, stars_granted).commit();

This means i am saving 63 of those strings as for only the stars granted for the levels. I also want to save "best amount of moves", "time used", and possibly more.

The game is not going to have a leaderboard, or communicate with others devices (although it may allow posting scores to FaceBook, twitter etc.)

Another thing that might be useful to mention is that the file should not be accessible(or atleast not readable enough for people to cheat)

What would you suggest as the best way of saving stats like this from android applications?


texts:
I'm currently working on a game for university in DirectX 11.

I have tried to add in a depth buffer to my project, but since adding it in none of my objects show.

//Describe the Depth/Stencil Buffer
D3D11_TEXTURE2D_DESC db;
db.Width = Width;
db.Height = Height;
db.MipLevels = 1;
db.ArraySize = 1;
db.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
db.SampleDesc.Count = 1;
db.SampleDesc.Quality = 0;
db.Usage = D3D11_USAGE_DEFAULT;
db.BindFlags = D3D11_BIND_DEPTH_STENCIL;
db.CPUAccessFlags = 0;
db.MiscFlags = 0;

//Create Depth View
hr = g_pd3dDevice->CreateTexture2D(&db, NULL, &g_depthBuffer);
if (FAILED(hr)) {
    MessageBox(NULL, L"Error.", L"Error", MB_OK);
}
g_pd3dDevice->CreateDepthStencilView(g_depthBuffer, NULL, &g_depthView);
//g_pd3dDevice->CreateDepthStencilState(&db, &g_depthStencil); //When uncommented, the '&db' shows the following error.
//argument of type "D3D11_TEXTURE2D_DESC*" is incompatible with parameter of type "const D3D11_DEPTH_STENCIL_DESC*"

//Set Render Target
g_pImmediateContext->OMSetRenderTargets( 1, &g_pRenderTargetView, g_depthView );

    void Render()
{
    //Update our time
    static float t = 0.0f;
    if ( g_driverType == D3D_DRIVER_TYPE_REFERENCE )
    {
        t += ( float )XM_PI * 0.0125f;
    }
    else
    {
        static ULONGLONG timeStart = 0;
        ULONGLONG timeCur = GetTickCount64();
        if (timeStart == 0)
            timeStart = timeCur;
        t = (timeCur - timeStart) / 1000.0f;
    }

    //
    // Animate the cube
    //
    //g_World = XMMatrixRotationY( t );

    //
    // Clear the back buffer
    //
    g_pImmediateContext->ClearRenderTargetView( g_pRenderTargetView, Colors::MidnightBlue );
    //g_pImmediateContext->ClearDepthStencilView( g_depthView, D3D11_CLEAR_DEPTH | D3D11_CLEAR_STENCIL, 1.0f, 0 );

    //
    // Update variables
    //
    ConstantBuffer cb;
        //cb.mWorld = cube1;
    cb.mWorld = XMMatrixTranspose( cube1 );

    cb.mView = XMMatrixTranspose( g_View );
    cb.mProjection = XMMatrixTranspose( g_Projection );
    g_pImmediateContext->UpdateSubresource( g_pConstantBuffer, 0, nullptr, &cb, 0, 0 );

    //
    // Draws first square
    //

    g_pImmediateContext->VSSetShader(g_pVertexShader, nullptr, 0);
    g_pImmediateContext->VSSetConstantBuffers(0, 1, &g_pConstantBuffer);
    g_pImmediateContext->PSSetShader(g_pPixelShader, nullptr, 0);
    g_pImmediateContext->DrawIndexed(36, 0, 0); //36 vertices needed for 12 triangles in a triangle list

    ConstantBuffer cb2;
        //cb2.mWorld = cube2;
    cb2.mWorld = XMMatrixTranspose(cube2);

    cb2.mView = XMMatrixTranspose(g_View);
    cb2.mProjection = XMMatrixTranspose(g_Projection);
    g_pImmediateContext->UpdateSubresource(g_pConstantBuffer, 0, nullptr, &cb2, 0, 0);

//  g_pImmediateContext->VSSetShader(g_pVertexShader, nullptr, 0);
//  g_pImmediateContext->VSSetConstantBuffers(0, 1, &g_pConstantBuffer);
//  g_pImmediateContext->PSSetShader(g_pPixelShader, nullptr, 0);
    g_pImmediateContext->DrawIndexed(36, 0, 0);

    //cube1 = XMMatrixIdentity();

    //
    // Present our back buffer to our front buffer
    //
    g_pSwapChain->Present( 0, 0 );
}

void Update()
{
    rot += 0.0005f;
    if (rot > 6.26f)
        rot = 0.0f;

    cube1 = XMMatrixIdentity();

    XMVECTOR rotaxis = XMVectorSet(0.0f, 1.0f, 0.0f, 0.0f);
    Rotation = XMMatrixRotationAxis(rotaxis, rot);
    Translation = XMMatrixTranslation(1.0f, 1.0f, 0.0f);

    cube1 = Translation * Rotation;

    cube2 = XMMatrixIdentity();

    Rotation = XMMatrixRotationAxis(rotaxis, -rot);
    Scale = XMMatrixScaling(0.5f, 0.5f, 0.5f);

    cube2 = Scale;
}

From what someone else had mentioned, that I'm either not creating a D3D11DepthStencilState or not clearing the depth stencil view.
I've tried to fix the problem, but no luck so far.


texts:
I have some questions regarding the XXSetShader and what happens after, for instance I would like to know if when XXSetShader is called the subsequent calls would be bound to that particular shader, like PSSetShaderRsources. Because at load time I am bounding the resource views needed for that particular shader, then the next one and so on, but what I found is that the resources were not bound, I need to set them again every time the XXSetShader is called.

Am I doing something wrong? it's not supposed to work like that, the purpose of this is to have the least change states at runtime.

Thanks.


texts: Why every character I drag to timeline is disabled in the timeline?

texts:
I dragged 3 different characters to the timeline window and each one asked for track so I did animation track for all of them but on each track on the left side there is a yellow triangle say "The component is disabled"

I created cinemachine virtual camera and it added the brain component to the main camera and created a timeline automatic for the virtual camera but when dragging a character to the timeline window I'm getting this yellow triangle with the message it's disabled.

You can see in the screenshot on the left side in the timeline window the yellow triangles with the message.


texts: Android Game-Loop (rendering & logic removed, but still 'skipping frames')

texts:
Overview

Guys really hoping for some help here. My game loop is based on code from Fix Your Timestep!.

I've read the article more than a few times, but I can't quite work out what exactly is supposed to be going on within the loop.

I'm running my code on a Nexus 10 tablet which has VSync set to 60fps.

Playing catch up

When I run my code, I'm getting caught quite often in the while loop, ie it runs my logic more than once - so runs logic twice in a row before rendering).

With my understanding of the loop, this should happen when rending takes too long to fit into the time slice (which is 16.66666666666667ms).

So, maybe in 'normal circumstances', I would expect this to happen occasionally).

However, I've tried removing all rendering and logic updating and just running a skeleton loop and I'm still getting caught regularly and constantly within the 'while-loop'.

Therefore, when I'm running my game (with rendering and logic), I'm getting a lot of stuttering because I know the loop is going to skip frames.  The logic updates are however being capped at 60 which is exactly what I want.

Obviously whether or not my rendering or physics update could be more efficient is not the issue here and is a question for another day as I've already removed that from the equation.

I can smooth things out somewhat with interpolation and it really does make a difference, however, it's not as smooth as some of the games I download from the Play Store and I really need to make it better.

So, what am I missing or not understanding?  I would think it should (certainly with no rendering or logic updating to create a bottleneck):

Enter the while-loop
Exit the while-loop
Wait for next VSync
And repeat

Here is the loop I'm testing with:

@Override
public void onDrawFrame(GL10 gl) {

    newTime = System.currentTimeMillis()*0.001;
    frameTime = newTime - currentTime; //Amount of time this entire frame took
            if ( frameTime > (0.25))
                frameTime = (0.25);

            currentTime = newTime;
            accumulator += frameTime;

            //Update logic
            while (accumulator >= dt){
//              saveGameState();  //Removed for testing
//              updateLogic(dt);  //Removed for testing
                accumulator -= dt;
            }

            //Get the amount to interpolate by
//              interpolation = (float) (accumulator / dt);  //Removed for testing
//              render(interpolate);                         //Removed for testing

}


texts: How to change mobile device screen size in Unity for testing?

texts:
For an experiment I need to be able to dynamically adjust the screen size of my device. I'm using a Nexus 5 (5") and want to fake the screensize to 2", 3", 4",.. See images:

Is this possible using Unity? I'm aware that I can easily place some planes right in front of my camera, but I'm looking for a proper solution.


texts:
I'm rendering equilateral triangles of different sizes and I'm having trouble making them symmetric along the vertical axis. Here I have rendered two triangles. The triangle on the left (rendered correctly) has the coordinates (0.0, 0.0), (-7.0, 14.0) and (7.0, 14.0). The triangle on the right, on the other hand, has the coordinates (0.0, 0.0), (-7.0, 15.0) and (7.0, 15.0) and is not symmetric along the vertical axis.

Here are the matrices I'm using:

glm::mat4 model_matrix = glm::translate(glm::mat4(1.0f), glm::vec3(90.0f, 90.0f, 0.0f));
glm::mat4 view_matrix = glm::mat4(1.0f);
glm::mat4 projection_matrix = glm::ortho(0.0f, w * 1.0f, h * 1.0f, 0.0f);
glm::mat4 mvp_matrix = projection_matrix * view_matrix * model_matrix;

I'm aware of the diamond exit rule but I don't think that's the cause of the problem. Seems like the diamond exit rule only applies to line segments? This problem also exists when I try to make triangles symmetric in the horizontal axis. Cheers!


texts: Compute shader: Property at kernel index is not set

texts:
I am trying to follow this excellent Coding Adventure: https://www.youtube.com/watch?v=lctXaT9pxA0 in order to get a very simple mesh deformation on a mesh using a compute shader.
I'm getting an error that reads:

Compute shader (NewComputeShader): Property (vertices) at kernel index (0) is not set
UnityEngine.ComputeShader:Dispatch(Int32, Int32, Int32, Int32)
MoonShader:runShader() (at Assets/MoonShader.cs:27)
MoonShader:Update() (at Assets/MoonShader.cs:15)

I'm calling runShader() in Update (maybe that's a terrible idea, but I don't think it's contributing to this specific problem yet).
Do I need to somehow pass my mesh's vertices into StructuredBuffer<float3> vertices;? If so, how am I supposed to do that?
This is the call to the compute shader in my .cs file.
void runShader() {
    int kernelHandle = computeShader.FindKernel("CSMain");
    computeShader.Dispatch(kernelHandle, 512, 1, 1); //this is the line it appears to be complaining about
}

This is my .compute file.
#pragma kernel CSMain
StructuredBuffer<float3> vertices;
RWStructuredBuffer<float> heights;
uint numVertices;
float testValue = 20;

[numthreads(512,1,1)]
void CSMain (uint id : SV_DispatchThreadID) {
    if(id >= numVertices) {

    } else {
        float3 vertexPosition = vertices[id];
        heights[id] = 1 + sin(vertexPosition.y * testValue) * 0.05;
    }
}

Link to repo if it's helpful: https://github.com/glenpierce/proceduralPlanets


texts: Character Controller + Lag = Massive Teleportation Through Walls

texts:
I'm working on a fairly robust game with another developer and we've been having a really serious issue with (I believe) the character controller. Specifically, if there's ever a large lag spike (as there are somewhat frequently - the code's not well optimized in some parts) there's a chance that the character controller will wing right through all nearby colliders and fall out of bounds.

It happens pseudo randomly, but I've noticed that it seems to be somewhat predictable, such as standing next to certain objects (nothing weird about them - just tables with colliders).

The lag often is a cause of large chunks of a level having SetActive(true) called on them in one frame or multiple objects being instantiated in one frame. These objects sometimes have colliders/rigidbodies attached but don't seem to be in any direct contact to the character controller.

I can very consistently make it happen by moving towards certain walls (again, very normal walls) and alt-tabbing while my character is still moving also seems to cause the issue predictably, which is VERY strange.

Has anyone ever experienced anything like this with the character controller? I'd give a code sample but honestly not even sure where from the codebase would be pertinent other than

if (Time.deltaTime < 0.15f)
{
    if (applyGravity && noClip == false)
        moveDirection.y -= gravity * Time.deltaTime;

    controller.Move(moveDirection * Time.deltaTime);
}

Which seems awfully straightforward to me. Obviously moveDirection gets changed elsewhere in the function too but it's all similarly bland. I'm pretty experienced with this sorta' stuff and it doesn't ring wrong to me at all.

Some other stuff.

Checked that moveDirection isn't a huge number

Tried eliminating Time.deltaTime from the equation

Fairly sure colliders aren't ending up inside of the player while a lag spike happens (again, alt-tabbing will do it too)

Geometry surrounding the player is clean (box colliders, mesh colliders on well-developed meshes)

Nothing strange like rapidly setting any components on or off is happening to my knowledge.

Anyone have any experience with this sort of issue?


texts: why one model can have different vertices and normal size?

texts:
I am using TinyObj to load models.  I found many obj files have different vertices and normal size, how could it happen?  I thought in the obj file one normal should be correspond to one vertex.

For example, I am loading one apple model, the vertices size is 6492 and normal size is 6557.  How to handle this stituation?  Some files have more vertices and some have more normals. Does it means I have to give up some attributes of the model?

I also found the obj file has normal index, but I dont know how to use it.  Does it matter to this problem?

In opengl/directx I have only used vertex index in the index buffer.

Can you give me some idea or reference about it?


texts: Two graphical entities, smooth blending between them (e.g. asphalt and grass)

texts:
Supposedly in a scenario there are, among other things, a tarmac strip and a meadow. The tarmac has an asphalt texture and its model is a triangle strip long that might bifurcate at some point into other tinier strips, and suppose that the meadow is covered with grass.

What can be done to make the two graphical entities seem less cut out from a photo and just pasted one on top of the other at the edges? To better understand the problem, picture a strip of asphalt and a plane covered with grass. The grass texture should also "enter" the tarmac strip a little bit at the edges (i.e. feathering effect).

My ideas involve two approaches:

put two textures on the tarmac entity, but that involves a serious
restriction in how the strip is modeled and its texture coordinates
are mapped

or

try and apply a post-processing filter that mimics a bloom effect where "grass" is used instead of light. This could be a terrible failure to achieve correct results.

So, is there a better or at least a more obvious way that's widely used in the game dev industry?

UPDATE:

This is a conceptual question, I do not require a specific shading language or framework.  In real life, I use Cg with Ogre for rendering experiments. If I supply two textures and two different texture coordinate sets for the tarmac entity, I can analyze the second texture coordinate set in the fragment shader and do some blending depending on the .y component of the uv pair, but that requires the artist to hand-craft every asphalt/tarmac runway in the scenario and it looked to me that this is probably the wrong way to tackle the issue.


texts: Animator.SetTrigger does not trigger an Animation

texts:
I have a basic animator setup for my Unity Character which has a "block" functionality when pressing the E key. So far, so good.

However I've made a transition from "Blocking Idle" to "Blocking_React" (which means that the character was hit) using a Trigger "tookDamage" (default to false).
The problem is that the character gets hit but does not transition to "Blocking_React" animation.

Code Sample:

//From Character Controller script
if (Input.GetKeyDown(KeyCode.E) && !_isBlocking)
        {
            _animator.SetBool("isBlocking", true);
            _isBlocking = true;
        }
        else if (Input.GetKeyUp(KeyCode.E) && _isBlocking)
        {
            _animator.SetBool("isBlocking", false);
            _isBlocking = false;
        }
//------------------------
//From my Character script

public void TakeDamage(float damage)
    {
        health -= damage;
        this.GetComponent<Animator>().SetTrigger("tookDamage");
    }

And this is my transition:

Am I missing something?


texts: Changing long float to number + short scale

texts:
I am looking to use a piece of code to take an extremely long number and convert it to decimal equivalent + short scale. (i.e. 120100000000 would be 120.1 Billion)

I am doing this with two separate scripts but this can be condensed into a single one. I am trying to look for a recurring process instead of the massive amount of if statements currently running in the script.
This is being done with an external array in Unity that holds the strings for short scale. (billion,trillion, etc)

Trying to find a recurring model that will look for the length, and attach it to the appropriate array object.

using UnityEngine;
using System.Collections;
using UnityEngine.UI;

public class amountText : MonoBehaviour {
    public Text text;
    public Text numberPref;
    public string[] values;
    public static float number = 1000f;

    private float numberLength;
    private float remainder;
    private float increaseAmount = 5000f;

void Start () {
    text = GetComponent <Text>();
}
void Update () {
    text.text = Mathf.RoundToInt(number).ToString();
    numberLength =  Mathf.RoundToInt(number).ToString().Length;
    if(numberLength <9) {
        text.text = Mathf.RountToInt(number).ToString();
        numberPref.text = (" ");
    }
    if(numberLength > 9 && numberLength =< 12) {
        text.text = number/1E-9;
        numberPref.text = (values[0]);
    }
    if(numberLength > 12 && numberLength =< 15) {
        text.text = number/1E-12;
        numberPref.text = (values[1]);
    }
    if(numberLength > 15 && numberLength =< 18) {
        text.text = number/1E-15;
        numberPref.text = (values[2]);
    }

}
}


texts:
Given a map created with procedural generation algorithms, should the server transmit the seed used to generate this map (so client must contain the same algorithm) or maybe send all the information?.

I'm inclined to send the seed, i have in mind generating big maps. Right now, i have one seed to generate multiples seeds, and each one is used to generate a chunk, so this last seed would be transmited to each client everytime someone needs information about a new chunk.


texts: Data Structure to Represent Connections Between Countries on a Map

texts:
In a game I'm developing for a client a key game concept involves moving around on a map. In this case the sizes and shapes and such of the various countries are irrelevant: moving from one country to an adjacent country counts as a single step.

I'm trying to figure out the best data structure for internally representing the connections between the countries. For a given country the game needs to know which countries are adjacent, both to know which ways the players can move as well as for allowing the game's AI to plot out routes, determining possible paths from one country to another. The AI also needs to evaluate how well-connected a country is, not just to its immediately-adjacent neighbors but to the neighbors of those countries, etc.

I've figured out a couple of possibilities but they seem ungainly and inefficient. Because the AI will need to calculate a bunch of possible routes in order to make good decisions about its movement, "inefficient" is highly problematic.

I suspect that this is a somewhat common CS puzzle and that there's a common solution, but I've not been able to find much by searching. Any suggestions are welcome.


texts: Issue with variables in GameMaker Studio

texts:
I am having issues coding a game, in terms of variables in objects. Whgen running i get this error

FATAL ERROR in
action number 1
of  Step Event0
for object obj_text_demo_player:

Variable obj_gameManager.<unknown variable>(100020, -2147483648) not set before reading it.
at gml_Object_obj_text_demo_player_StepNormalEvent_1 (line 1) - if  (obj_gameManager.ammo == 0)

and i have no clue hope to fix this, this is where the code is used.

obj_player (player - where the issue seems to be - STEP EVENT)

if (obj_gameManager.ammo == 0)
{
     obj_gameManager.weapon = "MachineGun";
    obj_gameManager.ammo = 50000;
};

obj_pickup (pickup object - COLLISION /W PLAYER OBJECT)

obj_gameManager.weapon = "Tri-Shooter";
obj_gameManager.ammo = 900;

Obj_gameManager (object variables are from - DRAW EVENT)

global.health = 100;
global.weapon = "MachineGun";
global.ammo = 50000;

draw_healthbar(787,181,1073,231,health,c_white,c_red,c_green,0,true,true);

draw_set_colour(c_blue);
draw_set_font(fnt_speach_new);
draw_text(780, 300, global.weapon );
draw_text(780, 375, global.ammo );

Any help would be massively appreciated, as I'm new to Game Maker Studio. If you need any more info I'm happy to add it.


texts: Frustum culling with third person camera

texts:
I have a third person camera that contains two matrices: view and projection, and two Vector3's: camPosition and camTarget. I've read up on frustum culling and it makes it seem easy enough for a first person camera, but how would I implement this for a third person camera? I need to take into effect the objects I can see behind me too. How would I implement this into my camera class so it runs at the same time as my update method?

    public void CameraUpdate(Matrix objectToFollow)
    {
        camPosition = objectToFollow.Translation + (objectToFollow.Backward *backward) + (objectToFollow.Up * up);
        camTarget = objectToFollow.Translation;

        view = Matrix.CreateLookAt(camPosition, camTarget, Vector3.Up);
    }

Can I just create another method within the class which creates a bounding sphere with a value from my camera and then uses the culling based on that? And if so, which value am I using to create the bounding sphere from?

After this is implemented, I'm planning on using occlusion culling for the faces of my objects adjacent to other objects. Will using just one or the other make a difference? Or will both of them be better? I'm trying to keep my framerate as high as possible


texts: SDL2, OpenGL, Nvidia laptop screen tearing

texts:
EDIT 2017-05-14 dvb. Issue still active to this very day, see geforce forum link in main question.

Note 3: "Stoltverd" has posted a "fix guide" on geforce forum. It has workarounds for non-OpenGL games.

https://forums.geforce.com/default/topic/1008527/geforce-mobile-gpus/-guide-diagonal-screen-tearing-problems-with-optimus-nvidias-control-panel-not-working-like-it-should-need-a-fix-get-in-here/

Note 4: My workaround for OpenGL games: use HDMI output to external monitor. (In my case, the only game I care about is my own, and I use a big cheap HDMI TV for demo.)

EDIT 2016-03-06.

Note 1: Apparently this is a known issue with Nvidia.
If you've found here due to same problem, please stoke the collective "please fix it" by filing a "question" at https://nvidia.custhelp.com/app/ask.

Note 2: Doesn't happen on external monitor. Also doesn't happen on internal display if external monitor is mirroring. (Surprise.)

I'm developing my game directly in C++, OpenGL, and SDL2.

On an Alienware 15 R2 laptop with Nvidia GTX 965M, I get screen tearing in a curious diagonal line like shown below. It goes across the window top left to bottom right.

The image below is taken during a screen fade-in, so shows just a brightness line. But it happens between any two different frames.

If my window is full screen, the line goes top-left to bottom-right of the whole screen.

Same code runs fine (no tearing) on: All macs, same laptop on Intel integrated GPU, desktop PC with Nvidia 730.

Same laptop looks fine with other games, Chrome+Shadertoy, &c.

Main loop looks something like:

// setup code
    SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
    SDL_GL_SetSwapInterval(1);
    flags = SDL_WINDOW_OPENGL;
    SDL_CreateWindow(... ,flags);
// main loop
while(1) {
    this->checkEvents();
    SDL_GL_SwapWindow(this->mainWindow);
    this->doGlDrawing();
}

Grepping forums, I've seen reports of some OpenGL games showing this on Alienware & other Dell laptops.

All suggestions welcome! Thanks.

Edit 2016-02-20, some links to similar user-side reports:
  https://forums.geforce.com/default/topic/903422/geforce-mobile-gpus/diagonal-screen-tearing-issues-on-gtx-860m-870m-960m-965m-970m-980m-/

http://en.community.dell.com/owners-club/alienware/f/3746/t/19658623

https://www.reddit.com/r/Alienware/comments/427ltv/anyone_have_diagonal_screen_tearing_when_playing/


texts:
I have been developing a game using XNA and am now at a point in the production of my game where I am testing out how the user will install the game. I know that XNA provides the usual ClickOnce publish option and also has the ability to use custom installer packages but my question goes a bit beyond that.

Part of my game (seeing as it will be my first available to the public) analyses the progress of the user and sends a metrics file to a database I have hosted on a website. That system is all set up and working however I want to prompt the user during installation to ask if sending this file is alright with them, and only have the game perform such as task with their consent.

My question is this, how do I, with either a custom bootstrapper for ClickOnce or any other installer package, convey to my game that the player has consented or not? I found this helpful tutorial which is on the right track but that just stops installation if the user selects "No".

Any suggestions are appreciated,
Thanks in advance.


texts: Drawing Sprites at Correct Z-Index without A Sprite Map?

texts:
My game is in HTML5 canvas, but I assume this concept applies to any language.

In the past I've used a multi-dimensional array to keep track of sprite positions.  Here is a simplified example:

[
[ [],[[plant12]],[],[],[] ],
[ [],[[apple]],[],[],[] ],
[ [],[],[],[],[] ],
[ [[apple]],[],[[apple]],[],[] ],
[ [],[],[],[],[] ],
]

And this would always draw sprites with the correct z-index, as the map was always read left-to-right, top-to-bottom:

But with a more experienced game developer's advice, I started using quad trees for collision.

Since I will have a tree of objects with x/y coordinates, I thought I might as well abandon using a sprite map, and just draw the sprites based upon the quad tree data.

But the problem is that if the objects are not collected in a precise order, the sprites will be drawn in incorrect order, resulting in such:

If I am not using a sprite map, what is the best way for me to ensure I am drawing sprites in the correct order/z-index?

I am thinking that maybe I will make a collection method for the quad tree that will collect objects from a left->right, top->bottom order, and then draw each object's corresponding sprite in a loop.  But honestly, that sounds a lot less inefficient that a having a predefined map, especially considering that all that traversing is a lot of recursive calls.

Another approach is to create some sort of z-index system, but I think that may be over-complicating things as well.

Any advice on how to approach this?


texts: What is the ballpark GL framerate for iPad and iPhone 4?

texts:
Does anyone the GL frame rate for iPad and iPhone 4 under the follow conditions:

Unlit
Non supersampled
GLSL texture mapped with two textures.
Single quad, 4 vertices

Thanks,
Doug


texts: Mesh complexity vs Texture Size (Performance)

texts:
From a performance view, which is preferable:

A higher detailed meshes with small textures (like 32x32 pixels)
or
A less detailed mesh with a bigger texture (like 1024x1024 pixels)?

Additional info.
I'm making a low poly project. Since I'm only using big textures for "alpha FX" (simulating complex geometry just by erasing the alpha on faces), I wonder if this is a bad approach.
I could add like 50~150 triangles per model to avoid using a higher texture per asset and made those "FX" directly on geometry (since erasing on a texture very small would look very bad)

Which is the "trend"? Which has more impact on performance?

Thanks.


texts: How to code a non-newtonian spaceship control script?

texts:
I'm working on a simple 3D space combat game, and I've decided to go with simplified physics over proper newtonian motion, similar to the space sim Oolite, and more 'arcade' style games.  I basically want my ships to move how spacecraft do in Star Wars.

This is what I'm trying to achieve specifically; ability to rotate along each axis, and with solely forward motion relative to the spacecraft.  In the case of impacts and collisions I want to spacecraft to move under normal physics, but for any rotation/velocity incurred by the collision to quickly bleed off.

I can find a lot of tutorials that show how to achieve this kind of flight by setting angular drag and such in a standard aircraft controller.  This seems like it is a waste of resources however, since you are using the drag equations to cancel out the newtonian thrust equations.  Since I'm aiming for hundreds of ships in a single battle I need to keep things as efficient as possible.

So is there a simpler, more efficient way to have this kind of controller?


texts: Generic multiple containers derived classes for Entity System

texts:
I am working on an entity system for a game. I have read that cache is very important with the common operation of iterating over entities and their components.

Currently I have a class World that contains the list of entities, and a list of each component.

class World {
  vector<Entity> entities;
  vector<PositionComponent> position_components;
  vector<SpeedComponent> speed_components;
  ...
};

The idea of this, is to have entities and components contiguous in memory to be cache-friendly.

The problem is that you have to write specific code for each different component, as it is hardcoded in the source code. One solution could be to have a matrix of Component*, where the i-th row of the matrix are all PositionComponents, and so on. The problem with this, is that with the pointers you don't have the memory continuous and break with the cache-friendly.

What would the best way to write generic code and still have cache-friendly data?


texts: Redundant checks from spatial partitioning

texts:
A simple 2D grid partition system for collision detection divides space into equal-sized tiles. Colliders then map themselves to tiles with their bounding box in O(1) time. Collision detection only has to be performed between objects that occupy the same tile(s).

Collision detection is expensive so the more culled, the better. With a grid partitioning system, how are collisions culled when colliders share multiple tiles?

For example, Circle_A and Circle_B both sit on the edge between Tile_1 and Tile_2. Iterating both tiles would make collision detection between Circle_A & Circle_B run twice.

A global pair hashtable seems performance expensive since it has to be cleared every frame. Tracking pairs inside colliders takes a lot of memory. How do you mitigate redundant pairs when iterating through partition grid tiles?


texts: How can I move game objects using keyboard in the Unity scene editor?

texts:
I know I can click on the "move" button

and use my mouse to drag the object around. How can I do the same using my keyboard?


texts: What are the formulas which represent the horizontal and vertical displacement of an arrow in flight (as well as it angle)? I would like to make sure that I take into consideration the arrow's fluid dynamics and center of gravity.


texts: Creating a rotation offset based on camera position with XNA

texts:
I have an XNA project where characters have the ability to pick up and move objects around (in 3d). When an object is picked up by a character, I want ithe objects position to always be out in front of the character (as if the character was holding it in their arms). I'm having trouble creating the offest using the charactors forward vector. The main issue is that I don't know how to properly incorporate the characters rotation into the objects position. I'm hoping somebody can give me an example of how to accomplish this to help point me in the right direction. Thanks!

Currently I'm just matching the held object's world matrix with the characters as a work around:

grabbedSceneObject.World = Matrix.CreateScale(20F) * Matrix.CreateTranslation(viewPosition);


texts:
OK, so I successfully learned how to bind textures to quads and display this cool looking crate. However, when I rotate the cube something goes wrong. During rotation the back-face of the cube overlays the front-face and appears in front of the front-face. This is also the case with the right and left faces. They overlay each other giving a weird perception. I'm not sure why this happens. Here is the code where I draw only four face of the quad (front, back right, left).

gl.glClear(GL2.GL_COLOR_BUFFER_BIT | GL2.GL_DEPTH_BUFFER_BIT);      // clear the screen and depth buffers
gl.glLoadIdentity();                            // reset the current modelview matrix

    // draw quad
    gl.glTranslatef(0.0f, 0.0f, -6.0f);                 // translate to the left and into the screen
    gl.glRotatef(rotateAngle, 0.0f, 1.0f, 0.0f);        // rotate triangle around the y-axis
    gl.glBindTexture(GL2.GL_TEXTURE_2D, textures[2]);   // bind the texture you want to use to gl_texture_2d
    gl.glBegin(GL2.GL_QUADS);

        // front face
        gl.glTexCoord2f(0.0f, 1.0f);                // bottom left
        gl.glVertex3f(-1.0f, -1.0f, 1.0f);
        gl.glTexCoord2f(1.0f, 1.0f);                // bottom right
        gl.glVertex3f(1.0f, -1.0f, 1.0f);
        gl.glTexCoord2f(1.0f, 0.0f);                // top right
        gl.glVertex3f(1.0f, 1.0f, 1.0f);
        gl.glTexCoord2f(0.0f, 0.0f);                // top left
        gl.glVertex3f(-1.0f, 1.0f, 1.0f);

        // right face
        gl.glTexCoord2f(0.0f, 1.0f);                // bottom left
        gl.glVertex3f(1.0f, -1.0f, 1.0f);
        gl.glTexCoord2f(1.0f, 1.0f);                // bottom right
        gl.glVertex3f(1.0f, -1.0f, -1.0f);
        gl.glTexCoord2f(1.0f, 0.0f);                // top right
        gl.glVertex3f(1.0f, 1.0f, -1.0f);
        gl.glTexCoord2f(0.0f, 0.0f);                // top left
        gl.glVertex3f(1.0f, 1.0f, 1.0f);

        // left face
        gl.glTexCoord2f(0.0f, 1.0f);                // bottom left
        gl.glVertex3f(-1.0f, -1.0f, -1.0f);
        gl.glTexCoord2f(1.0f, 1.0f);                // bottom right
        gl.glVertex3f(-1.0f, -1.0f, 1.0f);
        gl.glTexCoord2f(1.0f, 0.0f);                // top right
        gl.glVertex3f(-1.0f, 1.0f, 1.0f);
        gl.glTexCoord2f(0.0f, 0.0f);                // top left
        gl.glVertex3f(-1.0f, 1.0f, -1.0f);

        // back face
        gl.glTexCoord2f(0.0f, 1.0f);                // bottom left
        gl.glVertex3f(-1.0f, -1.0f, -1.0f);
        gl.glTexCoord2f(1.0f, 1.0f);                // bottom right
        gl.glVertex3f(1.0f, -1.0f, -1.0f);
        gl.glTexCoord2f(1.0f, 0.0f);                // top right
        gl.glVertex3f(1.0f, 1.0f, -1.0f);
        gl.glTexCoord2f(0.0f, 0.0f);                // top left
        gl.glVertex3f(-1.0f, 1.0f, -1.0f);

    gl.glEnd();

Moreover, the way I draw textures and then vertices is not yet clear to me. According to what I've read the bottom-left corner (0, 0) is where the textures start drawing, so I should also start drawing my quad from bottom-left accordingly. I tried that but it didn't work. The texture was drawn, but up side down. So I had to go through some trial and error till I got the texture drawn correctly. I wish I could attach a picture to this post so I can show you how the back face of the cube overlays the front one during rotation, but I think this facility isn't provided in stack exchange. Thanks.


texts:
I'm trying to implement a system whereby a "shield flare" will be shown whenever a projectile impacts the shield. The shield itself is one like in Star Wars, where it's more like a skin around the spaceship, rather than a simple bubble.

The problem I'm having is determining how to draw a simple flare effect where the projectile impacted the shield. I can determine the Vector2 point where the shield was hit. Right now, I'm able to show the whole shield whenever it's hit just fine.

The problem as I see it, is that I somehow need to mask out the shield, except for a few pixels around the point of impact. Either that, or I'm going about this the completely wrong way.

What I can do so far is draw the whole shield:

What I need is to be able to draw a piece of the shield on the point of impact:

Any help would be appreciated.


texts: How do I call the sprite auto-slicer from a script in the Unity editor

texts:
First of all let me start with an apology. I know this may not be the right place for this question, but the good people over at stackoverflow did not answer me and neither did I get a answer over at Unity Answers, so I'm hoping that someone here will know. So without further ado here is my problem.

I'm writing my own asset importer and would like to automatically slice the sprite sheet.Slicing it with a grid is not viable since we have sprites with different sizes and I need to use the automatic slice option form the Sprite Editor. So far if the imported file has "sheet" in the name I can set all the properties I want. All that is left is do the automatic slicing but I cant even find anything in the documentation. Is this even possible ?

Edit: here is a screen shot. I want to access this functionality from my custom EDITOR script.

In simples words I want to click this button from a script instead of the artist when he imports a new spritesheet.


texts: Splitting Graph into distinct polygons in O(E) complexity

texts:
If you have seen my last question:
trapped inside a Graph : Find paths along edges that do not cross any edges

How do you split an entire graph into distinct shapes 'trapped' inside the graph(like the ones described in my last question) with good complexity?

Please note each vertex has a fixed x,y position.

What I am doing now is iterating over all edges and then starting to traverse while always taking the rightmost turn. This does split the graph into distinct shapes. Then I eliminate all the excess shapes (that are repeats of previous shapes) and return the result.

The complexity of this algorithm is O(E2). I am wondering if I could do it in O(E) by removing edges I already traversed previously. My current implementation of that returns unexpected results.


texts: How do you handle scripting in multithreaded environment

texts:
In my experience, two approaches are preferred when people want to handle scripting in multithreaded environment.

Synchronize every accesses to scripting module with one coarse-grained lock.
No Synchronization - Scripting module should be used by just one logic thread.

Of course, both solutions are not scalable in multi-core perspective.

Question - Is there any other (multi-core) scalable solution?


texts: How can I make my animation switch frames automatically without pressing any keys?

texts:
So I have been trying to figure out for so long how I can loop the frames on my animation automatically without entering user input to prompt movement of my object.
I have four different frames for a sprite which I would like to loop, but at the moment it only shows the first frame. Here is the relevant code for my Play class (as the entire thing is too long):

package simpleslickgame;

import org.newdawn.slick.*;
import org.newdawn.slick.state.BasicGameState;
import org.newdawn.slick.state.StateBasedGame;

import java.util.Random;

public class PlayScreen extends BasicGameState {

    Image enemy;
    int enemyX = 800;
    int enemyY = 500;

    int RandomX;
    int RandomY;

    Animation blobfish, one, two, three, four;

    public PlayScreen(int state) {
    }

    public void init(GameContainer gc, StateBasedGame sbg) throws SlickException {
        enemy = new Image("C:\\Users\\User\\IdeaProjects\\Slick2D\\src\\main\\resources\\enemy.png");

        Image[] blobfishOne = {new Image("C:\\Users\\User\\IdeaProjects\\Slick2D\\src\\main\\resources\\blob-one.gif"), new Image("C:\\Users\\User\\IdeaProjects\\Slick2D\\src\\main\\resources\\blob-one.gif")};
        Image[] blobfishTwo = {new Image("C:\\Users\\User\\IdeaProjects\\Slick2D\\src\\main\\resources\\blob-two.gif"), new Image("C:\\Users\\User\\IdeaProjects\\Slick2D\\src\\main\\resources\\blob-two.gif")};
        Image[] blobfishThree = {new Image("C:\\Users\\User\\IdeaProjects\\Slick2D\\src\\main\\resources\\blob-three.gif"), new Image("C:\\Users\\User\\IdeaProjects\\Slick2D\\src\\main\\resources\\blob-three.gif")};
        Image[] blobfishFour = {new Image("C:\\Users\\User\\IdeaProjects\\Slick2D\\src\\main\\resources\\blob-four.gif"), new Image("C:\\Users\\User\\IdeaProjects\\Slick2D\\src\\main\\resources\\blob-four.gif")};

        one = new Animation(blobfishOne, 200,true);
        two = new Animation(blobfishTwo, 200, true);
        three = new Animation(blobfishThree, 200, true);
        four = new Animation(blobfishFour, 200, true);
        blobfish = one;

    }

    public void render(GameContainer gc, StateBasedGame sbg, Graphics g) throws SlickException {

        blobfish.draw(RandomX, RandomY);

        Random enemyX = new Random();
        Random enemyY = new Random();
        RandomX = enemyX.nextInt(1500);
        RandomY = enemyY.nextInt(1000);

    }

    public void update(GameContainer gc, StateBasedGame sbg, int delta) {
        Input input = gc.getInput();
        blobfish.start(); //I thought this would have ran the animation.

        isMoving = true;
        keyispressed = true;

        if (keyispressed) {
            isMoving = true;
        }

    }

    public boolean mouseClicked() {
        return true;
    }*/
    }
        public int getID () {
            return 1;
        }
    }

I did think that the 'blobfish.start();' line would have started the animation.
The variable 'blobfish' is the animation and 'enemy' is the image.

I'm a serious noob when it comes to Java game dev so any help as to why the animation is not running would be greatly appreciated.


texts: How can i save field member value of Scriptable Object when it changed on inspector at runtime?

texts:
Class Foo(monobehavior) has a scriptableObject and it is exposed to Inspector.
When i change its value on inspector on runtime, it is saved.
but when i try to change its value by script on runtime, it is never saved.
what the different?

and is there a way to save changed value of scriptableObject on runtime? without using json.. or something.

Thanks and sorry for my bad english.


texts: Plane is not affected by the light source

texts:
I'm going through a problem and I don't have a reasonable explanation for why this occurs. Basically, I have 3D scene in which there is a light source and simple plane and cube (i.e. .obj models) modeled and exported from Blender. The result with the cube is as follows:

The light source is located at (0,2,0) represented as a while cube and the result of the reflected light on the cube is expected. However when I import the plane model, the result is as follows:

The bottom of the plane should be dark if we are looking from the below of the plane but this is not the case. What things can cause this kind of behavior? Note: the code is identical for both cases.  I use OpenGL and Shaders 3.3 in Windows 10. The API is GLFW.

The plane model is

# Blender v2.78 (sub 0) OBJ File: ''
# www.blender.org
mtllib plane.mtl
o Plane
v -1.000000 0.000000 1.000000
v 1.000000 0.000000 1.000000
v -1.000000 0.000000 -1.000000
v 1.000000 0.000000 -1.000000
vn 0.0000 1.0000 0.0000
usemtl None
s off
f 1//1 2//1 4//1 3//1

whereas the cube model is

# Blender v2.78 (sub 0) OBJ File: ''
# www.blender.org
mtllib cube.mtl
o Cube
v 0.500000 -0.500000 -0.500000
v 0.500000 -0.500000 0.500000
v -0.500000 -0.500000 0.500000
v -0.500000 -0.500000 -0.500000
v 0.500000 0.500000 -0.499999
v 0.499999 0.500000 0.500000
v -0.500000 0.500000 0.500000
v -0.500000 0.500000 -0.500000
vn 0.0000 -1.0000 0.0000
vn 0.0000 1.0000 0.0000
vn 1.0000 0.0000 0.0000
vn -0.0000 -0.0000 1.0000
vn -1.0000 -0.0000 -0.0000
vn 0.0000 0.0000 -1.0000
usemtl Material
s off
f 1//1 2//1 3//1 4//1
f 5//2 8//2 7//2 6//2
f 1//3 5//3 6//3 2//3
f 2//4 6//4 7//4 3//4
f 3//5 7//5 8//5 4//5
f 5//6 1//6 4//6 8//6

I use assimp library to import models in my application. The fragment shader is

#version 330 core
out vec4 FragColor;

uniform vec3 objectColor;
uniform vec3 lightColor;
uniform vec3 lightPos;

in vec3 Normal;
in vec3 FragPos;

void main()
{
    float ambientStrength = 0.1;
    vec3 ambient = ambientStrength * lightColor;

    vec3 norm = normalize(Normal);
    vec3 lightDir = normalize(lightPos - FragPos);
    float diff = max(dot(norm,lightDir), 0.0);
    vec3 diffuse = diff * lightColor;

    vec3 result = (ambient + diffuse) * objectColor;
    FragColor = vec4(result, 1.0);
}


texts: Rotation of objects from different axes in Flash AS3

texts:
In my game, I have made 4 lines with different colors to form a square but the colored lines are different objects. I want to rotate the lines in a way that the lines will still form a square. Eg:

But I'm only able to rotate them on the central axis, so, it forms a cross:

The code for leftPressed is:

if(leftPressed)
{
black.rotation -= 90;
blue.rotation -= 90;
yellow.rotation -= 90;
red.rotation -= 90;
}

So, I need to know how to rotate objects on different axes.


texts:
I am currently discovering the world of isometrics, now I found out there are two approaches to creating the tilemap;

Just create 2:1 ratio tile-images and draw those.
Creating squares and transforming them to the 2:1 ratio. What is the general approach on developing an isometric game?

Now I was wondering a few things;

How do more known games like AOE1/2 do this?
What are the pros/cons of both methods?
Which method is preferred to be used in this day and age?

Edit added more general question