texts: VBO and gl*Pointer management practises?

texts:
I'm aware it's not a simple yes/no question and for the moment I can't tell if it can be simply answered, or is it a topic for a long discussion which is not suitable for our Q&A format.

I want to do some VBO management in order to reduce calls to GL.

I have 4 VBOs for all meshes:

one for static draws
one for dynamic draws
one for stream draws
one for indices

I want these four to handle my whole scene - this is going to reduce calls to glBindBuffer.

My mesh object consists respectively of static part, dynamic part and stream part, each of the part is specified by vertex specificator that is created at runtime, just by pushing back attribute objects containing size/type/offset to a member vector.

Based on the vertex specificators you can fill the parts with interleaved data, you don't have to do this for all the parts though. As I read here, separating vertex parts with different usage modes is good as it allows you to update all the dynamic/stream data at once without ever touching the static data. For example, doing particle simulation I may not be necessarily interested in streaming texture coordinates - changing vertex positions may be enough.

What's going to happen next:

sort all mesh objects by the vertex specificator of its static part
upload all the meshes' static parts' vertex data in obtained order to the static VBO
sort all mesh objects by the vertex specificator of its dynamic part
upload all the meshes' dynamic parts' vertex data in obtained order to the dynamic VBO

... and so on.

In short, static/dynamic/stream chunks (each in one of the 3 VBO's to which it belongs) with the same vertex types will be next to each other, and this is going to reduce calls to glVertexAttribPointer. Here I will need to smartly organize meshes that may want to use various parts, and then implement kind of lazy binds, probably if mesh needs to call glPointer for two different VBOs (separate static and stream parts for example), check if one of them is not already bound and call corresponding glPointer first.

Of course, each of the big batch obtained that way will then be sorted inside on the level of draw calls to reduce switches of shaders, textures and so on.

In short, this is my idea:

Although such a case may be uncommon, it's just to illustrate what should my mesh organizer be able to deal with.

Well, now it's only a plan and I haven't yet implemented it but..

How do the modern, high performance engines do their VBO and gl*Pointer state management? Is there something wrong with my concept, or am I totally misguided? Google results for VBO management and similiar tend to give me topics where people are asking for help because their programs crash, or just usage examples that tell nothing about optimizing my rendering procedures on VBO level but just "avoid redundant calls to GL", or some actual one-line tips (like glBufferData with NULL). So what I've described above is what I've concluded myself using those informations and I'm not sure if I am even on the right path.

Could somebody show me some good and actually proven practises managing VBOs in big 3D scenes, or maybe guide me a bit if I am actually reasoning right ?


texts:
How can I limit the position of a rigidbody, between two values if I use this code:

public Vector3 dir;

Rigidbody rb;

void Awake()
{
    rb = GetComponent<Rigidbody>();
}

void FixedUpdate()
{
    rb.velocity = new Vector3(0f, 0f, 6f);

    rb.AddForce(dir * 1f, ForceMode.VelocityChange);
}

If I use Vector3.Clamp then the object will shake


texts: How do I implement unit selection in this program?

texts:
I'm trying to implement unit selection on a large, scrollable surface.

# Arbitrary values for window size
self.w, self.h = 1600, 900

# Game world surface, everything gets blitted to this, which is then drawn to the screen:
self.mapSurf = pygame.Surface((3600, 3600))

The general process looks like this:

# draw the floor first
    for e in self.map_layout.fixed_list:
        if e.type == 1:
            self.mapSurf.blit(self.map_sprite_list['floor_red'], e.rect)
# then draw the walls
    for e in self.map_layout.fixed_list:
        if e.type == 2:
            self.mapSurf.blit(self.map_sprite_list['wall'], e.rect)
# add agents (units) to the mapSurf
    for a in self.agent_list:
        self.mapSurf.blit(self.map_sprite_list['proto_unit'], a.pos)
# draw everything to screen
    self.screen.blit(self.mapSurf, self.mapSurfRect)

I have a method for getting the coordinates of a click on the screen. And tried to use this to select units.

def mouseUp(self, button, pos):

# select agent
    if button==1:
        for a in self.agent_list:
            if a.pos.get_distance(vec2d(pos)) < 24:
                self.selected.append(a)

The problem is that the value pos does not correspond to the mapSurf, but rather to the self.screen surface, so when comparing a.pos to the pygame event.pos returned from mouseUp, this function can only return coordinates within the window size, and I can't select agents which are spawned outside of the top left area of mapSurf.

What would be the general method of selecting units I need to implement to fix this program?

For some more details, here are three relevant links, all of which describe different aspects of how my program was built:

Trying to make a python map editor

Collision detection performance problem

Pygame performance issue for many images


texts:
I'm making a 2D platformer, shooter type game in LibGDX, and I'm wondering about Box2D's mass system. I'ven't used mass for anything in the game so far, and everything has worked ok. We move the player, enemies, and bullets around by
body.applyLinierImpulse(new Vector2(impulseX, impulseY), body.getWorldCenter)
and even have a variable jump height system, and it all works fine. To change the speed or impact of objects, we just change the impulse. I've tried using aplyForce() but it won't move the body. Everything is usually just a simple polygon, but when I'm creating fixtures there's an option to set the density, and bodies have the option to set the massData, but I don't know what either of these properties does. The gravity of the world is around 11. Can anyone tell me how I should be handling mass with my objects in the game? Thanks.


texts:
While looking up OpenTK, I found a couple of references to threads that talk about Windows 8 support:

This one from 2011 claims that OpenTK works on a Win8 preview
A newer one from 2012 leaves the question open, and mentions crashes on VMs.

Is there a definitive answer to this?


texts: Synchronizing object states over .NET sockets

texts:
What I want to achieve is synchronize the state of a list of objects between two applications using sockets. All my attempts, but failed.

One of my methods was to send each object each update to the client, which is clearly a bandwidth problem and I'm very limited to the amount of objects I can send since I send all the objects in one UDP packet.

It's clear to me that I need to send all the game objects to the client and then only update the fields as they change on the server side. The reason why I didn't try this approach from the beginning is because I identified a few barriers. My objects gets serialized and would like to synchronize every property.

How do I detect the change of a property without implementing a change event externally and for all the objects that inherited my main entity class.
Alot of the object's properties gets changed every frame so when I apply the changes to the clients representative object it requires alot of processing since I need to find each property which I need to change from the object and assign it the new value.
Each object has components which also needs synchronization. These components are within a list contained in each game object. So I must not only simple synchronize the object's properties, but the properties of each component as well.
A property can change multiple times each frame and I only want to synchronize the last value the property was set to at the end of the frame.

I currently I have no clue on how I can implement this method. My first method works, but it's not the optimal approach according to my understanding. Please any small hint or opinion can contribute to the formulation of the answer.

Thanks in advance.


texts: moving object while being snapped to another one lwjgl

texts:
hi now I want to move an object(cube) while being snapped to the surface of  another one (sphere) with the same surface of the cube how can i achieve this in lwjgl
here is a diagram. to describe my point
thanks in advance ☺


texts: How to pass one float as four unsigned chars to shader by glVertexPointAttrib?

texts:
For each vertex I use two floats as position and four unsigned bytes as color.
I want to store all of them in one table, so I tried casting those four unsigned bytes to one float, but I am unable to do that correctly...

All in all, my tests came to one point:

    GLfloat vertices[] = { 1.0f, 0.5f, 0, 1.0f, 0, 0 };
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 2 * sizeof(float),
        vertices);

// VER1 - draws red triangle
//  unsigned char colors[] = { 0xff, 0, 0, 0xff, 0xff, 0, 0, 0xff, 0xff, 0, 0,
//          0xff };
//  glEnableVertexAttribArray(1);
//  glVertexAttribPointer(1, 4, GL_UNSIGNED_BYTE, GL_TRUE, 4 * sizeof(GLubyte),
//          colors);

// VER2 - draws greenish triangle (not "pure" green)
//  float f = 255 << 24 | 255; //Hex:0xff0000ff
//  float colors2[] = { f, f, f };
//  glEnableVertexAttribArray(1);
//  glVertexAttribPointer(1, 4, GL_UNSIGNED_BYTE, GL_TRUE, 4 * sizeof(GLubyte),
//          colors2);

// VER3 - draws red triangle
int i = 255 << 24 | 255; //Hex:0xff0000ff
int colors3[] = { i, i, i };
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 4, GL_UNSIGNED_BYTE, GL_TRUE, 4 * sizeof(GLubyte),
        colors3);

glDrawArrays(GL_TRIANGLES, 0, 3);

Above code is used to draw one simple red triangle. My question is - why do versions 1 and 3 work correctly, while version 2 draws some greenish triangle?
Hex values are one I read by marking variable during debug. They are equal for version 2 and 3 - so what causes the difference?

Edit:
Question is already answered, I just want to add some more information, to clarify my motives for eventual future readers.

I am aware, that when copied to graphics memory, all values will be eventually stored as floats (even 4 unsigned bytes).
"Packing" 4 colors into one float is used by me just to decrease memory usage by color values in my VertexBufferObject class, where all vertex values are stored in one float array. Thanks to this approach, color information for each vertex (RGBA) is stored into single float value, instead of four. Memory usage is significantly lower, at small cost of one additional reinterpret_cast at color creation/change


texts: Problems with recursive backtracking algorithm for a 3D maze

texts: The algorithm really shines when craving process get's stuck (only visited nodes around), then it backtracks and creates alternative routes for the maze. That's kind of the point of a maze, that there are different paths and you can take wrong or right one. When I add extra dimensions (3rd one) to the algorithm to create a 3D maze, it almost never gets stuck because there are so much directions now to go and for most it's just one way path. I wonder if there is some trick to fix this or maybe I need different algorithm?


texts: Show view over existing view in same activity

texts:
I am newbie Android developer, and I am starting out with a simple Sudoku game. The problem I am facing right now is that I have my game showing on a dedicated Activity, which is displaying a custom View class. I have the code within the onDraw function. Now I want to show a custom keypad view, which is a separate class extending View, whenever a user clicks on a block in the Sudoku grid.

I am extremely confused as to how I should go about doing this. I am reluctant to create a dedicated activity for just this keypad, and want to show this keypad over the Sudoku grid view that the activity is currently displaying.

The activity is using setContentView(myCustomGridViewClass) to show the grid. Now I want something to the equivalent of

onTouch -> setContentView(myCustomKeypadView), though this should appear over the previous view.

I have tried reading about the LayoutInflater, but did not understand how to use it to show the keypad within this same activity. This is probably a very noob question, but any help, including any other questions, or sources I could refer to for an answer would be highly appreciated.

Regards,


texts:
I need to record my wp7 game gameplay like on Hot Apps from channel 9 http://channel9.msdn.com/Shows/Hot-Apps/Hot-Apps-Minesweeper-Cheezia-Interior-Design-Talking-Alien-Zombie-Squish.

My current game is written on Silverlight, but I will have XNA games latter as well, so I need some solution which will work for both technologies. If there any free software? If yes is there any way to record video from real device, not emulator?


texts: DirectX 11 Sprite Alpha (Invalid? + Bad Quality)

texts:
I have a bug with a texture font.
This is the texture file in photoshop:

This is the result I am getting:

The alpha from 0 and 1 shows weird artifacts as the final result, alongside the low quality of the image itself.
How can i fix this?
blendStateDescription.RenderTarget[0].BlendEnable = TRUE;
blendStateDescription.RenderTarget[0].RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL;
blendStateDescription.RenderTarget[0].SrcBlend = D3D11_BLEND_SRC_ALPHA;

blendStateDescription.RenderTarget[0].DestBlend = D3D11_BLEND_INV_SRC_ALPHA;
blendStateDescription.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_INV_DEST_ALPHA;
blendStateDescription.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_ONE;
blendStateDescription.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD;
blendStateDescription.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD;

float4 FontPixelShader(PixelInputType input) : SV_TARGET
{
   float4 color;

   // Sample the texture pixel at this location.
   color = shaderTexture.Sample(SampleType, input.tex);

   // If the color is black on the texture then treat this pixel as transparent.
   if(color.r == 0.0f)
   {
       color.a = 0.0f;
   }

   // If the color is other than black on the texture then this is a pixel in the font so draw it using the font pixel color.
   else
   {
       color.rgb = pixelColor.rgb;
       color.a = pixelColor.a;
   }

   return color;
}

// Create a texture sampler state description.
samplerDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR;
samplerDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP;
samplerDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP;
samplerDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP;
samplerDesc.MipLODBias = 0.0f;
samplerDesc.MaxAnisotropy = 1;
samplerDesc.ComparisonFunc = D3D11_COMPARISON_ALWAYS;
samplerDesc.BorderColor[0] = 0;
samplerDesc.BorderColor[1] = 0;
samplerDesc.BorderColor[2] = 0;
samplerDesc.BorderColor[3] = 0;
samplerDesc.MinLOD = 0;
samplerDesc.MaxLOD = D3D11_FLOAT32_MAX;


texts:
I'm making a game which is playable with VR and without VR. The SteamVR plugin is inside my project folders, but no CameraRig or other SteamVR object is inside my scene.
When I start the game, SteamVR starts.
How can I only activate SteamVR when I need it? (When it is checked in the settings).


texts: I´ve got a question regarding TileMaps. Each level in my game is going to be determined by the length of the tile map. I would like to create a map that will be about 5 mins (in length) long. I want to add depth to my map so I will be making individual layers to create that depth illusion via ParallaxNode. Each independent layer is going to be scrolling automatically at different speeds however the ground layer is going to be scrolling the fastest thus increasing its length being a map that long and the ground layer being longer. Will that bring performance in my game to it's knees?


texts: Calculating the inverse mesh of a 2D mesh inside a bounding box

texts:
If I have a mesh (drawn in red below)

How can I calculate the inverse of the mesh (drawn in red below), given that the mesh is always constrained by the same four vertices of the encompassing bounding box?

My mesh is drawn using a series of clockwise wound triangles.

Is there possibly any easy way to do this in a shader?

I wish to draw the triangles, and therefore each pixel, of the inverse mesh rather than draw the original mesh with color of the mesh and the background swapped to give an inverse effect.


texts: MonoGame renders texture in an almost compressed looking way

texts:
I was working on a game in MonoGame, which I have been doing for quite some time now. As I was implementing UI, I was noticing some sort of weird scanlines. Investigating further, to my surprise my whole scene was covered in it!

Notice how the texture when zoomed in has almost a JPEG squared compressed feel too it. I have no idea what is causing this.

We were using a RenderTargetTexture instead of the backbuffer, so figured I try it without, but the same happens. I checked if we were doing any weird Matrix transformations, we did not, in fact, I disabled them just to test it out. After that I thought "half pixel offset" (even though it should not really apply anymore post DX9), but also that did not solve a thing. Last but not least I thought maybe a MipMapping issue, but that would be weird since the exact same thing happens with the normal backbuffer.

My Question: Does anyone here recognize this "effect", and have any clue what might be causing it?

I'm basically just rendering a 1920x1080 image to a 1920x1080 backbuffer, but I can assure its not the image. When I for example draw a cursor and make it follow the mouse, the points where pixels "go missing", even the cursor texture deforms.

Might not be as clear in this picture, but notice how both the cursor and the orange curve basically "skip" a row of pixels, when I move the cursor to another location, it turns back to normal.


texts:
I have an idea for a space-based game where there are different sectors of control. These would be set up in a manner similar to terrain biomes, where there will be clusters with limited space between them where there are 'mixed' biomes or even no biomes whatsoever, indicating no 'side' has control over that region.

There are a plethora of articles on the web these days about how to create two dimensional biome maps, but I have seen none about making three-dimensional maps. Has anyone done any coding like this before? My Google-fu is strong but I haven't found any significant pages on it.

I will continue to work on it solo, but as a beginning, solo programmer I expect I will be quite slow on it. I was just wondering if anyone had done this already.


texts: Compressing textures and recompressing textures

texts:
Which tools are considered best-quality for compressing textures for use in OpenGL?  Which can be used from the Linux commandline?

And which lossless compressors give good ratio/speed on compressed textures?

(I see that Skyrim's BSA archives are typically only half the size of the DDSes they contain)


texts:
I am trying to build a game and i want people to be able to select stuff with a pointer but i don't want it to be just an ugly looking default pointer so i wrote this code to try and get a image as it

first i loaded the image

game.load.image('selector', 'assets/img/pointer.png')

then I put it into my game

selector = game.add.sprite(game.world.centerX, game.world.centerY, 'selector')

and then in my render() function i do this

selector.x = game.input.x;
selector.y = game.input.y;

it moves fine with my mouse but with one problem

my game is designed so that i have to use a camera that follows my character because the map is bigger than the view

so since for some reason my sprite always starts at 0,0 it can only move 800x600px since thats all that the canvas sees the mouse in so i need a way to fix this but i'm not sure how to do this because i am new to phaser


texts: How to encapsulate game objects (entities) in Box2d

texts:
I am currently learning Box2d, a 2D physics engine within libgdx. But Box2d seems to be in every game framework these days so I am not really talking about libgdx.

I understand Box2d comes with lots of new concepts such as shape, bodydef, body, fixture, sprite, joint. But I think I can slowly but surely manage to learn about them.

My question, however, is how to organize them into a game object for better maintenance of code. Naturally, I am thinking about following fields in the game object class.

GameArea gameArea
Body body
BodyDef bodyDef;
FixtureDef fixtureDef
Shape shape;
Sprite sprite;

As for its methods, it has constructor, update, and display. But I am talking without experience. For example, I don't know how I can organize joints - maybe in GameArea. Any thought from experienced would be appreciated.


texts: Want some limits in Bullet firing and its stop when i press the shoot button

texts:
I want some limits or range when my player fire the bullets and when i press the shoot button my fire as been stopped. I use the GetButtonDown from this its fire continuously but its not stopped. and if i use Input.GetButton than its hold the button and fire continuously but in fire there is no gap. So, my problem is that how i stop the bullet fire when i press the shoot button and if choose this (INPUT.GETBUTTON) and its hold the shoot button and its fire continuously than i  want some gap on that fire and some limits or range of fire.

void Update(){
        if(Input.GetButtonDown("Fire1"))
        {
            shootRoutine = StartCoroutine(PlayerShoot());

        }else if(Input.GetButtonUp("JumpButton"))
        {
            StopCoroutine(shootRoutine);
            shootRoutine = null;

        }
    }

    void JumpButton(){
        if(!transform.GetChild(0).gameObject.GetComponent<PlayerHealth>
            ().hasDied){
            if (grounded){
                grounded = false;
                myRigidBody.AddForce (new Vector2 (0,
                    jumpPower), ForceMode2D.Impulse);
                if(myRigidBody.velocity.y > jumpPower){
                    myRigidBody.velocity = new Vector2 (0,
                        jumpPower);
                }
                animator.SetBool ("isGrounded", grounded);
            }
        }
    }

PlayerShoot method

IEnumerator PlayerShoot()
    {
        while(true)
        {
            if (!transform.GetChild
                (0).gameObject.GetComponent<PlayerHealth>().hasDied)
            {
                if (energy >= 5f)
                {
                    //energy -= 5f;
                    energyLevel.value = (int)
                        energy;
                    energyText.text = (int)energy
                        + "%";

                    GameObject newProjectile =
                        Instantiate(projectile, new Vector3(transform.position.x + 1.5f, transform.position.y - 0.02f,
                            transform.position.z), Quaternion.identity) as GameObject;
                    if
                        (GameController.instance.isMusicOn)
                    {

                        AudioSource.PlayClipAtPoint(MusicController.instance.audioClips[2],
                            newProjectile.transform.position);
                    }
                }
            }

            yield return new WaitForSeconds(shootDelay);
            //Wait for 'shootDelay' seconds before starting over again.
        }
    }


texts:
I have a 2D Mesh object generated at runtime painted all with uniform color.
I want that mesh to have its color fade to transparent color close to the edges.

Despite I searched everywhere I could not find any solution. Unfortunately I'm not into Shader programming enough to build logically my solution.

EDIT:According to @wondra's reply my mesh is not fan shaped. It has a non regular hole in it.

How can I achieve this?


texts: Object outlining, stencil is not working WebGL

texts:
I can't seem to figure out my problem with stencil buffer in object outlining algo.

function init() {
   ...
   gl.enable(gl.STENCIL_TEST);
   gl.stencilOp(gl.KEEP, gl.KEEP, gl.REPLACE);
   ...
}

var mscaled = [];     // scaled model matrix of a cube
function render() {
   gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT | gl.STENCIL_BUFFER_BIT);

    gl.stencilFunc(gl.ALWAYS, 1, 0xFF);
    gl.stencilMask(0xFF);
     // use program1
     // set attrib pointers
     // bind cube's ebo buffer
     gl.drawElements(gl.TRIANGLES, 36, gl.UNSIGNED_SHORT, 0);

     gl.stencilFunc(gl.NOTEQUAL, 1, 0xFF);
     gl.stencilMask(0x00);

      // set scaled model matrix
      mat4.fromRotationTranslationScale(mscaled, cube.rotation, cube.translation, vec3.fromValues(1.1, 1.1, 1.1));

      // use program2
      // set attrib pointers
      // bind cube's ebo buffer
      gl.drawElements(gl.TRIANGLES, 36, gl.UNSIGNED_SHORT, 0);
}

And it just draws the whole second cube on top of the first, like there's no stencil test. I've tested with up-scale and down-scale.

the red cube should be the outliner. In the first image it is scaled up - but WebGL draws it just on top of the first one, in the second image it is scaled down - ideally it shouldn't been even drawn due to stencil test (of course, depth test is disabled in the case of a second image)


texts:
I have a shader as an 'ID3D11VertexShader' (or generally any 'ID3D11*Shader') instance. For my application I would like to read the shader byte code that is associated with this instance.

The goal is the create an D3D11InputLayout without having to carry around the byte code blob.

Is there a way in DirectX 11 to retrieve the byte code, that was used to create this shader? I was looking for something similar to glGetProgramBinary (that would return the byte code instead of the binary code).


texts: "Update cannot be an iterator block" when trying to wait for jump to finish

texts:
As of now, I'm getting a C# error (CS1624) stating that:

The body of PlayerMovement.Update() cannot be an iterator block because void is not an iterator interface type.

The error is within the void Update section. I believe it started when I added lines 34 - 37, the second "if" clause.
Here's the code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerMovement : MonoBehaviour
{

    Animator m_Animator;
    bool m_Jump;

    public CharacterController2D controller;

    public float runSpeed = 40f;

    float horizontalMove = 0f;
    bool jump = false;

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

    // Update is called once per frame
    void Update()
    {
        horizontalMove = Input.GetAxisRaw("Horizontal") * runSpeed;

        if (Input.GetButtonDown("Jump"))
        {
            jump = true;
            m_Animator.SetBool("Jump", true);
        }

        // These are lines 34-37 that cause the error, I think.
        if (m_Animator.GetBool("Jump") == true)
        {
            yield return new WaitForSeconds(3);
            m_Animator.SetBool("Jump", false);
        }
    }

    void FixedUpdate()
    {
        controller.Move(horizontalMove * Time.fixedDeltaTime, false, jump);
        jump = false;
    }
}


texts: Solitaire Game: Transferring Cards Design in C++

texts: So, I'm working on a Solitaire game. I already created a the classes: Card, Pile, Stock. Each work as expected on it's own. My question is: What possible design for managing moving card(s) between the 7 piles, the stock (the waste) and the foundations? I want a possible design that is suitable for managing these game objects so they can work together smoothly. Any help is greatly appreciated.


texts: How do I calculate the path of something in orbit around one or more bodies?

texts:
I need to figure out how to calculate the orbit of an object around one or more bodies for a game that I am making (built on Cocos2D-Swift). The game is in two dimensions, so it's a two-dimensional orbit I am calculating. I currently have it set up so that, in the update loop, it calculates the force of each of the bodies on the object, the acceleration due to that force, and the change in velocity due to that acceleration. This would probably work fine if I were going through the update loop a thousand times per second, but on the iPhone 6+ simulator, I'm going through it approximately thirty times per second, which is a discretization so wide that it makes the orbit of the object very unstable.

As a result, I am looking for an equation that tells me the position of the orbiting object as a function of time; therefore, the force, acceleration, and velocity are not discretized, so the simulation is accurate. An example of what I am looking for is how Kerbal Space Program calculates the orbital paths ahead of time. Any thoughts? Thanks.


texts:
I'm applying phong shading onto a single giant triangle, and I'd like the light's coordinates to coincide with the camera's coordinates in 3D space. In order to do this, whenever I update the camera's coordinates, I also update the light's coordinates. However, diffuse and specular lighting don't "focus" exactly at the camera position when I bring the camera close to the triangle, instead they do it a few units too far. The triangle is .5 units below the XZ plane and parallel to it. Here is a picture demonstrating this effect.

Also, here are my HLSL shaders; this is where all the transformations happen.

// Vertex Shader ////////////////////////////////////////

 float4x4    Matrix; // ViewProjection Matrix
 float4x4    Matrix2; // View matrix
 float4x4    Matrix3; // View matrix with translation zeroed out

 float4    lightPos;

struct VS_INPUT
{
    float4  Pos     : POSITION;
    float4  Normal  : NORMAL;
    float2  Tex0    : TEXCOORD0;
};

struct VS_OUTPUT
{
    float4  Pos     : POSITION;
    float4  Normal  : TEXCOORD1;
    float4  LightDir     : TEXCOORD2;
    float2  Tex0    : TEXCOORD0;
};

////////////////////////////////////////

VS_OUTPUT VShade(VS_INPUT In)
{
    VS_OUTPUT Out = (VS_OUTPUT) 0;

    Out.Tex0      = In.Tex0;

    //world space -> clip space transformation
    Out.Pos       = mul(In.Pos, Matrix);

    // world space -> camera space transformations
    Out.Normal    = normalize(mul(In.Normal, Matrix3));
    Out.LightDir  = normalize(mul(lightPos - In.Pos, Matrix3));

    return Out;
}

// Pixel Shader ////////////////////////////////////////

sampler   baseTex;

struct PS_INPUT
{
    float4  LightDir     : TEXCOORD2;
    float4  Normal  : TEXCOORD1;
    float2  Tex0    : TEXCOORD0;
};

struct PS_OUTPUT
{
    float4  Color   : COLOR;
};

////////////////////////////////////////

PS_OUTPUT PShade(PS_INPUT In)
{
    PS_OUTPUT Out = (PS_OUTPUT) 0;

    float4 Normal = normalize(In.Normal);
    float4 LightDir = normalize(In.LightDir);

    float di = saturate(dot(Normal, LightDir));

    float4 ambient = {0.1, 0.1, 0.1, 1};

    float4 Reflect = normalize(2 * di * Normal - LightDir);
    float specular = pow(saturate(dot(Reflect, LightDir)), 2);

    Out.Color = ambient + tex2D(baseTex,In.Tex0) * di + specular;
    return Out;
}

EDIT

In.LightDir is computed for each pixel. It is first computed for each vertex in the vertex shader Out.LightDir  = normalize(mul(lightPos - In.Pos, Matrix3));, then it is interpolated across the whole triangle. lightPos is just the camera's position (which coincides with the light):

if(handle = m_pVertexConstants->GetConstantByName(NULL,"lightPos"))
        m_pVertexConstants->SetVector(pDevice,handle,(D3DXVECTOR4*)m_camera.GetPosition());

Also, the world transformation matrix is just the identity, so I have not included it anywhere.


texts: How to build multiplayer games for android?

texts:
I'd like to know how to build android multiplayer games but I'm struggling to find a step-by-step or good resources on this topic. My main questions is which engine and api to use? I'd like to achieve this with the technologies I already know such as Firebase and Libgdx on android studio.

All my researches point to things like Unity, Godot and unreal. Is this the only/better way to go since I want to build simple games such as pool ?

What I want to build is a multiplayer game on where the users should be able to invite friend from their social media to play against, provide rankings and sharing results on social media. ONLY for Android, using Java and free resources (APIs, db's, engines).

A good example would be Trivia Crack how is this game (probably) made? which technologies?


texts: Are there any good ways to know if a resource is patented trademark or illegal to use?

texts:
This is something that I worried about for a long time. While making games, it is hard to tell for sure if any of the resources are copyrighted unless a person is clearly aware that they are to a like to an image that have known in certain work done. I wanted to make a 2D MMO, that in certain ways might be similar to "Pokémon". I did not want to make an illegal game, but it is just that there are certain elements that I want in the game which are similar to those in "Pokémon". I also wanted to possibly sell the features of it, if the project succeeds and works out all well. What exactly are some ways that I can find out for sure if images that I am using are illegal to use or not.

The element which I am worried about in the game which I was planning to make was about creature battling and summoning. Thankfully, game concepts cannot be copyrighted, but I did not want to take or use images that were exactly like those in "Pokémon", and I wanted to make a game that is very different in many ways. I might have wanted to use creatures in a similar cartoon fashion that is used in "Pokémon". This has been somewhat of a concern, to me, though as about the legal issues possibly.


texts: How can I attract & repel the mouse cursor from particular UI controls?

texts:
This question came from some of my students. I wanted to share it here so others can find & improve on the solutions we've found so far.

In particular, my answer below doesn't behave as well as I'd like in windowed / editor mode - UI buttons no longer respond to hovering the cursor. I welcome alternative answers that solve this more completely.

We're making a visual novel game using the Fungus asset for Unity.

We want to add a twist where some dialogue options are easier or harder to press, because they attract or repulse your mouse cursor.

Unfortunately, we haven't been able to identify a cross-platform way to manipulate the mouse's position, nor a way to create a "Fake" mouse cursor image that can still interact with Fungus's UI buttons.

How can we pull this off?


texts: How to compute highscores, so that 10 matches will "correctly" compete 100 matches

texts:
When computing highscores, it is possible to:

count sum of points (in every match),
count average of points (across all matches).

Sum is vulnerable to: multiple low-quality matches.

Average is vulnerable to: creating new account and playing few high-quality matches.

How to face this problem? Multiply sum x average? How is this done in practice, e.g. in World of tanks?


texts: Box2d collision on isometric maps built in Tiled

texts:
I am trying to add Box2d collision to a map I created in Tiled http://www.mapeditor.org/

It all worked when I was creating standard othergraphic maps but now I have changed to isometric the objects layer (Where I am creating the bodies for box2d) no longer match the rendering from the IsometricTiledMapRenderer.

I created the collision using the MapBodyBuilder class (written by someone else much smarter) Code below:

public class MapBodyBuilder {

// The pixels per tile. If your tiles are 16x16, this is set to 16f
private static float ppt = 0;
public static Array<Body> bodies;

public static Array<Body> buildShapes(Map map, float pixels, World world) {
    ppt = pixels;

    MapObjects objects = map.getLayers().get("Obstacles").getObjects();

    bodies = new Array<Body>();

    for(MapObject object : objects) {

        if (object instanceof TextureMapObject) {
            continue;
        }

        Shape shape;

        if (object instanceof RectangleMapObject) {
            shape = getRectangle((RectangleMapObject)object);
        }
        else if (object instanceof PolygonMapObject) {
            shape = getPolygon((PolygonMapObject)object);
        }
        else if (object instanceof PolylineMapObject) {
            shape = getPolyline((PolylineMapObject)object);
        }
        else if (object instanceof CircleMapObject) {
            shape = getCircle((CircleMapObject)object);
        }
        else {
            continue;
        }

        BodyDef bd = new BodyDef();
        bd.type = BodyDef.BodyType.StaticBody;
        Body body = world.createBody(bd);
        body.createFixture(shape, 1);

        bodies.add(body);

        shape.dispose();
    }
    return bodies;
}

private static PolygonShape getRectangle(RectangleMapObject rectangleObject) {
    Rectangle rectangle = rectangleObject.getRectangle();
    PolygonShape polygon = new PolygonShape();
    Vector2 size = new Vector2((rectangle.x + rectangle.width * 0.5f) / ppt,
            (rectangle.y + rectangle.height * 0.5f ) / ppt);
    polygon.setAsBox(rectangle.width * 0.5f / ppt,
            rectangle.height * 0.5f / ppt,
            size,
            0.0f);
    return polygon;
}

private static CircleShape getCircle(CircleMapObject circleObject) {
    Circle circle = circleObject.getCircle();
    CircleShape circleShape = new CircleShape();
    circleShape.setRadius(circle.radius / ppt);
    circleShape.setPosition(new Vector2(circle.x / ppt, circle.y / ppt));
    return circleShape;
}

private static PolygonShape getPolygon(PolygonMapObject polygonObject) {
    PolygonShape polygon = new PolygonShape();
    float[] vertices = polygonObject.getPolygon().getTransformedVertices();

    float[] worldVertices = new float[vertices.length];

    for (int i = 0; i < vertices.length; ++i) {
        System.out.println(vertices[i]);
        worldVertices[i] = vertices[i] / ppt;
    }

    polygon.set(worldVertices);
    return polygon;
}

private static ChainShape getPolyline(PolylineMapObject polylineObject) {
    float[] vertices = polylineObject.getPolyline().getTransformedVertices();
    Vector2[] worldVertices = new Vector2[vertices.length / 2];

    for (int i = 0; i < vertices.length / 2; ++i) {
        worldVertices[i] = new Vector2();
        worldVertices[i].x = vertices[i * 2] / ppt;
        worldVertices[i].y = vertices[i * 2 + 1] / ppt;
    }

    ChainShape chain = new ChainShape();
    chain.createChain(worldVertices);
    return chain;
}

}

Any help would be greatly appreciated.

Thanks

pps I know this has been asked before generate box2d bodies from isometric tiled map

But I cannot find an answer.


texts: Object is not rotating from right direction

texts:
im beginner to unity so im using this code to rotate object with mouse with max rotation of 35 degrees,it is working but it's only possible to rotate object if mouse is under of that object. here is my code:

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

public class rotObj : MonoBehaviour {
    //private float baseAngle = 0.0f;
    private float maxRotaion = 35f;
    void Update () {
        var dir = Camera.main.ScreenToWorldPoint (Input.mousePosition) - transform.position;
        var angle = Mathf.Atan2 (dir.y, dir.x) * Mathf.Rad2Deg;
        if (angle >= -maxRotaion && angle <= maxRotaion)
            transform.localRotation = Quaternion.AngleAxis (angle, Vector3.forward);
    }
}

as i think, localrotation is making that problem? how can i fix this without removing maximum rotation angle and will be able to rotate object not just from mouse under object, but from any position? my english grammar is very bad but i hope you will understand


texts: Interactive texture modification (such as swirling) in Unity

texts:
I am working on a game where I want to allow users to mix multiple colors (similar to shown in this video): https://youtu.be/11UFYyv8hjs?t=316.
I have the following questions:

I am expecting that this is done using shaders. What kind of shader I have to use for such implementation? What will be the logic to create this type of shader?
Are there any other ways using which this feature can be implemented?
Are there any open source tutorials or examples?

I would appreciate any suggestions and thoughts on this topic. Thank you.


texts: Collision works except for when coming from right side

texts:
I am trying to make a bomberman clone. I'm having problems with the collision on the walls that is not on the sides of the map (see image). When I come from the right (going left), the red square (player) goes through the wall but when I come from other sides (up, left, down) the collision works well and the player does not go through. The collision on the side walls works well also even when I come from the right and going left.

I am using Tiled and LibGDX and here is the code:

private void checkCollision(float delta) {
    //player.getVelocity().scl(delta);
    Vector2 position = player.getPosition();

    // just to see if it overlaps because this is the location of the
    // rectangle when getTiles is called when player moves left as shown in the image
    Rectangle rect = new Rectangle(128, 128, 64, 64);
    if(player.getRectangle().overlaps(rect)) {
        System.err.println("overlap");
    }

    if(player.isMovingRight()) {
        Array<Rectangle> tiles = getTiles((int)(position.x/TILE_SIZE + 1), (int)(position.y/TILE_SIZE - 1),
                (int)(position.x/TILE_SIZE + 1), (int)(position.y/TILE_SIZE + 1));
        for (Rectangle tile : tiles) {

            if(player.getRectangle().overlaps(tile)) {
                System.out.println("overlap right");
                player.setPosition(tile.x - player.getWidth() , player.getPosition().y);
            }
        }
    }
    if(player.isMovingLeft()) {
        Array<Rectangle> tiles = getTiles((int)(position.x/TILE_SIZE - 1), (int)(position.y/TILE_SIZE - 1),
                (int)(position.x/TILE_SIZE - 1),  (int)(position.y/TILE_SIZE + 1));
        for (Rectangle tile : tiles) {

            if(player.getRectangle().overlaps(tile)) {
                System.out.println("overlap left"); // this doesn't show
                player.setPosition(tile.x + tile.width, player.getPosition().y);
            }
        }
    }

    if(player.isMovingUp()) {
        Array<Rectangle> tiles = getTiles((int)(position.x/TILE_SIZE - 1), (int)(position.y/TILE_SIZE - 1),
                (int)(position.x/TILE_SIZE + 1), (int)(position.y/TILE_SIZE));
        for (Rectangle tile : tiles) {

            if(player.getRectangle().overlaps(tile)) {
                System.out.println("overlap up");
                player.setPosition(player.getPosition().x, tile.y + tile.height);
            }
        }
    }
    if(player.isMovingDown()) {
        Array<Rectangle> tiles = getTiles((int)(position.x/TILE_SIZE - 1), (int)(position.y/TILE_SIZE + 1),
                (int)(position.x/TILE_SIZE + 1), (int)(position.y/TILE_SIZE + 1));
        for (Rectangle tile : tiles) {

            if(player.getRectangle().overlaps(tile)) {
                System.out.println("overlap down");
                player.setPosition(player.getPosition().x, tile.y - player.getHeight());
            }
        }
    }

    //player.getVelocity().scl(1/delta);

}

private Array<Rectangle> getTiles(int startX, int startY, int endX, int endY) {
    TiledMapTileLayer layer = (TiledMapTileLayer)level.getMap().getLayers().get(1);
    Array<Rectangle> rectangles = new Array<Rectangle>();
    for (int x = startX; x <= endX; x++) {
        for (int y = startY; y <= endY; y++) {
            Cell cell = layer.getCell(x, y);
            if(cell != null) {
                Rectangle rect = new Rectangle(x*TILE_SIZE, y*TILE_SIZE, TILE_SIZE, TILE_SIZE);
                rectangles.add(rect);
            }
        }
    }
    return rectangles;
}


texts: Is there a library like ImGui with the ability to customize frames, buttons, sliders, etc. in the windows for OpenGL

texts: I'm trying to write a game on OpenGL using C++. From third-party libraries for creating windows (widgets?) Inside OpenGL, I was able to add ImGui to my project, create a window and attach some functions to it. But I did not find information like changing the style of this window. Specifically, in this situation, I need to create the starting window of the game (start the game, settings, exit, etc.) and create in-game windows (inventory, character menu, minimap, chat, etc.). I heard about Qt, but given the size they require, my program will weigh 3-4 times more than we would like. In addition, I do not need any super high-quality graphics and a large set of visualization capabilities. I would like to understand what my program consists of and have a set of basic concepts about how this is implemented. Could you advise: is there a similar library with the ability to create and edit the style of in-game windows (maybe in ImGui this function is still there?) with open source code in C++?


texts: implementing a 2d looping using a physics engine

texts:
I am implementing a 2d mobile racing game. I have already implemented a 2d terrain using a physics engine (using edges). Now i would like to implement a looping very similar to the one in the old super sonic (http://higherorderfun.com/blog/wp-content/uploads/2012/05/Sonic_2_Loop.jpg). The problem is if i use a normal edge the car hits in the edge when going up the ramp (which is completely logical).  Does any one have any experiences on how to make a looping using a 2d physics engine (without faking it)? Is it even possible (i know that is possible in 3d).

Thanks for the help!


texts: Why I don't have the DX templates even with the Windows 8 SDK installed?

texts:
I have Windows 7, 64 bit.
I installed the Windows 8.1 SDK from here, and I installed Visual Studio Ultimate 2013. I chose to install everything; the size of the install was around 11GB.
Yet I don't have any of the templates shown here. What am I doing wrong? Do I need to install some other version of Visual Studio, like Express? Do I need Windows 8.1?


texts: New Input System Differs Between Editor and Runtime?

texts:
I'm sure the problem is me.
Here is a simple look script (from a tutorial, actually).
I'm getting inconsistent results between editor and runtime. I'm guessing its a framerate thing.
Code:
using UnityEngine;
using Mirror;
using Cinemachine;

public class PlayerCameraController : NetworkBehaviour
{
    [Header("Camera")]
    [SerializeField] private Vector2 maxFollowOffset = new Vector2(-1f, 6f);
    [SerializeField] private Vector2 cameraVelocity = new Vector2(4f, 0.25f);

    [SerializeField] private Transform playerTransform = null;
    [SerializeField] private CinemachineVirtualCamera virtualCamera = null;

    private Controls controls;
    private Controls Controls {
        get {
            if (controls != null) { return controls; }
            return controls = new Controls();
        }
    }
    private CinemachineTransposer transposer;

    public override void OnStartAuthority()
    {
        transposer = virtualCamera.GetCinemachineComponent<CinemachineTransposer>();
        virtualCamera.gameObject.SetActive(true);

        Controls.Player.Look.performed += ctx => Look(ctx.ReadValue<Vector2>());

        enabled = true;
    }

    [ClientCallback]
    private void OnEnable() => Controls.Enable();

    [ClientCallback]
    private void OnDisable() => Controls.Disable();

    private void Look(Vector2 lookAxis) {
        float deltaTime = Time.deltaTime;

        float followOffset = Mathf.Clamp(
            transposer.m_FollowOffset.y - (lookAxis.y * cameraVelocity.y * deltaTime),
            maxFollowOffset.x,
            maxFollowOffset.y);

        transposer.m_FollowOffset.y = followOffset;
        playerTransform.Rotate(0f, lookAxis.x * cameraVelocity.x * deltaTime, 0f);
    }
}

The code seems right. Watching the values of Vector2 lookAxis reveals that the numbers are slightly different coming into the function based on environment.
Is there something wrong with this code that would give different results between editor and runtime?


texts: Why does my A* implementation overflow the stack?

texts:
I'm fairly new to game dev and working on my first ever attempt at 2D pathfinding. I'm using the A* algorithm as detailed here.

For the most part, it seems to be working correctly and as intended. However upon attempting to wrap my path around a building in the map, a stack overflow is caused in ClosedList (the list storing coordinates of the path). It appears that at some point in the path, the algorithm is switching back and forth between two tiles, but I cannot work out why.

The code probably isn't the best way to do things but this is my first attempt. Apologies if it offends anyone. :P

void CheckSquare(Vector2 Start, Vector2 End)
{
    //Check for Invalid Start/End Points
    if (Start == End ||
        grid.PTileArray[(int)Start.x, (int)Start.y].CurrentType.Passable == 0 ||
        grid.PTileArray[(int)End.x, (int)End.y].CurrentType.Passable == 0)
    {
        return;
    }

    //Check which adjacent tiles are passable
    if (grid.PTileArray[(int)Start.x - 1, (int)Start.y].CurrentType.Passable == 1)
    {
        OpenList.Add(new Vector2(Start.x - 1, Start.y)); //LEFT
        gValues.Add(10);
    }
    if (grid.PTileArray[(int)Start.x - 1, (int)Start.y + 1].CurrentType.Passable == 1)
    {
        OpenList.Add(new Vector2(Start.x - 1, Start.y + 1)); //TOP LEFT
        gValues.Add(14);
    }
    if (grid.PTileArray[(int)Start.x, (int)Start.y + 1].CurrentType.Passable == 1)
    {
        OpenList.Add(new Vector2(Start.x, Start.y + 1)); //TOP
        gValues.Add(10);
    }
    if (grid.PTileArray[(int)Start.x + 1, (int)Start.y + 1].CurrentType.Passable == 1)
    {
        OpenList.Add(new Vector2(Start.x + 1, Start.y + 1)); //TOP RIGHT
        gValues.Add(14);
    }
    if (grid.PTileArray[(int)Start.x + 1, (int)Start.y].CurrentType.Passable == 1)
    {
        OpenList.Add(new Vector2(Start.x + 1, Start.y)); //RIGHT
        gValues.Add(10);
    }
    if (grid.PTileArray[(int)Start.x + 1, (int)Start.y - 1].CurrentType.Passable == 1)
    {
        OpenList.Add(new Vector2(Start.x + 1, Start.y - 1)); //BOTTOM RIGHT
        gValues.Add(14);
    }
    if (grid.PTileArray[(int)Start.x, (int)Start.y - 1].CurrentType.Passable == 1)
    {
        OpenList.Add(new Vector2(Start.x, Start.y - 1)); //BOTTOM
        gValues.Add(10);
    }
    if (grid.PTileArray[(int)Start.x - 1, (int)Start.y - 1].CurrentType.Passable == 1)
    {
        OpenList.Add(new Vector2(Start.x - 1, Start.y - 1)); //BOTTOM LEFT
        gValues.Add(14);
    }

    //Remove the parent from the Possible choices
    for (int n = 0; n < OpenList.Count; n++)
    {
        if (OpenList[n] == ClosedList[ClosedList.Count - 1])
        {
            OpenList.RemoveAt(n);
        }
    }

        //Calculate H Values
        for (int n = 0; n < OpenList.Count; n++)
        {
            float x = Mathf.Abs(End.x - OpenList[n].x);
            float y = Mathf.Abs(End.y - OpenList[n].y);
            float final = 10 * (x + y);
            hValues.Add((int)final);
        }

    //Calculate F Values
    int lowest = 10000;
    int reference = 0;
    for (int n = 0; n < OpenList.Count; n++)
    {
        int g = gValues[n];
        int h = hValues[n];
        int final = g + h;
        fValues.Add(final);
        if (fValues[n] < lowest)
        {
            lowest = fValues[n];
            reference = n;
        }
    }

    //Add the square with the lowest F Value to the closed list as part of the path
    ClosedList.Add(OpenList[reference]);

    //Clear Lists
    OpenList.Clear();
    gValues.Clear();
    hValues.Clear();
    fValues.Clear();

    //If the final Location in ClosedList is not the end then continue
    if (ClosedList[ClosedList.Count - 1] != End)
        CheckSquare(ClosedList[ClosedList.Count - 1], End);
}

Help or nudges in the right direction would be greatly appreciated.


texts:
The hero has a ball, which shall be thrown with accuracy in a court on iPhone/iPad. The player is seen from above, in a 2D view. In game play, the player reach is between 1/15 and 1/6 of the height of the iPhone screen. The player will run, and try to outmaneuver his opponent, and then throw the ball at a specific location, which is guarded by the opponent (which is also shown on the screen). The player is controlled by a joystick, and that works ok, but how shall I control the stick?

Maybe someone can propose a third control method?

I've tried the following two approaches:

Joystick:

Hero has a reach of 1 meter, and this reach is marked with a semi-opaque circle around the player.
The ball can be moved by a joystick. When the joystick is moved south, the ball is moved south within the reach circle. There is a direct coupling with the joystick and the position of the ball. I.e. when the joystick is moved max south, the ball is max south within the player reach.
At each touch update the speed is calculated, and the Box2d ball position and ball speed are updated. NB, the ball will never be moved outside the reach as long as the player push the joystick.
The ball is thrown by swiping the joystick to make the ball move, and then releasing the joystick. At release, the ball will get a smoothed speed of the joystick.

Joystick Problem:

The throwing accuracy gets bad, because the joystick can not be that big, and a small movement results in quite a large movement of the ball.
If the user does not release before the end of the joystick maximum end point, the ball will stop, and when the user releases the joystick the speed of the ball will be zero. Bad...

Touch pad

A force is applied to the ball by a sweep on a touchpad.
The ball is released when the sweep is ended, or when the ball is moved outside the player reach.
As there is no one to one mapping between the swipe and the ball position, the precision can be improved. A large swipe can result in a small ball movement.

Touch Pad Problem

A touchpad is less intuitive. Users do not seem to know what to do with the touch pad. Some tap the touchpad, and then the ball just falls to the ground.
As there is no one-to-one mapping, the ball can be moved outside the reach, and then it will just fall to the ground. It's a bit hard to control the ball, especially if the player also moves.


texts: How do I organize my class structure for networking?

texts:
In my gameclient I have the following classes(compontents):
Game, GameScreen, GameWorld, Player.

They are structured like this:
Game has two GameScreens: MenuScreen and MainScreen.
MenuScreen has an instance of GameWorld.
GameWorld has an instance of Player.

Now I wanted to add a multiplayer mode to my game. For this I have a class "NetworkConnection".
For the problem keep in mind that this class needs to access individual objects in the game world, as well as vice-versa. Meaning that individual objects (as a simple example the player) need to send messages to the class.
It could look like this for example:

networkConnection.SendPlayerPositionUpdate(x, y, playerID);

The problem

Where do I put my NetworkConnection?

I thought about adding it to "Game" because it is a part of the game (duh).
But when I want the player to tell its position to the server I have to do this:

(Inside the player class)
world.screen.game.networkConnection.SendPositionUpdate(...);

The otherway around (when messages are being received from the server)

(Inside the network class)
game.currentScreen.world.player.SetHealthPoints(receivedHealth);

Where should I place NetworkConnection?
Should I make NetworkConnection a global singelton ?


texts: Jerky Character movement after adding mouse orbit script

texts:
I added a custom mouse orbit script to my project. When the right mouse button is clicked, the camera can be rotated around the player.

The issue, after this change, is my player movement has become jerky / choppy and not smooth. If I remove my mouse orbit script, player moment is back to normal i.e smooth. I can't seem to pin point what is causing this jerky movement withing MouseOrbit script

Video demo

Code

/* This is where we initialize our script */
void Start()
{
    Initialize();
}

/* This is where we set our private variables, check for null errors,
 * and anything else that needs to be called once during startup */
void Initialize()
{
    h = this.transform.eulerAngles.x;
    v = this.transform.eulerAngles.y;

    cameraTransform = this.transform;
    cam = Camera.main;
    smoothDistance = distance;
    timerot = TimeSignature((1 / rotationDampening)) * 100.0f;
    NullErrorCheck();
}

/* We check for null errors or warnings and notify the user to fix them */
void NullErrorCheck()
{
    if (!viewTarget)
    {
        Debug.LogError("Please make sure to assign a view target!");
        Debug.Break();
    }
    if (collisionLayers == 0)
    {
        Debug.LogWarning("Make sure to set the collision layers to the layers the camera should collide with!");
    }
}

/* This is where we do all our camera updates. This is where the camera
 * gets all of its functionality. From setting the position and rotation,
 * to adjusting the camera to avoid geometry clipping */
void Update()
{
    if (!viewTarget)
        return;

    if (Input.GetMouseButton(1))
        {
            Cursor.lockState = CursorLockMode.Locked;

            h += Input.GetAxis("Mouse X") * horizontalRotationSpeed * Time.deltaTime;
            v -= Input.GetAxis("Mouse Y") * verticalRotationSpeed * Time.deltaTime;

            h = ClampAngle(h, -360.0f, 360.0f);
            v = ClampAngle(v, minVerticalAngle, maxVerticalAngle);
            //              Debug.Log ("value of h: "+h);
            newRotation = Quaternion.Euler(v, h, 0.0f);
        }
        else
        {
            Cursor.lockState = CursorLockMode.None;
        }

    if (Input.GetKeyDown(KeyCode.D))
    {
        h = transform.eulerAngles.y + 90;
        newRotation = Quaternion.Euler(transform.eulerAngles.x, h, transform.eulerAngles.z);
    }

    if (Input.GetKeyDown(KeyCode.A))
    {
        h = transform.eulerAngles.y - 90;
        newRotation = Quaternion.Euler(transform.eulerAngles.x, h, transform.eulerAngles.z);
    }

    /* We set the distance by moving the mouse wheel and use a custom
     * growth function as the time value for linear interpolation */
    distance = Mathf.Clamp(distance - Input.GetAxis("Mouse ScrollWheel") * 10, minDistance, maxDistance);
    smoothDistance = Mathf.Lerp(smoothDistance, distance, TimeSignature(distanceSpeed));

    /*We give the rotation some smoothing for a nicer effect */
    smoothRotation = Quaternion.Slerp(smoothRotation, newRotation, TimeSignature((1 / rotationDampening) * 100.0f));

    newPosition = viewTarget.position;
    newPosition += smoothRotation * new Vector3(0.0f, height, -smoothDistance);

    /* Calls the function to adjust the camera position to avoid clipping */
    CheckSphere();

    smoothRotation.eulerAngles = new Vector3(smoothRotation.eulerAngles.x, smoothRotation.eulerAngles.y, 0.0f);
    Vector3 dir = new Vector3(0, 0, -distance);

    cameraTransform.position = newPosition;
    //cameraTransform.position = viewTarget.position + smoothRotation * dir;
    cameraTransform.rotation = smoothRotation;
}

Time Signature
with speed as input

private float TimeSignature(float speed)
{
    return 1.0f / (1.0f + 80.0f * Mathf.Exp(-speed * 0.02f));
}


texts: How to create an animation clip that changes whatever color a RawImage has to a certain destination color?

texts:
I created an animation clip that turns a certain RawImage's color from white to red.
I'd like to know how I could change that clip to turn any color that the RawImage might have into red - with other words, I don't want to have a specific starting color. Instead the current color shall be used and faded to red.


texts: What is wrong with my 2D orbit calculation?

texts:
I am working on a 2D game, and I am working on adding some space physics, so I need to find a way to create a circular orbit.

I want to make my game object move on a circular way around a planet. I'm starting with the old famous formula:

V = sqrt(G * ((m1 + m2 ) / r))

This formula is the classic real world one, V is the velocity of the game object.

Once I code it, it doesn't move on a circular way, it just being attracted by the planet, like normal gravity. Here's my code (I'm using Unity):

dist = new Vector2(
  Planet.renderer.bounds.center.x - renderer.bounds.center.x,
  Planet.renderer.bounds.center.y - renderer.bounds.center.y
);
r = dist.magnitude;
rigidbody2D.velocity = dist.normalized * (Mathf.Sqrt (0.5f * ((mBody + mPlanet) / r)));

Dist is a 2D vector and r is a float, The G value is 0.5 (I used this one because 6.673E-11 is very small and it's not what I want)

So the question is is how can I make my GameObject move on a circular orbit like a satellite around earth ?

One thing to note, is that my GameObject is kicked by the player, so it get a speed of 12. (I am using addForce()).


texts: Unity - Change base class variable to a derived class in inspector dynamically

texts:
In an item system I'm trying to create I'm using prefabs to store an item's default values, and then grab that item from the prefab to use in runtime. It works well, but I was wondering if there was a way to dynamically change a variable with a base type to a derived type, probably with a custom editor, so that I wouldn't have to make separate classes for each derived type. This is the how I'm imagining it would be like:
public class ItemPrefab : Monobehaviour {
    public ItemTypes itemType;
    public Item item;
}

public enum ItemTypes {
    meleeWeapon,
    rangedWeapon
}

Item is an abstract base class, and MeleeWeapon and RangedWeapon are serializable derivatives. With that, I'm trying to do something to the effect of this:
switch (itemType) {
    case ItemTypes.meleeWeapon:
        item = item as MeleeWeapon;
        break;
    case ItemTypes.rangedWeapon:
        item = item as RangedWeapon;
        break;
}

I was wanting it to be the same as the below, just less scripts.
public class MeleeWeaponItemPrefab : Monobehaviour {
    public MeleeWeapon item;
}

public class RangedWeaponItemPrefab : Monobehaviour {
    public RangedWeapon item;
}

Edit: Here is my item system so far (I just included MeleeWeapon because I didn't want this to get too long).
public abstract class Item {

    [Header("Basic Info")]
    [SerializeField] private string name = "";
    [SerializeField] private Image icon = null;
    [SerializeField] private GameObject itemPrefab = null;
    [SerializeField] private float weight = 0;
    [SerializeField] private int maxStack = 0;
    private Guid gUID;

    public string Name => name;
    public Image Icon => icon;
    public GameObject ItemPrefab => itemPrefab;
    public float Weight => weight;
    public int MaxStack => maxStack;
    public Guid GUID { get { return gUID; } private set { gUID = Guid.NewGuid(); } }
}

public abstract class Weapon : Item {
    public abstract void Attack();
}

[System.Serializable]
public class MeleeWeapon : Weapon {

    [Header("Weapon Attributes")]
    [SerializeField] private MeleeWeaponTypes weaponType = default;
    [SerializeField] private float damage = 0;
    [SerializeField] private float chargeDamage = 0;
    [SerializeField] private float meleeSpeed = 0;
    [SerializeField] private float chargeTime = 0;
    [SerializeField] private float chargeCooldown = 0;

    public MeleeWeaponTypes WeaponType => weaponType;
    public float Damage => damage;
    public float ChargeDamage => chargeDamage;
    public float MeleeSpeed => meleeSpeed;
    public float ChargeTime => chargeTime;
    public float ChargeCooldown => chargeCooldown;

    public override void Attack() {
        // attack
    }
}

I have other stuff in Weapon and its derivatives but I removed it to keep the base idea more simple. Anyway, I then have prefabs with a MonoBehaviour that hold a derived type of Item, like I showed above, as data containers that I use to instantiate items during runtime.


texts: Terrain shader from heightmap opengl GLSL

texts:
I generated a terrain from a heightmap and now I'd like to apply  shader on it which can contain different textures, based on height but I can't adapt any online code to my project.
This is the GL_LINE rendered image

The matrix generated from the heightmap has 0-255 values and -1 as the endline character.

This is the code of the terrain, the matrix is stored in a map<int, map<int, int>> data;structure:

#include "Terrain.h"

Terrain::Terrain(Scene* s, string filename): Entity(s) {
    this->hm = s->getHeightmap(filename);
    texture = scene->getTexture("avatar2.jpg");
    shader = scene->getShader("terrain.shader");
}

Terrain::~Terrain() {
}

void Terrain::draw() {
    cout << "Draw Terrain" << endl;
    glPolygonMode(GL_FRONT_AND_BACK,GL_LINE);
    //glUseProgramObjectARB(0);
    glUseProgram(this->shader->getRes());
    glTranslated(0, -20, -31.4);
    glRotatef(45, -1, 0, 0);

    const float offX = -25;
    const float offY = 0;
    const float lato = 0.5;
    const int limit = 100;
    const int limsx = 0;

    glBegin(GL_QUADS);
    for (float i = limsx; i < limit-1; ++i) {
        for (float j = limsx; j < limit-1; ++j) {
            glVertex3f(offX+lato*(j+1), offY+lato*i, hm->getHeight(i,j+1)/50);
            glVertex3f(offX + lato*(j + 1), offY + lato*(i + 1), hm->getHeight(i + 1, j+1)/50);
            glVertex3f(offX + lato*j, offY + lato*(i + 1), hm->getHeight(i+1, j)/50);
            glVertex3f(offX + lato*j, offY + lato*i, hm->getHeight(i, j)/50);
        }
    }
    glEnd();
}

Can you help me generating a terrain shader? Thank you very much

EDIT: thanks a lot to sakul_ca. This is what I got by using and editing his code

I used a shader that applies 4 textures to different heightmap values


texts: How to determine contact bodies when multiple bodies overlap and a third makes contact with both at the same time

texts:
I understand how the below DidBeginConact function works, but how do you detect which categories make contact when you have multiple colored bars (in the example code) or a friend category and enemy category when an enemy overlaps a friend or two enemies overlap and a projectile category intersects both at the same time?

func didBeginContact(contact: SKPhysicsContact) {

var firstBody: SKPhysicsBody
var secondBody: SKPhysicsBody

if contact.bodyA.categoryBitMask < contact.bodyB.categoryBitMask {
    firstBody = contact.bodyA
    secondBody = contact.bodyB
} else {
    firstBody = contact.bodyB
    secondBody = contact.bodyA
}

if firstBody.categoryBitMask == RedBallCategory &&
   secondBody.categoryBitMask == GreenBarCategory {

    (secondBody.node!.removeFromParent())
    score++
    scoreLabel.text = "\(score)"
} else if firstBody.categoryBitMask == GreenBallCategory &&
          secondBody.categoryBitMask == RedBarCategory {

    (secondBody.node!.removeFromParent())
    score++
    scoreLabel.text = "\(score)"
}

I've tried so many different combinations I can't keep them all straight or remember what I've tried and what I haven't.

Thanks in advance for help and suggestions in this.


texts: Which parts of my game should be Activity objects?

texts:
Currently my game has an Activity for the splash screen then it starts the main class activity then it starts a menu activity then from the menu there is an activity for each option (only two at the moment), Start and About.

Splash --> Main --> Menu --> (Start, About)

The start then sets a Content View for my game to draw to the screen.

What additional parts to a game should have or require an activity and what parts that I may or may not have don't need to be an Activity.

Activity:

  An activity is a single, focused thing that the user can do. Almost
  all activities interact with the user, so the Activity class takes
  care of creating a window for you in which you can place your UI with
  setContentView(View)

Since we know what an Activity is, now I am just looking for places that it would be used in a game?

UPDATE

We have a great explanation of the game architecture in Android. This diagram is awesome!


texts: How to sell Android game if selling through Market is not available in your country

texts:
Android Market doesn’t allow developers from my country to sell app. From what I understand the only chance to make some profit is to place ads in my application.

Does ads make a decent profit or is there some other way to earn money are there any other payments system available for Android to bypass Google’s limitations?


texts: How do I set bullets to shoot from the correct position on the sprite?

texts:
How can I set the bullets start position to shoot from the front right of the sprite?

It is currently shooting from the top of the sprite.

P.S. I'm doing a tutorial online with the sprite shooting upwords. I'm trying to change the direction of the bullet to shoot sideways to the right, which I got but the starting position isn't correct.

Here's my the code:

// Extending bullets sprite to funtion in the game
class Bullet extends Sprite {
    constructor(divName, assetDesc, position) {
        super(divName, position, assetDesc.fileName, new Size(assetDesc.width, assetDesc.height));
        this.life = GameSettings.bulletLife;
        this.dead = false;
        this.addToBoard(true);
    }

// Defining the bullets funtions to update throughout the game & bullet direction
update(dt) {
    let inc = dt * GameSettings.bulletSpeed;
    this.incrementPosition(inc, 0);
    this.life -= dt;
    if (this.life < 0) {
        this.killMe();
    }

}
    killMe() {
        this.dead = true;
        this.removeFromBoard();
    }
}

// Collection of bullets & how many added to player
class BulletCollection {
    constructor(player) {
        this.listBullets = [];
        this.lastAdded = 0;
        this.player = player;
        this.total_bullets = 0;
    }

    reset() {
        for (let i = 0; i < this.listBullets.length; ++i) {
            this.listBullets[i].removeFromBoard();
        }
        this.listBullets = [];
        this.lastAdded = 0;
        this.total_bullets = 0;
    }
// Bullets update
    update(dt) {
        for (let i = this.listBullets.length - 1; i >= 0; --i) {
            if (this.listBullets[i].dead == true) {
                this.listBullets.splice(i, 1);
            } else {
                this.listBullets[i].update(dt);
            }
        }
        this.lastAdded += dt;

// Detection to whether we need to add bullet to the game
        if (this.lastAdded > GameSettings.bulletFireRate &&
            this.player.state != GameSettings.playerState.hitFlashing) {
                this.lastAdded = 0;
                this.listBullets.push(
                    new Bullet(
                        'bullet_' + this.total_bullets,
                        GameManager.assets["burrito_dog"],
                        new Point(this.player.position.x + (this.player.size.width / 2),
                        this.player.position.y)
                    )
                );
                this.total_bullets++;
            }
    }
}

Thank you for the support!

Here's an img for reference:


texts: Required Security Precautions for Flash / AS3 Multiplayer Game

texts:
I have created a couple of games in Flash/AS3 and am playing with programming a flash-based multiplayer (possibly mmo?) game where the application will communicate with a server over a socket connection.

Obviously I need some form of authentication (username and password) but what other security precautions do I  need to explore to prevent cheating?


texts: How to achieve after-image pixel shader effect

texts:
How would one go about writing a pixel shader like this one in XNA 4.0?

http://www.youtube.com/watch?v=f1uZvurrhig&feature=related


texts:
According to this page Events in unity are suppose to execute in a specific order.  Specifically, OnCollisionEnter is supposed to be called right after OnTriggerEnter; however, FixedUpdate and Update are both being called at least once in between calls to my OnTriggerEnter2D and OnCollisionEnter2D functions in my Enemy class, why is this the case?

Here is my code:

public class Enemy : Combatant
{
public int kill_points;
public float force;
public List<GameObject> path_verticies;
private int pathi;
private bool on_path;
private bool is_flying;
private bool ignore_collision;          //Used for ignoring collisions with walls, if the enemy has already touched an enemy_controller.

void Start ()
{   Init();
    pathi = 0;
    ignore_collision = false;
    is_flying = false;
    if (gameObject.tag.Contains("Fly")) is_flying = true;//Assuming contains is cheaper than a full string compare.
    on_path = null != path_verticies && 0 != path_verticies.Count;
}

private void FixedUpdate() { ignore_collision = false; }

void Update ()
{   if (!CheckBounds()) Destroy(gameObject);
    if (on_path)
    {   transform.LookAt(path_verticies[pathi].transform, Vector3.up);
        transform.Rotate(new Vector3(0,-90,0));
        phys.velocity = transform.right * speed;
    }
    else dx = Mathf.Sign(Cx) * speed;
}

public void Flip(){ Cx *= -1; }

#pragma warning disable CS0642 // Possible mistaken empty statement
private IEnumerator OnCollisionEnter2D(Collision2D collision)
{   if (on_path && path_verticies[pathi] == collision.gameObject)
    {   if (collision.gameObject == player)
        {   throw new System.NotImplementedException();
            yield return new WaitForSeconds(0.1f);//Used to prevent damage to the player if the player landed on top of the enemy.
            var atk = player.GetComponent<Combatant>().vigor.Attack(2);
            if (Health.Atk.DIES == atk) player.GetComponent<Life>().Die();
        } else pathi = (pathi+1) % path_verticies.Count;
        yield return new WaitForSeconds(0.0f);
    }
    else if (on_path)
    {   if (collision.gameObject == player)
        {   yield return new WaitForSeconds(0.1f);//Used to prevent damage to the player if the player landed on top of the enemy.
            var atk = player.GetComponent<Combatant>().vigor.Attack(2);
            if (Health.Atk.DIES == atk) player.GetComponent<Life>().Die();
        } else if (collision.collider == On(Truebounds)) /*nothing*/;
        else if (collision.gameObject.layer == 0 || collision.gameObject.layer == 8)// TODO
            /*take velocity in the direction opposite of the normal and add it to
             * the perpendicular component the enemy is moving in*/;
        yield return new WaitForSeconds(0.0f);
    }
    else
    {   if (collision.gameObject == player)
        {   yield return new WaitForSeconds(0.1f);//Used to prevent damage to the player if the player landed on top of the enemy.
            var atk = player.GetComponent<Combatant>().vigor.Attack(2);
            if (Health.Atk.DIES == atk) player.GetComponent<Life>().Die();
        } else if (ignore_collision) /*nothing*/;
        else if (collision.collider == On(Truebounds)) { if (is_flying) Flip(); }
        else if (collision.gameObject.layer == 0 || collision.gameObject.layer == 8) Flip();
        yield return new WaitForSeconds(0.0f);
    }
}

private IEnumerator OnTriggerEnter2D(Collider2D collider)
{   var component = collider.GetComponent<MonoBehaviour2>();
    if(!component) yield return null;
    else if (on_path && path_verticies[pathi] == collider.gameObject)
        pathi = (pathi+1) % path_verticies.Count;
    else if (on_path) /*nothing*/;
    else if (component.type == typeof(Enemy_Controller)) { Flip(); ignore_collision = true; }
    yield return null;
}
#pragma warning restore CS0642 // Possible mistaken empty statement

//public void OnDestroy(){  }
}

and these are my timestep settings:


texts: NavMeshAgent fails to find paths in certain areas in NavMesh

texts:
I've been using Unity for about 2 days, and I have a scene with a navmesh. I can click on the NavMesh and get the NavMeshAgents to move to that position most of the time. However, there is a region of the NavMesh where it fails to generate a path to. I technically have two NavMeshes, because I have two different sized NavMeshAgents, but both fail in the same region. Since I'm very new to Unity, I don't know how to diagnose this, much less fix it. How should I go about learning more about this problem?
I can path through the affected area, as long as the destination point is on the other side of it. Also, when I put a cube in the middle of the affected area and rebake the NavMesh, the problem area moves to a new location, so it must have something to do with the geometry.


texts: Ambient occlusion: Correct culling after anisotropy correction

texts:
I've added simple color based ambient occlusion to my game.

First it looked like this (from giawa.com):

The description: "Due to anisotropy, the ambient occlusion shading on the top left is inconsistent with the top right. We need to flip those quads so that they get rendered properly."

So according to that I had to flip some faces in order to fix the issue. I did and then it would look like this:

This is of course because of back face culling, culling the flipped faces.

When I disable culling, it looks like this:

Which is how it's supposed to look. But as you can imagine, that costs a lot of performance because culling is now disabled.

According to the article: http://www.giawa.com/author/giawa/page/10/
"This occurs due to differences in how the GPU linear interpolates across the edge of a triangle versus the body of a triangle. This is called anisotropy, and can be fixed by ‘flipping’ the quad. My final fix was to enable polygon culling, which meant I had to make sure to render my quads in a consistent winding. "

I've searched for this "polygon culling" but could not find anything about that.

I can't just switch between culling modes because all the vertexes are added to a vertex buffer when initializing a chunk. This is so I can render each chunk in one draw call.

I hope anyone knows a way to fix this, thanks in advance.


texts: Game "Hocus": How to do the path finding?

texts:
I rebuild popular apps to get good at Godot. This game Hocus poses a challenge in terms of path finding. I have a solution, but as the illusions scale, it becomes ridiculously time-consuming to set up. I set destination, to which the cube can go, but then you have to set up possible connections for every destination, because there're supposed to be constraints. This can lead to something like 100 variations to be set up for one level, which is of course ridiculous if you want to do 100 levels like the creators. Any idea?

This is a video, where you can exactly see the pathfinding mechanism. Short description:
Whenever you're at one corner of the bars of the illusion graphic (it's just a 2D graphic), you have to set up ways, where the player can go next, because some ways are invalid in this illusion, logically. This is what I intended with setting up an array of numbers, which represent the possible next points for each point. However, this is extremely time-consuming if levels reach even slightly more complexity. I highly doubt the creators did it that way.


texts: using a wire-frame shader on a plane how can i also fill in the squares with a solid color so that each square's color can be changed?

texts:
I'm not sure if using a shader is the best way for what I'm trying to achieve, but I would like to apply a color to each of the squares like in the picture and have the ability to change each color separately. I got the shader on this site: Link to Shader site

Shader "Custom/Geometry/Wireframe"
{
Properties
{
    [PowerSlider(3.0)]
_WireframeVal("Wireframe width", Range(0., 0.5)) = 0.05
    _FrontColor("Front color", color) = (1., 1., 1., 1.)
    _BackColor("Back color", color) = (1., 1., 1., 1.)
    [Toggle] _RemoveDiag("Remove diagonals?", Float) = 0.
}
    SubShader
{
    Tags{ "Queue" = "Geometry" "RenderType" = "Opaque" }

    Pass
{
    Cull Front
    CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#pragma geometry geom

    // Change "shader_feature" with "pragma_compile" if you want set this
keyword from c# code
#pragma shader_feature __ _REMOVEDIAG_ON

#include "UnityCG.cginc"

    struct v2g {
    float4 worldPos : SV_POSITION;
};

struct g2f {
    float4 pos : SV_POSITION;
    float3 bary : TEXCOORD0;
};

v2g vert(appdata_base v) {
    v2g o;
    o.worldPos = mul(unity_ObjectToWorld, v.vertex);
    return o;
}

[maxvertexcount(3)]
void geom(triangle v2g IN[3], inout TriangleStream<g2f> triStream) {
    float3 param = float3(0., 0., 0.);

#if _REMOVEDIAG_ON
    float EdgeA = length(IN[0].worldPos - IN[1].worldPos);
    float EdgeB = length(IN[1].worldPos - IN[2].worldPos);
    float EdgeC = length(IN[2].worldPos - IN[0].worldPos);

    if (EdgeA > EdgeB && EdgeA > EdgeC)
        param.y = 1.;
    else if (EdgeB > EdgeC && EdgeB > EdgeA)
        param.x = 1.;
    else
        param.z = 1.;
#endif

    g2f o;
    o.pos = mul(UNITY_MATRIX_VP, IN[0].worldPos);
    o.bary = float3(1., 0., 0.) + param;
    triStream.Append(o);
    o.pos = mul(UNITY_MATRIX_VP, IN[1].worldPos);
    o.bary = float3(0., 0., 1.) + param;
    triStream.Append(o);
    o.pos = mul(UNITY_MATRIX_VP, IN[2].worldPos);
    o.bary = float3(0., 1., 0.) + param;
    triStream.Append(o);
}

float _WireframeVal;
fixed4 _BackColor;

fixed4 frag(g2f i) : SV_Target{
    if (!any(bool3(i.bary.x < _WireframeVal, i.bary.y < _WireframeVal,
[![Plane with Shader attached][1]][1]i.bary.z < _WireframeVal)))
    discard;

return _BackColor;
}

    ENDCG
}

    Pass
{
    Cull Back
    CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#pragma geometry geom

    // Change "shader_feature" with "pragma_compile" if you want set this
keyword from c# code
#pragma shader_feature __ _REMOVEDIAG_ON

#include "UnityCG.cginc"

    struct v2g {
    float4 worldPos : SV_POSITION;
};

struct g2f {
    float4 pos : SV_POSITION;
    float3 bary : TEXCOORD0;
};

v2g vert(appdata_base v) {
    v2g o;
    o.worldPos = mul(unity_ObjectToWorld, v.vertex);
    return o;
}

[maxvertexcount(3)]
void geom(triangle v2g IN[3], inout TriangleStream<g2f> triStream) {
    float3 param = float3(0., 0., 0.);

#if _REMOVEDIAG_ON
    float EdgeA = length(IN[0].worldPos - IN[1].worldPos);
    float EdgeB = length(IN[1].worldPos - IN[2].worldPos);
    float EdgeC = length(IN[2].worldPos - IN[0].worldPos);

    if (EdgeA > EdgeB && EdgeA > EdgeC)
        param.y = 1.;
    else if (EdgeB > EdgeC && EdgeB > EdgeA)
        param.x = 1.;
    else
        param.z = 1.;
#endif

    g2f o;
    o.pos = mul(UNITY_MATRIX_VP, IN[0].worldPos);
    o.bary = float3(1., 0., 0.) + param;
    triStream.Append(o);
    o.pos = mul(UNITY_MATRIX_VP, IN[1].worldPos);
    o.bary = float3(0., 0., 1.) + param;
    triStream.Append(o);
    o.pos = mul(UNITY_MATRIX_VP, IN[2].worldPos);
    o.bary = float3(0., 1., 0.) + param;
    triStream.Append(o);
}

float _WireframeVal;
fixed4 _FrontColor;

fixed4 frag(g2f i) : SV_Target{
    if (!any(bool3(i.bary.x <= _WireframeVal, i.bary.y <= _WireframeVal,
i.bary.z <= _WireframeVal)))
    discard;

return _FrontColor;
}

    ENDCG
}
}
}


texts: How to store an array of prefabs together with configuration parameters

texts:
I have attached the following script to a number of weapon prefabs:

public class WeaponScript : MonoBehaviour {

    public enum Direction {Right, Straight, Left};
    public Direction weaponDir;

    void Start () {
        prepareDirection (weaponDir);
    }

    void prepareDirection(Direction dir)    {
        if (dir == Direction.Straight)  {
            transform.localEulerAngles = new Vector3 (0, 0, 0);

        }

        else if(dir == Direction.Left)  {
            transform.localEulerAngles = new Vector3 (0, 0, -30);
        }

        else if(dir == Direction.Right) {
            transform.localEulerAngles = new Vector3 (0, 0, 30);

        }
    }
}

I also added the following script to an empty game object SetupWeapon:

public class SetupWeaponsScript : MonoBehaviour {

    public GameObject[] weaponPrefabs;
    public GameObject[] weapons;

    void Start ()
    {
        weapons = new GameObject[weaponPrefabs.Length];

        for (int i = 0; i < weaponPrefabs.Length; i++)
        {
            weapons[i] = Instantiate(weaponPrefabs[i]) as GameObject;
        }

    }
}

When I select my SetupWeapon object, I am able to populate the weaponPrefabs array with the weapon prefabs I want to use, but I can't directly alter their parameters in that same inspector view. I want to be able to override the direction of each weapon prefab in the list, rather than use the value that's stored on the prefab itself.

How can I create the weaponsSetupScript in such a way that I can set the direction enum for each weapon entry at the same time that I set select the prefab in the editor? I believe it might have something to do with inheritance, just not too sure how to go about it though.


texts: How do you use the distributive law with Quaternions and vectors?

texts:
I'm trying to solve for the distance from Obj1 to Obj2 relative to Obj1, because I do not know their global positions, rotations, or the difference between their local spaces.

Thankfully, they are locked to each-other, so their relationship relative to Obj1 is constant across time.

I believe that the following is true, assuming A and B represent discrete samples at different times where the objects moved between A and B:
Obj1.positionB + Obj1.rotationB * relationship = Obj1.positionA + Obj1.rotationA * relationship + (Obj2.positionB - Obj2.positionA)

Given that, we can solve for relationship, right? First, move all instances of relationship to the left side...
Obj1.rotationB * relationship - Obj1.rotationA * relationship = Obj1.positionA + (Obj2.positionB - Obj2.positionA) - Obj1.positionB

From here, the AB+AC = A(B+C) rule tells me to do this:
(Obj1.rotationB - Obj1.rotationA) * relationship = Obj1.positionA + (Obj2.positionB - Obj2.positionA) - Obj1.positionB

But I know that QuaternionAVector+QuaternionBVector does NOT equal (QuaternionA*QuaternionB)*Vector.

So, given QuaternionA*VectorA+QuaternionB*Vector = VectorB, is it possible to solve for VectorA? How? I'm using Unity, if that's any help.

(Note that the above assumes that the two coordinate spaces are oriented consistently even though they don't share the same origin. Solving for difference in parent space orientation, if ever necessary, is a different problem.)


texts: Why does calling GL.Color4 result in a blank screen?

texts:
I am learning OpenGL using OpenTK and VB.NET. I made a square with a texture:

    GL.Begin(BeginMode.Quads)
    GL.TexCoord2(0.0, 0.0)
    GL.Vertex3(-1.0, 1.0, 0.0)
    GL.TexCoord2(1.0, 0.0)
    GL.Vertex3(1.0, 1.0, 0.0)
    GL.TexCoord2(1.0, 1.0)
    GL.Vertex3(1.0, -1.0, 0.0)
    GL.TexCoord2(0.0, 1.0)
    GL.Vertex3(-1.0, -1.0, 0.0)
    GL.End()

This works fine and produces this image:

When I add GL.Color4, the whole screen is completely blank. This is what my code looks like:

    GL.Color4(100, 100, 100, 255)
    GL.Begin(BeginMode.Quads)
    GL.TexCoord2(0.0, 0.0)
    GL.Vertex3(-1.0, 1.0, 0.0)
    GL.TexCoord2(1.0, 0.0)
    GL.Vertex3(1.0, 1.0, 0.0)
    GL.TexCoord2(1.0, 1.0)
    GL.Vertex3(1.0, -1.0, 0.0)
    GL.TexCoord2(0.0, 1.0)
    GL.Vertex3(-1.0, -1.0, 0.0)
    GL.End()

Here is an additional piece of code:

    GL.ShadeModel(ShadingModel.Smooth)
    GL.ClearColor(Color.Black)
    GL.ClearDepth(1.0)

    GL.Enable(EnableCap.Texture2D)
    GL.BlendFunc(BlendingFactorSrc.SrcAlpha, BlendingFactorDest.One)
    GL.Enable(EnableCap.Blend)

    GL.Hint(HintTarget.PerspectiveCorrectionHint, HintMode.Nicest)


texts: Unity: How do I only show parts of objects that overlap [2D]

texts:
I'm working on a 2D Unity project where the player can only see objects in their field of view. I have successfully created a mesh that overlaps anything that would be in the player's field of view, but now I'm having trouble with only showing parts of objects that the mesh overlaps with.

Here is what I have so far (the gray area is the player's field of view which is a mesh:

Here is the type of thing that I'm looking for:

What can I do to get that desired effect? Shaders (I have no clue how to use shaders)? Colliders? Any ideas would be greatly appreciated. If there is any info you need that I didn't provide, comment and I add the necessary info. Thank you in advance!


texts: Unity How does Time.smoothDeltaTime work

texts:
I can't seem to find any actual information on what Time.smoothDeltaTime does or how it works.

I would assume it takes a rolling average of previous deltaTimes but how does it do that? Is the average asymptotic? How sensitive is it to outliers? What is it's actual intended use case?

If anyone could explain how it works, or link to a resource on what it is doing it would be really helpful.


texts: Prevent Unity from crashing your computer?

texts:
Recently, I made a very dumb mistake that caused Unity to crash my computer. I could move the mouse sometimes, but everything else became completely unresponsive, leading to me having to shut off my PC.

What happened: I had an object, let's say an arrow, that could collide with another object, let's call it spawner. When the arrow collides with the spawner, it's supposed to destroy the arrow that activated the spawner. The spawner would then, as the name might imply, spawn more arrows. The problem was that I forgot to temporarily disable to collision on the newly spawned arrows, meaning that as soon as they would spawn inside the spawner's collision box, they'd spawn more arrows, and those arrows would spawn more arrows, and those arrows would... you get the idea. It was a very stupid mistake I realized the moment I hit play, but it was too late.

Now, I know that was entirely my fault, but I was wondering if you could prevent Unity from sending your PC into a coma like that? (Besides not making a dumb mistake like that, of course...) I'll be honest, I kind of expected Unity would have some sort of fail safe for this kind of error. Is there a way to limit the object count for example?


texts:
Is there a way to change the scene after playing a timeline with the new timeline system?

I have 3 scenes in my project. The first scene is where a player interacts with an object to trigger a change to the second scene. The second scene then plays my timeline. When the timeline finished playing I want to change to the 3rd scene.

How can I trigger the scene change at the end of that timeline?


texts:
TLDR: using typeof(T) twice; assigning the value to a variable and reusing that = uber fast (30FPS), actually calling typeof(T) twice = derped (5FPS). Why?

I have a simple entity/component system; my basic entity had an array of IComponents, and methods like HasComponent<T> and GetComponent<T>. These just iterate over the arrays and return the first matching item (this.components.Any(c => c is T)).

Turns out a performance bottleneck I experience with 100k components "in memory" (albeit most off-screen) is actually these two methods. With a few components, no problem (30FPS+). With 100k components, just sprites, I get around 5FPS.

So I figured, why not use a Dictionary<Type, IComponent> instead? It'll be faster, right?

Right?!

Wrong. First, a complexity: I have a SpriteComponent class, and a SpriteSheetComponent component class (knows about frames, animation, etc.). To simplify everything, SpriteSheetComponent derives from SpriteComponent. This makes drawing, ordering, etc. simpler, because of the is-a relationship.

Second, querying for components became more complex; if I ask HasComponent<SpriteComponent>, and you have a SpriteSheetComponent, you should return true, right?

So the way I handle that is:

return this.components.Keys.Any(t => t == typeof(T) || t.IsSubclassOf(typeof(T)));

Ditto for fetching the element, except I use First instead of Any.

Anyway, I noticed that the performance actually degraded. What's even more surprising is that this fixed the performance issue:

var tType = typeof(T);
return this.components.Keys.Any(t => t == tType || t.IsSubclassOf(tType));

The only difference is that I'm checking typeof(T) once and reusing that. This fixed my FPS up to 30ish, hurrah.

But this is definitely a "lolwut" moment for me. Is typeof(T) really that slow? And in this case, it's shredding my performance with just one extra call?


texts: I am trying to implement a falling animation to my game and i am having alot of problems doing so

texts:
i am trying to have it so that when my character isnt touching anything he plays an animation of falling, yet when he moves from one game object to different one, he plays the animation. for example if he steps from one platform to another, even if he doesnt have to jump, he plays the falling animation. How would i make it so that when he jumps and doesnt touch anything he plays the animation?

  void Update()
{
    if(!colliding)
    {
        animator.Play ("Fall");
    }
  }
  void OnCollisionEnter(Collision collision)
{
    colliding = true;

}
void OnCollisionExit(Collision collision)
{
    colliding = false;
}


texts: How to correctly implement custom tick system?

texts:
I am making a custom tick system to suit my needs (calling normal ticks every 0.2 seconds, medium ticks every 5 seconds etc...)
I followed the tutorial in this video: CodeMonkey tick system tutorial
In his tutorial, he implements the tick counting as shown:
    private const float tickTimerMax = 0.2f;

    private void Update()
    {
        tickTimer += Time.deltaTime;

        if (tickTimer >= tickTimerMax)
        {
            tickTimer -= tickTimerMax;
            Tick++;

            // Happens every 0.2 seconds.
            OnTick?.Invoke(this, new OnTickEventArgs {Tick = Tick});
        }
    }

However, in other sources I have seen that instead of subtracting tickTimerMax from tickTimer, we just straight up set the tickTimer to 0, as shown:
if (tickTimer >= tickTimerMax)
    {
        tickTimer = 0;
        Tick++;
    }

It's hard to say if there's a big difference between these two methods, because at first glance they seem to do the same thing, but clearly they have their differences. So I'm wondering, which one I should use?


texts:
I use LWRP, one Directional Light and Hard Shadows with 1024 resolution. When I imported this super simple mesh from blender this happened:

What is this weird line on the stitch of the mesh and how do I fix it? I tried using Soft Shadows with higher quality but it did not help.


texts: Finding which tiles are intersected by a line, without looping through all of them or skipping any

texts:
I've been staring at this problem for a few days now. I rigged up this graphic to help me visualise the issue:

(from the graph, we know that the line intersects [1, 1], [1, 2], [2, 2], [2, 3], ending in [3,3])

I want to step along the line to each grid space and check to see if the material of the grid space is solid. I feel like I already know the math involved, but I haven't been able to string it together yet. I'm using this to test line of sight and eliminate nodes after a path is found via my pathfinding algorithms - my agents cant see through a solid block, therefore they cant move through one, therefore the node is not eliminated from the path because it is required to navigate a corner.

So, I need an algorithm that will step along the line to each grid space that it intersects. Any ideas?

I've taken a look at a lot of common algorithms, like Bresenham's, and one that steps at predefined intervals along the line (unfortunately, this method skips tiles if they're intersecting with a smaller wedge than the step size).

I'm populating my whiteboard now with a mass of floor() and ceil() functions - but its getting overly complicated and I'm afraid it might cause a slowdown.