texts: Technique suggestion to render corroded pipes in 3D

texts:
We currently have a lot of data relating to cracks/corrosion/deformations in metal pipes which at present, can be viewed in a crude flat/2D application which makes the metal anomalies hard to spot.

What I would like to create is a virtual 3D pipe viewer that displays the pipe and then models all of the dents in it.

I have limited knowledge of graphics programming from University however, what I was thinking of doing is creating a height-map from the data given and then use tessellation to push/pull the vertices of the pipes mesh, similar to terrain generation techniques.

My Question(s):

Can a tessellated square/plane be wrapped around to form a pipe (and would this approach loose accuracy)? (I've only ever manipulated vertices in the y-direction on a flat plane).
Some of the dents are extremely small (1-5mm across/deep), would my approach be accurate enough to model these anomalies?
Is this tessellated/terrain generation style the correct way to proceed or is there a simpler solution.

Any advise is welcome


texts:
When using an Orthographic Camera, the shadows appear to be of poor quality.

How can I display smooth shadows?


texts: 3D collision response advice for complex meshes

texts:
I am trying to use my own collision detection system in Unity to speed up my game. My problem is that when rigid bodies sit on top of static bodies, they will balance unrealistically on one edge or a corner. I really just need a better way of fixing this issue, but I will explain further.
The way I am detecting collisions right now will probably change because it isn't great but I am simply making a list of unique vertices of the mesh, and testing if those points are inside another mesh (it's a voxel game so that is a bit easier than it might otherwise be). I eventually want to either figure out a better way or just cast points along the edges too and call it good enough.
I have tried adding a force to the point of collision to try and "settle" the rigid body into place, and this sort of works, it's just that once it has settled, it vibrates wildly just sitting on top of a static mesh... I can get it to either slowly float down into a settled position or it does it fast but vibrates wildly after settling on a static mesh.
I would appreciate any ideas at all, even if they are bad ones. Thank you.


texts:
this might seem like a silly question but I'm raycasting on specific objects (Targets) in a scene and zooming in on them but i also have a few UI elements (buttons, toggles...) on the side of the screen that need to always be visible because they provide certain functionalities (isolate target, switch view...).

The problem is that sometimes when i want to click on a certain UI element I unintentionally send a Raycast that changes my target. Moving the UI elements is not helpful since the objects occupy the whole screen. What other ways do I have to make sure I'm only clicking the UI element? (especially for smaller screens)


texts: How can I make a shader effect that looks like a lightly shaded pencil drawing?

texts:
I want to make a shader effect using OpenGL ES 2.0 that looks like this image:

I'm not sure if this image was painted or is the result of some filter, but I want to create a shader that produces images looking similar.
I want to know a Shader algoritm to produce this kind of output!


texts: Why can I not save preferences on Android?

texts:
I'm using the code in this tutorial (Full LibGDX game tutorial). The code to save the preferences works fine on Desktop but not on Android. Here's how I access and save my preferences:

public class AppPreferences {
private static final String PREF_MUSIC_VOLUME = "volume";
private static final String PREF_MUSIC_ENABLED = "music.enabled";
private static final String PREF_SOUND_ENABLED = "sound.enabled";
private static final String PREF_SOUND_VOL = "sound";
private static final String PREFS_NAME = "b2dtut";

protected Preferences getPrefs() {
    return Gdx.app.getPreferences(PREFS_NAME);
}

public boolean isSoundEffectsEnabled() {
    return getPrefs().getBoolean(PREF_SOUND_ENABLED, true);
}

public void setSoundEffectsEnabled(boolean soundEffectsEnabled) {
    getPrefs().putBoolean(PREF_SOUND_ENABLED, soundEffectsEnabled);
    getPrefs().flush();
}

public boolean isMusicEnabled() {
    return getPrefs().getBoolean(PREF_MUSIC_ENABLED, true);
}

public void setMusicEnabled(boolean musicEnabled) {
    getPrefs().putBoolean(PREF_MUSIC_ENABLED, musicEnabled);
    getPrefs().flush();
}

public float getMusicVolume() {
    return getPrefs().getFloat(PREF_MUSIC_VOLUME, 0.5f);
}

public void setMusicVolume(float volume) {
    getPrefs().putFloat(PREF_MUSIC_VOLUME, volume);
    getPrefs().flush();
}

public float getSoundVolume() {
    return getPrefs().getFloat(PREF_SOUND_VOL, 0.5f);
}

public void setSoundVolume(float volume) {
    getPrefs().putFloat(PREF_SOUND_VOL, volume);
    getPrefs().flush();
}
}


texts: Trouble creating fog and lighting in unity

texts:
I am trying to create a model in unity that looks like this picture by Escher

I can create the lattice, however, I can not create the fog and background/lighting effect. When I adjust the fog in Lighting the cubes just get more of the supposed fog color. Also I don't know how to eliminate the sky and make the lighting more like it is in the picture. Does anybody know how to great the fog and lighting effect I am looking for Thanks
I previously posted this on unity Q and A and got no answer

I can not post my other image with no fog because i do not have enough reputations. It is basically the image I posted just with more shadow and gray cubes.


texts: what is the difference between the regular camera and the first person camera?

texts: I'm asked to implement first person camera but all I know is the regular camera that moves when I hit specific keys and could anyone tell me the steps to implement it?


texts: How to delay a timer when it's run the first time in update method not using a coroutine

texts:
In the code below I am resetting a timer after a duration maxiTime within the update method.
I want to delay the timer before it begins to run for a certain duration. I believe this could be done with a coroutine, but I am using StopAllCoroutines, so I need to do this within the update method. How can I get the delay only before the first run?

        timeElapsed +=1;
    if(timeElapsed >= maxiTime) {

        timeElapsed = 0;

        Debug.Log ("Thank You!");
    }


texts: (Unity) Optimised networking solution for many moving objects

texts:
I've currently undertaking quite an ambitious project. In short, it's a real time multiplayer strategy game which has bacteria mechanics.

Essentially, I have two remote players in the environment, and they can spawn bacteria-like units which attack each other and multiply, duplicating themselves until a resource limit is hit.
This often results in around 200+ game objects being rendered to the screen, each with their own state and movement. This sounds bad, but the local gameplay against a bot is actually very good, and I've managed to make it quite performant.

However, the issue arises when I try to network this game. I have already attempted to follow this guide to implement this feature: http://www.paladinstudios.com/2013/07/10/how-to-create-an-online-multiplayer-game-with-unity/

This produces quite a slow, displeasing game experience even with the best latency. This is likely caused by having to transmit movement data for hundreds of units.

The question I am posing:

How can I optimize the networking and synchronization of many moving units between two clients?

I've already thought of one way to do this. After spawning a unit, they will only travel in one direction until they hit something - perhaps I can synchronize only when units are spawned and when they interact with another object? Would this have much benefit? What's the ideal way to implement this?

Thanks in advance for responses!


texts:
I am writing a Minecraft mod that supports input from the Razer Hydra. It is a pair of motion controllers (one for each hand) that provide incredibly accurate position and rotation information.

For the purpose of this question, rotating the right controller on the Y-axis cause the player's character to look left or right (yaw), and rotating on the X-axis makes the player look up and down (pitch).

The input from the controller is mapped directly to the character's heading. If the controller is rotated 30 degrees left, the character turns 30 degrees to the left.

The problem is that the input "jitters". If I try to hold the controller perfectly still, the character's heading moves erratically within a very small cone (maybe 1 degree).

This is probably due to my shaky hands, as the controller's data is seemingly exact.

I tried filtering input by averaging data from the last X frames, but this makes input seem buttery.

My question is: How can I filter the rotational data to remove jitter without loosing precision?


texts: What server architecture should I use for matchmaking in Node.js?

texts: I'm making a board game in which users register for a game which will start at fixed time and users can register till the start of the game. My initial idea was to use it with socket.io(connection sets up when user opens up the app and use same socket for gameplay) with Redis adapter and fire start game event from outside the context of sockets (using redis adapter and separate process). But my friend suggested to use ws with in-memory state management(for making stateless and not use socket.io for performance) and use polling for showing registering tournaments. Can you please help me with if I'm missing out anything ?


texts:
I am working on an AR application using Unity3D and the Vuforia SDK for Android. The way the application works is a when the designated image(a frame marker in our case) is recognized by the camera, a 3D island is rendered at that spot. Currently I am able to detect when/which objects are touched on the model by raycasting. I also am able to successfully detect a swipe using this code:

if (Input.touchCount > 0)
{
         Touch touch = Input.touches[0];

         switch (touch.phase)
         {
                case TouchPhase.Began:

                    couldBeSwipe = true;

                    startPos = touch.position;

                    startTime = Time.time;

                break;

                case TouchPhase.Moved:

                    if (Mathf.Abs(touch.position.y - startPos.y) > comfortZoneY)
                    {

                        couldBeSwipe = false;

                    }
                    //track points here for raycast if it is swipe
                break;

                case TouchPhase.Stationary:

                    couldBeSwipe = false;

                break;

                case TouchPhase.Ended:

                    float swipeTime = Time.time - startTime;

                    float swipeDist = (touch.position - startPos).magnitude;

                    if (couldBeSwipe && (swipeTime < maxSwipeTime) && (swipeDist > minSwipeDist))
                    {

                        // It's a swiiiiiiiiiiiipe!

                        float swipeDirection = Mathf.Sign(touch.position.y - startPos.y);

                        // Do something here in reaction to the swipe.
                        swipeCounter.IncrementCounter();
                    }

                break;

            }

         touchInfo.SetTouchInfo
          (Time.time-startTime,(touch.position-startPos).magnitude,Mathf.Abs (touch.position.y-startPos.y));
       }

Thanks to andeeeee for the logic. But I want to have some interaction in the 3D world based on the swipe on the screen. I.E. If the user swipes over unoccluded enemies, they die. My first thought was to track all the points in the moved TouchPhase, and then if it is a swipe raycast into all those points and kill any enemy that is hit. Is there a better way to do this? What is the best approach?

Thanks for the help!


texts: Using a dissolve shader as well as the Standard shader

texts:
I'm applying a "burning" dissolve shader to an object which uses the Standard shader already. Because I need the Standard shader for better lighting, etc, I looked into how to use them "both" or how to extend the standard shader.

According to the Unity docs I can define which lighting mode I want to use in the pragma so I used Standard. That must not work the way I thought, because I see none of the lighting I do when using the standard shader directly.

I'm using the burning dissolve shader from Harry Alisavakis

Shader "Custom/BurnDissolve" {
    Properties {
        _Color ("Color", Color) = (1,1,1,1)
        _MainTex ("Albedo (RGB)", 2D) = "white" {}
        _SliceGuide("Slice Guide (RGB)", 2D) = "white" {}
        _SliceAmount("Slice Amount", Range(0.0, 1.0)) = 0

        _BurnSize("Burn Size", Range(0.0, 1.0)) = 0.15
        _BurnRamp("Burn Ramp (RGB)", 2D) = "white" {}
        _BurnColor("Burn Color", Color) = (1,1,1,1)

        _EmissionAmount("Emission amount", float) = 2.0
    }
    SubShader {
        Tags { "RenderType"="Opaque" }
        LOD 200
        Cull Off
        CGPROGRAM
        #pragma surface surf Standard

        fixed4 _Color;
        sampler2D _MainTex;
        sampler2D _SliceGuide;
        sampler2D _BumpMap;
        sampler2D _BurnRamp;
        fixed4 _BurnColor;
        float _BurnSize;
        float _SliceAmount;
        float _EmissionAmount;

        struct Input {
            float2 uv_MainTex;
        };

        void surf (Input IN, inout SurfaceOutputStandard o) {
            fixed4 c = tex2D (_MainTex, IN.uv_MainTex);
            half test = tex2D(_SliceGuide, IN.uv_MainTex).rgb - _SliceAmount;
            clip(test);

            if (test < _BurnSize && _SliceAmount > 0) {
                o.Emission = tex2D(_BurnRamp, float2(test * (1 / _BurnSize), 0)) * _BurnColor * _EmissionAmount;
            }

            o.Albedo = c.rgb;
            o.Alpha = c.a;
        }
        ENDCG
    }
    FallBack "Standard"
}

I also tried adding this as another subshader to a copy of the Standard shader source, but I wasn't able to get it working there. If I put it before the others, it works as if it was alone, if I put it after, the standard shader works like if it was alone.

I'm still new to shaders so I'm sure I'm misunderstanding this. How can I get the dissolve shader to apply as well the standard shader, without hopefully having to manually rewrite stuff.


texts: How can I draw a line of certain length and direction?

texts:
I want to create a line of certain length and direction.

What I mean by this is drawing a line from Point A to Point B.
Normally in Unity C# to draw a line from Point A to Point B is simply:

Debug.DrawLine(point_A, point_B);

The diagram would be something like this

A----------------B

But I dont want something like this, I want it to draw from Point A to Point B but with a certain length. So I am guessing I need the direction for this to work. But I don't know how to code it.

Here is a basic diagram of how i want it.

A--------        B


texts: Unity Raycasting Error: NullReferenceException

texts:
EDIT: I added the if statement:
if(hitInfo.collider != null)

above the
if(hitInfo.collider.CompareTag("Player"))

statement and it seems to work.

I'm trying to give my Enemy AI (Red dude) a line of sight via Raycasting. I want it to initiate the Attack(); function when it sees the Player (blue dude) whose tag is "Player".
I first need to get a "true" statement from the RaycastHit2D to write the rest but the game just crashes whenever the Player is out of the ray. When I put the player in range of the enemy model by hand before running the game, it runs okay:

But when I make something, like jumping, to stay out of the ray, the game crashes and I get the error:

NullReferenceException: Object reference not set to an instance of an object.

It shows the line 90 which corresponds to the line:
if(hitInfo.collider.CompareTag("Player"))

Here is the whole code for my RaycastPlayerDetection() which is called in the Update() function:
 private bool RaycastPlayerDetection()
{
    RaycastHit2D hitInfo = Physics2D.Raycast(EyeSight.position, transform.right, lineOfSight);

        Debug.DrawLine(EyeSight.position, hitInfo.point, Color.red);

        if(hitInfo.collider.CompareTag("Player"))
        {
        Debug.Log("player has been seen");
        return true;
        }
        else return false;

}


texts: arrays last element that has color never gets accessed

texts:
I have assigned this C# script to a spot light. But the green color which is at 2nd position in array never gets accessed and spot light never gets green light. I tried debugging this code but no idea what's wrong

public class CSharping : MonoBehaviour {

    public Light lt;

    Color[] allColor = { Color.red, Color.blue, Color.green};

    // Use this for initialization
    void Start () {
        lt  = GetComponent<Light>();
    }

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

        if(Input.GetButtonDown("Fire1"))
        {
            int colorVariable = Random.Range(0,2);
            lt.color = allColor[colorVariable];
        }

    }
}


texts: best way to compute vertex normals from a Triangle's list

texts:
hi
i'm a complete newbie in computergraphics so sorry if it's a stupid answer.
i'm trying to make a simple 3d engine from scratch, more for educational purpose than for real use.

for now i compute only face normals. in this way:

i have a Surface object with inside a Triangle's list. i compute normals inside Triangle class, in this way:

triangle.computeFaceNormals() {
    Vec3D u = v1.sub(v3)
    Vec3D v = v1.sub(v2)
    Vec3D normal = Vec3D.cross(u,v)
    normal.normalized()
    this.n1 = this.n2 = this.n3 = normal
}

and when building surface:

t = new Triangle(v1,v2,v3)
t.computeFaceNormals()
surface.addTriangle(t)

and i think this is the best way to do that.. isn't it?

now.. this works, ok. but light it's not smoothed. i'm trying to compute also vertex normals. (i'm testing my engine with tubolar surfaces so i have almost all vertex shared with more then one triangles)

i've found this simple algorithm: flipcode vertex normal
but.. hei this algorithm has.. exponential complexity? (if my memory doesn't fail my computer science background..) (bytheway.. it has 3 nested loops.. i don't think it's the best way to do it..)

any suggestion?


texts: How to use atan2 to get the correct angle? (inside or outside angle)

texts:
I would like to rotate an object (white rectangle) towards another object (black rectangle). EDIT: the white rectangle (at the top) has a camera. I finally rotated the camera by 180 around the "y" axis, because it was looking to the right of the image. Now, the goal is to rotate the camera around the "x" axis, by the green angle.

I found some images that explains atan2 :

What I try to do is :

Edit : the green angle seems wrong, here is a new one :

If I refer to the trigonometry circle, I should have a value around -120 :

Would someone know what is happening? Here is the code I am using :

    //boxNode is the black rectangle, boxYellow is the white rectangle at the top
    //163 degrees
    let opposite = boxNode.position.z - boxYellow.position.z
    let adjacent = boxNode.position.y - boxYellow.position.y

    //-73 degrees
    //let opposite = boxNode.position.y - boxYellow.position.y
    //let adjacent = boxNode.position.z - boxYellow.position.z

    camRadians = atan2(opposite, adjacent)
    println("deg: \(convertRad2Deg(camRadians))")

Thanks


texts:
I have an issue while trying to load a font file with the extension ".xnb" and I am receiving following error:

Error loading "SpriteFont1". File not found.

For following code:

public static Dictionary<string, T> LoadListContent<T>(this ContentManager contentManager, string contentFolder)
        {
            DirectoryInfo dir = new DirectoryInfo(contentManager.RootDirectory + "/" + contentFolder);
            if (!dir.Exists)
                throw new DirectoryNotFoundException();
            Dictionary<String, T> result = new Dictionary<String, T>();

            FileInfo[] files = dir.GetFiles("*.*");
            foreach (FileInfo file in files)
            {
                string key = Path.GetFileNameWithoutExtension(file.Name);

                result[key] = contentManager.Load<T>(key);
            }
            return result;
        }

The file is actually there and I am getting here FileInfo[] files = dir.GetFiles("*.*"); one file which is present in the folder.

I am using the function like this:

fontList = ContentLoader.LoadListContent<SpriteFont>(Content, "Fonts");

Is there something which I have overlooked?


texts: Loading and using GLEED2D levels into WP7 Game

texts:
I've been trying to use this modified version of GLEED2D that includes WP7 support,

The progress so far, is I've been able to load the level XML file to the project and read it successfully thanks to This answer

I got in touch with the author of the modified version, he added the answer to the wiki

The problem now is I cannot implement the following steps, according to the wiki, I now need to:

  "enumerate the levels and then enumerate each item in each level. For
  each item, add the object/sprite into XNA."

My initialize() method now looks like this

    protected override void Initialize()
    {

        Stream stream = TitleContainer.OpenStream("Content/leveltest.xml");
        //Stream stream = TitleContainer.OpenStream("Content/level.gleed");
        XElement xml = XElement.Load(stream);
        level = LevelLoader.Load(xml);

        base.Initialize();
    }

When I debug I find the level object loaded successfully and has list of layers and list of items inside the layers, but I'm not sure how to continue my way from here to Display the level items on the screen.

Any idea?

--UPDATE--

I added

foreach (Layer layer in level.Layers)
{
   foreach (LayerItem item in layer.Items)
   {
      item.Properties.Visible = true;
      //something should be added here to draw
   }
}

I am not sure what to add now to draw the item into it's position on screen !?


texts:
So I'm trying to create a simple text input Texas Hold 'Em game that can be played in a Terminal between multiple computer. (Disturbing lack of hold 'em games that don't require Facebook integration or a million ads or micro transactions :c )

With my current knowledge I can create the TCP Server and Connect some clients, but I'm not sure how to proceed from here. How can I communicate between the clients and server turn by turn using text input effectively?
My vague idea of what to do is

Accept clients, store FD in Array
Loop through Id's sending them 2 cards each
Create thread with a game info struct, that reads users text input
Wait for thread to finish and return value will be the players move
Update game info, and move repeat step 3-4 for all Clients
Break whenever only 1 player is left, or all bettings phases are over then repeat

This outline makes sense in the server, but I'm not sure how to construct the client to not do anything until it gets prompted by the thread creation in the main server while loop. If anyone has any advice or links to helpful articles or example code I would really appreciate it thanks so much!!


texts: Is it a good idea to use per pixel collision detection in an isometric game?

texts:
I've completed the per-pixel collision detection for a small side-scroller game, for learning purposes using a Lazyfoo.net tutorial, and I am wondering if it is a good method for detecting collision in an isometric game consisting of a pure 2D world.

My plan is described in this picture:

As you can see, I want to start with bounding boxes, and if I collide with it I start iterating through the tiles rectangles (19, in this case) for better precision. Is it a good way to handle collisions in this type of game? If not, what would be a suitable alternative?


texts: Do you need to pay just to put your game as a closed beta on steam?

texts: I'm currently working on my game, and we are planning on releasing a closed beta pretty soon. I would like to use Steam to make it, as it has a key generator to give people access, but I can't figure out or find out anywhere if you need to pay for the Steamworks partner, just to make a closed beta.


texts: Books that discuss practical rendering techniques?

texts: I'm looking for some books that discuss practical rendering topics like say rendering a bsp level or md2/3 mode, making a little quake like game as the goal or something to that effect. Any recommendations would be much appreciated.


texts: Loading texturecube using DirectXTK DDSTextureLoader

texts:
I've been trying to implement a skybox for some time now and there's probably only a tiny problem left to solve. When I load a texture using DirectXTK's CreateDDSTextureFromFileEx with a TEXTURECUBE flag, the resulting shader resource has its view dimension set to Texture2D and not TextureCube, which means I can't treat it as a TextureCube in HLSL. Also the file I'm loading contains all six faces. Here's the code where the texture is loaded:

// Loading the texture
HRESULT hr = DirectX::CreateDDSTextureFromFileEx(device, filename, 0, D3D11_USAGE_IMMUTABLE, D3D11_BIND_SHADER_RESOURCE,
    0, D3D11_RESOURCE_MISC_TEXTURECUBE, false, &texture, &mSkyboxSRV);

This is the error message being output by DirectX:

D3D11 ERROR: ID3D11DeviceContext::Draw: The Shader Resource View dimension declared in the shader code (TEXTURECUBE) does not match the view type bound to slot 0 of the Pixel Shader unit (TEXTURE2D).  This mismatch is invalid if the shader actually uses the view (e.g. it is not skipped due to shader code branching). [ EXECUTION ERROR #354: DEVICE_DRAW_VIEW_DIMENSION_MISMATCH]

I've also tried this:

ID3D11Texture2D* texture = nullptr;

HRESULT hr = DirectX::CreateDDSTextureFromFileEx(device, filename, 0, D3D11_USAGE_IMMUTABLE, D3D11_BIND_SHADER_RESOURCE,
0, D3D11_RESOURCE_MISC_TEXTURECUBE, false, (ID3D11Resource**)&texture, nullptr);

D3D11_TEXTURE2D_DESC texDesc;
texture->GetDesc(&texDesc);

D3D11_SHADER_RESOURCE_VIEW_DESC srvDesc;

srvDesc.TextureCube.MipLevels = texDesc.MipLevels;
srvDesc.TextureCube.MostDetailedMip = 0;
srvDesc.Format = texDesc.Format;
srvDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURECUBE;

hr = device->CreateShaderResourceView(texture, &srvDesc, &mSkyboxSRV);

But that gives me an error message saying the texture's view dimension and the srv's view dimension are not the same:

D3D11 ERROR: ID3D11Device::CreateShaderResourceView: Resources created without D3D11_RESOURCE_MISC_TEXTURECUBE may not be treated as cubemap ShaderResourceViews. [ STATE_CREATION ERROR #126: CREATESHADERRESOURCEVIEW_INVALIDDESC]

Does anyone have any ideas on what to do? Any help is much appreciated!


texts: So I am using eclipse to make mods for Minecraft. I recently took a break and was doing other things. My problem is when I came back to it, all my work was gone. There is nothing in the file explorer. The only changes I made to my computer between now and the last time I used eclipse is that I cleaned up my desktop (I moved a few related files into other folders) and that I installed a program called MCreator (to help with a class I'm teaching, and it may have messed with some of the related files). Does anyone have any idea what would have caused it and/or how to fix this?


texts:
So far I've always used a time granularity of 1 msec (that's it, 1 millisecond is the atomic time unit).

I'm wondering if this is always fine, or if for some cases (some specific games, game components or platforms) it would be suggested to have a more accurate time unit (on the order of microseconds or, I don't know, hundreds of microseconds).


texts: How do I modify a Boids algorithm to be player controlled?

texts:
Found source code on Boids in C#.

http://3carrotsonastick.wordpress.com/2012/11/01/boids-in-c-xna/

How do I go about making the raven class in the above player controlled?
If I could control it myself, it would be a great help, but I don't know how to go about it.


texts: Math.Clamp won't limit my position until movement is ceased

texts:
The program is in a top down view, with Y going up (or forward depending upon how you see it), and X going from left to right based on the camera view. I am attempting to set the minimum and maximum values of my main character's x/y-axis movement through the float "clamp", under the struct "Mathf".

When my ship passes the minimum/maximum value on either axis, it doesn't stop it. If you release the movement key after passing the point, the character will appear directly on the minimum/maximum point that was passed. See the gif below.

Gif here http://gph.is/22fdHv4

Below is the current script running for both player movement and the boundary, attached to the main character.

using UnityEngine;
using System.Collections;

public class ShipMovement : MonoBehaviour {

public float xMin;
public float xMax;
public float yMin;
public float yMax;
public float speed = 2f;
public float shotSpeed = 4f;
public float nextFire1;
public float nextFire2;
//Animator anim;
public GameObject shot;
public Transform shotSpawn;
public float fireRate = 0.25f;

void Start () {

//anim = GetComponent<Animator> ();
}

void FixedUpdate () {

        GetComponent<Rigidbody> ().position = new Vector3 (
            Mathf.Clamp (transform.position.x, xMin, xMax ),
            Mathf.Clamp (transform.position.y, yMin, yMax),
            0.0f
        );

        if (Input.GetKey (KeyCode.W)) {
        transform.Translate (Vector2.up * speed * Time.deltaTime);
        //anim.SetBool ("moving", true);
    }
        if (Input.GetKey (KeyCode.S)) {
        transform.Translate (Vector2.down * speed * Time.deltaTime);
        //anim.SetBool ("moving", true);
    }
        if (Input.GetKey (KeyCode.A)) {
        transform.Translate (Vector2.left * speed * Time.deltaTime);
        //anim.SetBool ("moving", true);
    }
        if (Input.GetKey (KeyCode.D)) {
        transform.Translate (Vector2.right * speed * Time.deltaTime);
        //anim.SetBool ("moving", true);
    } else {
        //anim.SetBool ("moving", false);
    }

    if (Input.GetKey (KeyCode.Space) && Time.time > nextFire1)
    {
        nextFire1 = Time.time + fireRate;
        Instantiate(shot, shotSpawn.position, shotSpawn.rotation);
    }

    if (Input.GetKey (KeyCode.X) && Time.time > nextFire2) {
        nextFire2 = Time.time + fireRate;
        Instantiate (shot, shotSpawn.position, shotSpawn.rotation);
    }

    if (gameObject == null) {
        Application.Quit ();
      }
   }
}

Although I am not sure, I suspect it may have something to with the way I am controlling the movement. I have had issues with what I have written in the past, especially with animations and moving left/right while also moving up/down. (Hence why I have all of the animation code commented out, and I am using a Capsule instead of a ship).

If anything else is needed, I can provide it.


texts:
Here's a quick image:

I've generated a navmesh for my game that shows how an AI can get to each of its possible neighboring tiles in a map. (I followed some gamasutra article as reference, I'll paste a link if I can find it again). You can see that it calculates all possible jump, fall, and walking connections between points.

Now that I have this, I've been researching how to actually use it. I understand that A* is generally the algorithm that people use but I haven't been able to find a resource for adapting it to a non-grid based dataset. Any articles that you know of or pseudocode would be awesome :)


texts: Why value 1 in OrthographicCamera viewPort width?

texts: So, I read that camera = new OrthographicCamera(1, h/w); creates a camera  with an appropriate width and height for the field view.. However, I can't understand that value 1 for the viewport width, does a value 1 means full width?


texts:
I'm using scene2d for the first time, and I can't get anything to draw EXCEPT the stage ui. Say I have my ui on top of my game screen:

uiStage.act():
batch.begin();
gameSprite.draw(batch); //does not show up
uiStage.draw();
batch.end();

How can I render my game, and then render my gui stage on top? Should I use a stage for both the game and the ui?


texts: Anti-Cheat for MMOs issues and solutions?

texts:
Most online games suffer for this problem and there are some software companies out there to cover this but recently from what I've seen most companies are trying to avoid those programs creating their own system (blizzard with warden, aion with their own checking, etc...) but it is a very difficult case to prevent such ...

Just wanted to say i made another question topic as community wiki specific for posting applications and it is features and the ideas behind this question here is not to list those but instead to know more about what were your attempts, issues along the road and possible solutions, piece of codes if application and so forth.

What sort of protection do you guys use in order to (try to) prevent such acts:

Anti-cheat Software ? (please state which, why and possible problems you faced, for example aion stopped using GameGuard at beta stage due to a huge amount of compatibility problems and complains from their users)
Your own code ? (what sort of verification do you usually run to make sure of the bad-faith players, for example speedhack, verify new location against speed+last location, etc...)
None, i dont care ? (any personal reason or input you did like to share ?)

Any interesting piece of code related to the issue you would like to post ?

Feel free to rework my text my english inst that great  ?**


texts:
I'm developing 2.5D game (3D assets, 2D gameplay). Since gameplay takes place on horizontal plane, majority of game objects have y component equal to 0. Most of my algorithms work on Vector2s, since these calculations obviously make more sense (and are a little bit faster, I guess). This makes field for hard to catch bugs, since Unity allows transparent conversion from Vector3 to Vector2 via cutting off z component.

Since I'm still in a stage in which I can change calculations quite easily, my question is: which approach will cause me the least trouble?

Current: Gameplay on XZ plane, custom conversion from Vector3.XZ to Vector2.XY
Gameplay on XZ plane, calculations on Vector3.XZ (and making sure, that y is always 0 - otherwise some of calculations may be erroneous)
Gameplay on XY plane (that may cause some problems in editor I guess) and automated conversion from Vector3.XZ to Vector3.XY
Gameplay on XY plane, calculations on Vector3.XY (though I see no benefit over solution 2)

Or is there some other approach I may take?


texts:
I wonder if it's possibel to add a value to X and Y in a Vector2? I have this code that creates a missile that use the position from the spaceship as a start position. But I would like to add some pixels so that the missile starts a little bit away from the spaceship. can I do that?

objectManager.AddNewMissileToList(new Missile(textureMissile, spaceship.spaceshipPosition, spaceship.spaceshipDirection));


texts:
I'm not sure if I understand callback functions completely - they are functions that another function calls? This seems like a powerful tool, especially w/r/t handling input.
I've written up this quick and dirty example using callbacks(or at least my understanding of them), but I feel as though I am doing too much.

1st, I would gather input from the OS.

2nd, I would pass that input into some sort of Context to handle input.

3rd, I would use the current active Contexts to shoot off these callback functions, based off of the input.

Something like this,

//Gathers keyboard input
struct InputData {

    std::map<SDLKey, bool> held_keys;
    std::map<SDLKey, bool> pressed_keys;
    std::map<SDLKey, bool> released_keys;
};

//Takes a shared_ptr in the constructor so it always knows what the current InputData is

class Context {

public:
    //Constructors/Destructors
    ...

    //Maps a function to a SDLKey
    void set_held_key_to_function(SDLKey key, std::function func)
    {
        held_key_action[key] = func;
    }

    void set_pressed_key_to_function(SDLKey key, std::function func)
    {
        pressed_key_action[key] = func;
    }

    void set_released_key_to_function(SDLKey key, std::function func)
    {
        released_key_action[key] = func;
    }

    //Fires off actions of pressed keys
    void PressKey(SDLKey key)
    {
        if(input_->pressed_keys[key] == true) {
            pressed_key_action[key]();
        }
    }

    //Fires off actions of held keys
    void HeldKey(SDLKey key)
    {
        if(input_->held_keys[key] == true) {
            held_key_action[key]();
        }
    }

    //Fires off actions of released keys
    void ReleasedKey(SDLKey key)
    {
        if(input_->released_keys[key] == true) {
            released_key_action[key]();
        }
    }

private:
    std::shared_ptr<InputData> input_;

    std::map<SDLKey, std::function> held_key_action;
    std::map<SDLKey, std::function> pressed_key_action;
    std::map<SDLKey, std::function> released_key_action;
};

Is this a viable way to handle user input, especially considering that the input in a Pause Menu would be vastly different than the input in the actual Gameplay part? Or am I vastly over-complicating the entire process of handling input? Am I even understanding callbacks correctly?


texts: Collision problem with multiple tiles (rectangles)

texts:
I think that I found what the problem is, see below

So I'm working on a collision system and I use multiple tiles in my project, each with a collision box. The player also has a collision box.

I'm testing this collision method so it's not done yet (very basic). I had another collision method in the past but it only worked for one tile and used a lot of booleans so I decided to make a new method.

This is my collision method in my SpriteManager class:

public void Collision(List<PlayerMovement> playerCollision, List<TileSprite> tileCollision)
{
    // For each sprite in the tileCollision list
    foreach (TileSprite t in tileCollision)
    {
        // For each player (head, body, legs) in the playerCollision list
        foreach (PlayerMovement p in playerCollision)
        {
            if (p.collisionRect.Intersects(t.bCollisionRect))
            {
                // Collision methods
                player.CollisionPlayer(p, t);

                // TileBase collision method not used in this test version
                tileBase.CollisionBlock(t);
            }

            if (!(tileBase.bCollision.Any(c => player.collisionRect.Intersects(c))))
            {
                p.ground = false;
            }
        }
    }
}

I basically need to place the player outside the collision block of the tile (now with testing version only above the tile), but when there are multiple tiles next to each other, then the overlapping rectangle changes because it's a simple variable (see below).

This is my collision method in my PlayerMovement class:

public override void CollisionPlayer(PlayerMovement p, TileSprite t)
{
    rect2 = Rectangle.Intersect(p.collisionRect, t.bCollisionRect);
    p.position.Y = p.position.Y - rect2.Height;
    p.jumping = false;
    p.ground = true;
}

You can see that it's really simple (for now). I make a new rectangle that consists of the intersection of the tile rectangle and the player rectangle and then I subtract the rect2 (new rectangle) height from the player position.

This works fine when the player collides with one tile, but he rapidly jumps up and down one pixel (position - lag, not performance) when he collides with more rectangles at the same time. I think this is because the collision method makes a new rect2 and overwrites the old one because the rect2 is only an overlapping of 2 rectangles. But I do not know how to fix this.

Images:

(NOTE: These images are the lagging behavior of the player when he collides with two tiles at the same time. The right image is how it should be. (it is like this with one tile))

PROBLEM: I think the problem is that only ONE overlapping rectangle is being made because the collision saves the overlapping rectangles all in the same variable (not in a list or an array, so it is overwritten). The problem I have now is that I don't know how to expand the overlapping rectangle to two or more tiles OR how to make multiple overlapping rectangles for this collision method.


texts: How to translate from Slick2d coordinates to jBox2d

texts:
I read through this question to try and get a grasp on the topic, but I can't figure out how to apply this to my Slick2d window.

I'm trying to do something as simple as place an edge on the bottom of the screen, so I had been thinking of something like

bottomEdge.setAsEdge(new Vec2(0f, SCREEN_HEIGHT), new Vec2(SCREEN_WIDTH, SCREEN_HEIGHT))

...but I have no idea how move from my pixel system to the MKS system of jBox2d. In fact, the body.getPosition().x of a movable body I am drawing returns a decimal value between 100 and 101, but I have no idea how it's deciding on this value. As I move off screen to the left, it decreases down to 99, 98, and so on.

How should I go about making this conversion and thereby also being able to support different screen sizes & resolutions? My instinct is to somehow use the LWJGL underneath Slick, but I'm lost.


texts: When should a bullet texture be loaded in XNA?

texts:
I'm making a SpaceWar!-esque game using XNA. I want to limit my ships to 5 active bullets at any time. I have a Bullet DrawableGameComponent and a Ship DrawableGameComponent. My Ship has an array of 5 Bullet.

What is the best way to manage the Bullet textures? Specifically, when should I be calling LoadTexture? Right now, my solution is to populate the Bullet array in the Ship's constructor, with LoadTexture being called in the Bullet constructor. The Bullet objects will be disabled/not visible except when they are active. Does the texture really need to be loaded once for each individual instance of the bullet object? This seems like a very processor-intensive operation.

Note: This is a small-scale project, so I'm OK with not implementing a huge texture-management framework since there won't be more than half a dozen or so in the entire game. I'd still like to hear about scalable solutions for future applications, though.


texts: Stop 2D platformer character from sliding down slope

texts:
I'm making a 2D platformer game with the default Unity 2D physics. I am implementing slopes, but my player slips down the slope because of the physics.

Here is the code I use for the player movement:
MoveInput = Input.GetAxisRaw("Horizontal");
rbd2.velocity = new Vector2(MoveInput * speed, rbd2.velocity.y);
//rotacion de personaje
if (MoveInput > 0)
{
    transform.localScale = new Vector3(1f, transform.localScale.y, transform.localScale.z);

}
if (MoveInput < 0)
{
    transform.localScale = new Vector3(-1f, transform.localScale.y, transform.localScale.z);

}


texts: What would cause my script generated buttons and text to show in Unity and not on my phone?

texts:
I am using Unity 5 and the built in GUI tools.  My static GUI shows up just fine which makes me think it's not a text/font issue or some such. Again, it all looks good in the Unity editor when I hit Play.

I have tried the different canvas options as far as what space to work in and how to scale. I have messed with the build options.  I have tried turning batching off. I have tried building for Android 4 through 5. (Ice Cream, Jelly Bean, etc) I have tried turning dynamic text on and off.  I have ensured the Buttons and text are made to be children of the canvas. I have only uploaded the game onto my Galaxy Note 4. I moved my background texture out of screen space in case it somehow covered the buttons on Android.

https://www.youtube.com/watch?v=Hk1UjXwOR08


texts: What algorithms can I use for bullet movement toward the enemy?

texts:
I'm developing 2D strategy game. There are weapons that shoot at enemies.
From what I've read in this, this, this and this post I think that I need linear algebra, but I don't really understand what algorithm I should use so the bullet will go to the target? Do I need a pathfinder, why?

Can you please suggest what algorithms and/or books I can use for bullet movement toward the enemy?


texts: Start C# script when imagetarget is detected for Vuforia+Unity

texts:
I have a script like given below which implements spirral motion of a sphere to the center (0,0,0). I want the script to start only when the image target is detected, however in my project it starts just when I open the app.  I know that the DefaultTrackableEventHandler needs to be modified, however, I am doing this for first time and I do not know how to implement this script in the eventhandler script. Where should I attach the event handler script etc...

The hierarchy and the script for spiraling motion is as given below

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

    public class spiralanti : MonoBehaviour
    {
        float angles;
        float radiuss;
        float angleSpeed;
        float rSpeed;
        // Start is called before the first frame update
        void Start()
        {
            angles = 0;
            radiuss = 1f;
            angleSpeed = 250f;
            rSpeed = 0.05f;
            angles = Mathf.Max(0, Mathf.PI);
            radiuss = Mathf.Max(0, radiuss);

            //float x = 0;
            // float y = 0;
            // float z = 0;
        }

        // Update is called once per frame
        void Update()
        {
            angles += Time.deltaTime * angleSpeed;
            radiuss -= Time.deltaTime * rSpeed;
            if (radiuss <= 0)
            {
                float x = 0;
                float y = 1;
                float z = 0;

                transform.localPosition = new Vector3(x, y, z);
            }

            else
            {
                float x = radiuss * Mathf.Cos(Mathf.Deg2Rad * angles);
                float z = radiuss * Mathf.Sin(Mathf.Deg2Rad * angles);
                float y = 1;

                transform.localPosition = new Vector3(x, y, z);
            }

            }

 }

Please Help !


texts: Where can I access the installed Maya Bonus Tools?

texts:
I installed Maya 2013 Bonus Tools... checked plugin manager... don't know what plugin to load to use UV Align feature.

Where can I access the installed Bonus Tools?


texts: Why is a baked normal map more efficient to render than additional physical detail?

texts: I was just contemplating about why I improve performance by baking additional details into the object rather than just rendering the more detailed model. How does the GPU get to take a shortcut to render potentially the same amount of detail on screen, just because the detail is represented in a different way?


texts: Godot :How does the VisibilityEnabler work?

texts:
Visibility Enabler

I'm confused about the use of the Visibility enabler node in godot. I've read the documentation and tried it out both stand-alone and as a child without success.

I set the parent to print a String during its _process function. Despite adding the enabler it continued to print despite being off screen.

How do I set it up so that It actually disables anything?


texts:
I am trying to create camera behavior where camera moving slightly forward the player along his movement direction to extend the visible area.

For camera movement, I use an empty object which moves as the player object by Input.GetAxis() and clamps in some borders around the player for the later to stay in camera area.

But I don't want to simply snap camera to the target object. I want the camera to smoothly lerp forward in player's movement direction and if there is no movement anymore - smoothly lerp back to the player object.

Problem is - I can't detect presence or absence of movement of the empty target object. I thought of using this method https://answers.unity.com/questions/907078/how-to-detect-movement.html  if(Mathf.Abs(rigidbody2D.velocity.y) < 0.001)

It didn't work at first because I moved my target point with transform.Translate(). When I tried rigidbody2D.Addforce() and it didn't work neither. I noticed that applied force actualy isn't reducing per time it stays the same. Then I tried rigidbody2D.MovePosition() and it also isn't working also velocity on every axis stays 0 and clamp isn't working with this method. Here is the code:

public class TargetPointBehaviour : MonoBehaviour{

[Tooltip("Used as origin point for camera movement.")]
[SerializeField]
private GameObject playerObject; //Used as origin point for camera movement

private Transform playerTransform; //players transform
private Vector2 playerPosition; // x, y player position

private Rigidbody2D targetPointRB2D; //rigidbody2D of target point object

//========================================================================================================

[Tooltip("Value to offset the camera from the player")]
[SerializeField]
private float offsetFromThePlayer; //value to determine how far target to interpolation will be

void Start()
{
    playerTransform = playerObject.GetComponent<Transform>();
    targetPointRB2D = GetComponent<Rigidbody2D>(); // assigning RigidBody2D component to variable
}

void FixedUpdate()
{
    MoveTargetPoint();
    ClampMovement();
    MoveTargetPointToPlayerPosition();
}

private void MoveTargetPoint() // moves targetPoint object by player controls
{
    GetComponent<Rigidbody2D>().MovePosition((new Vector2(Input.GetAxis("Horizontal") * 100,
        Input.GetAxis("Vertical") * 100))); // moves object by player controls
}

private void ClampMovement() //moves target point in defined borders GetComponent<Rigidbody2D>().AddForce
{
    transform.position = new Vector2(Mathf.Clamp(transform.position.x, playerTransform.position.x - offsetFromThePlayer, playerTransform.position.x + offsetFromThePlayer),
    Mathf.Clamp(transform.position.y, playerTransform.position.y - offsetFromThePlayer,
    playerTransform.position.y + offsetFromThePlayer)); //constraints movement by offsetFromThePlayer value

}

//checks if movement of targetPoint stops and when returns it to player object coordinates
private void MoveTargetPointToPlayerPosition()
{
    Debug.Log("Velocity Y: " + targetPointRB2D.velocity.y + ". Velocity X: " + targetPointRB2D.velocity.x);

    if (Mathf.Abs(targetPointRB2D.velocity.y) < 0.01f && Mathf.Abs(targetPointRB2D.velocity.x) < 0.01f)
    {
        StartCoroutine(DelayBeforereturningToPlayerObject());
        transform.Translate(playerTransform.position.x, playerTransform.position.y, 0);
    }
}

private IEnumerator DelayBeforereturningToPlayerObject() //delay for some time befor target returns to player object
{
    yield return new WaitForSeconds(0.1f);
}}

I didn't implemented actual camera movement yet cause don't see the point while the target for the camera isn't working. But maybe there is a more efficient way to implement what I want?


texts: How to deal with inconsistent network delay caused by packets arriving at different times in the frame?

texts:
I'm developing a multiplayer game that does not have prediction. It implements client-side interpolation. The problem with this is that input delay can be perceived. I've measured the various times involved in calculating the delay(packet arrival time, server respond time, time spent interpolating), and it seems about 50ms is spent on interpolating(correct), and 60ms is spent on ping and what I can only assume to be unfortunate message arrival time.

The ping is 18ms, which leaves 42ms. If the message arrives at the server immediately after the server has finished reading it's incoming messages this frame, we suffer at least a 16ms delay(at 60fps) that wouldn't be there if the message arrived right before the reading. If this happens with both the server and the client, the delay really adds up, especially at lower frame rates.

How can posts like this http://pastebin.com/ekk07PKn claim to have exactly 50ms  delay with 0 ping if this is an issue?

If it's relevant, this is being developed with Unity3d and the Lidgren networking library in C#. I've moved the server snapshot writing to a different thread with a lock around the game world update method. This helped a lot, but from what I understand moving the reading to a different thread won't help in the same way, because the client won't be able to use the new information until the next frame anyway.


texts: Is it possible to design a multiplayer game which can be played from different devices?

texts:
I want to design a online multiplayer game for all gaming devices e.g. Desktop PC, Internet browser, Android phones, Android tablets, iPhone, iPad, XBOX 360 etc. Now my main requirement is that, I want all devices can be used to play the game in multiplayer mode together i.e. One player can be connected using PC another using Android phone and other may be with iPhone or iPad.

My doubts are:

How to make all devices to connect to common game server?
What will be the logic for graphics and texture because all devices screen will be of different aspect ratio?


texts: Is the series of books "GPU Gems" still good for a modern OpenGL 3.0+ approach?

texts: I noticed that this series of free books from Nvidia is really popular and well know in the devs world, the problem is that is simply old; you would recommend to read those 3 books to a developer that wants to improve his skills with a programmable pipeline and is starting to do so in the 2012 ?


texts:
This is related to rendering creating a model, view, projection matrix for opengl. While matrix are fairly standard there's a lot of talk about using quaternions for rotations but why would u go from quaternions to matrix and back to matrix?

Quaternions might be faster but if you have to switch to matrix and back again doesn't that overhead eat into using just matrix only?

Is the typical workflow for using quaternions with matrix is to let the quaternion handle the rotation then create a 4x4 matrix from that rotation to concat with translation/ scale matrix in the model->view->projection matrix stack?

Does converting quaternion to matrix cause a lot of overhead?


texts:
I was originally thinking of creating a game with Python and SFML. I understand Python is slow compared to C++, but how is it compared to Game Maker?

The main reason I ask is I recently played a Game Maker game (The Iconoclasts) which ran at a fairly bad frame-rate on my computer (GMA 950). I'm worried I would have similar performance issues with Python/SFML.


texts: Spawning random objects at random positions in the 3D world

texts:
My main character can move horizontally and not vertically. It can move from x = -4 to 4 and z = -4 to 4 (a square area). I don't want objects to spawn where my character can move but every where else.
I wrote the following script. According to me it should have worked perfectly fine. But, I can't figure out why the objects are still spawning in the perimeter where the main character is present.

public class SpawnGameObjects : MonoBehaviour
{
    public float secondsBetweenSpawning = 0.1f;
    public float xMinRange = -25.0f;
    public float xMaxRange = 25.0f;
    public float yMinRange = -5.0f;
    public float yMaxRange = 0.0f;
    public float zMinRange = -25.0f;
    public float zMaxRange = 25.0f;
    public GameObject[] spawnObjects; // what prefabs to spawn

    private float nextSpawnTime;

    void Start ()
    {
        // determine when to spawn the next object
        nextSpawnTime = Time.time+secondsBetweenSpawning;
    }

    void Update ()
    {
        // exit if there is a game manager and the game is over
        if (GameManager.gm) {
            if (GameManager.gm.gameIsOver)
                return;
        }

        // if time to spawn a new game object
        if (Time.time  >= nextSpawnTime) {
            // Spawn the game object through function below
            MakeThingToSpawn ();

            // determine the next time to spawn the object
            nextSpawnTime = Time.time+secondsBetweenSpawning;
        }
    }

    void MakeThingToSpawn ()
    {
        Vector3 spawnPosition;

        // get a random position between the specified ranges
        spawnPosition.x = Random.Range (xMinRange, xMaxRange);
        spawnPosition.y = Random.Range (yMinRange, yMaxRange);
        spawnPosition.z = Random.Range (zMinRange, zMaxRange);
        if ((spawnPosition.z < 4 && spawnPosition.z > -4) || (spawnPosition.x < 4 && spawnPosition.x > -4))
        {
            MakeThingToSpawn ();
        }

        // determine which object to spawn
        int objectToSpawn = Random.Range (0, spawnObjects.Length);

        // actually spawn the game object
        GameObject spawnedObject = Instantiate (spawnObjects [objectToSpawn], spawnPosition, transform.rotation) as GameObject;

        // make the parent the spawner so hierarchy doesn't get super messy
        spawnedObject.transform.parent = gameObject.transform;
    }
}


texts: Defining a random irregular shape in a bool array

texts:
I need to find out how to populate an array bool[x,y] with a random filled shape.

lets say I want a triangle depicted in my array i would define an area within the array and set all points to "true" that exist within the defined by 3 key points.

Now lets say my array is ... bool[100, 100] I want to define a shape with N(random) number of sides.

Plot N number of points within the array and set their values to true
set all points that represent a line between the current point and the next point to true
fill the shape by setting all inside points to true

Any ideas?
I'm using C# and if it helps anyone Unity too. This is part of a much bigger problem so it doesn't sound like much but it will hugely help.

Thanks guys.


texts:
I am trying to translate world coordinates to screen coordiantes, and I am using the following line:
Vector3 Vec = cam.WorldToScreenPoint(Input.mousePosition);

for some reason the value of Vec is (0,0,0). Why is that?


texts: How to implement "bullet time" in a multiplayer game?

texts:
I have never seen such a feature before, but it should provide an interesting gameplay opportunity.
So yes, in a multiplayer/real-time environment (imagine FPS), how could I implement a slow motion/bullet time effect?
Something like an illusion for the player that's currently slo-mo'ed. So everybody sees him "real-time", but he sees everything slowed down.
Update
A sidenote: keep in mind that a FPS game has to be balanced in order for it to be fun. So yes, this bullet time feature has to be solid, giving a small advantage to the "player", while not taking away from other players.
Plus, there is a possibility that two players could activate their bullet time at the same time.
Furthermore:
I'm going to implement this in the future no matter what it takes. And, the idea is to build a whole new game engine for all this. If that gives new options, I'm more then interested in hearing the ideas.
Meanwhile, here with my team we're thinking about this too, when our theory will be crafted, I'm going to share it here.
Is this even possible? So, the question on "is this even possible" has been answered, now it's time to find the best solution.
I'm keeping the "answer" until something exceptionally good comes up, like a prototype theory with something close to working pseudo code.
What the physicists and philosophers say:
The links are for you interest, because topics are closed.
https://physics.stackexchange.com/questions/17118/time-traveling-and-time-dilation-within-a-multiplayer-videogame
https://philosophy.stackexchange.com/questions/1704/seeing-everything-in-slow-motion-but-being-real-time
The conditions I thought about when writing the question on physics site (copied):

The player under the effects of slow motion has an advantage to make more precise actions (shooting, movement etc.), due to seeing everything in a much slower pace.
His actions should affect the other players in real-time.
The players looking upon our affected player, do not see any difference, except they can experience the actions he have done (like, player gets shot/affected dodges a rocket).
When the player comes out of this effect, he simply continues in the same pace as usual. (If this is not possible, then I guess he'll have to suffer until the time gets synced back)

References on bullet time (slow motion):
Sadly, most of implementations are single-player only
http://www.gamesradar.com/a-videogame-history-of-bullet-time/


texts: Can I make global illumination from directional lights only affect their assigned layers?

texts:
I have a large space station scene, where there are giant mirrors that are sources of reflected light, and to emulate this, I made directional lights attached to the mirrors with cookies to make them look like the reflections of the sun in the mirrors. I have a few of these mirrors, lighting different parts of the station, and to keep the directional lights in check, I divided up the station into layers, so certain mirrors shine light on only certain sections. This works all well and good for the actual lights, but when I pre-calculate the realtime GI, suddenly parts of the station are getting reflected light from "mirrors" that are nowhere near them!

In other words: How can I make the GI from directional lights respect the layer mask I set on their source lights?? I'd prefer not having the directional lights affect parts of my scene they shouldn't be affecting!

(And if anyone has any better ways of reflecting sunlight onto a large scene via massive mirrors, I'm open to that too.)


texts: Programming Test for a job in Game Dev - expected levels of documentation etc

texts:
If this is the wrong place to be asking this - please let me know and I'll happily ask it somewhere else!

I am completing a C++ Proficiency test for a "Junior Engine Programmer" role at a game studio in the UK. The test involves creating a pathfinding demo and rendering it to the screen. I won't go too into the details of the test, but the brief doesn't mention any documentation or unit testing etc.

I've been told by a lecturer I should definitely include both of those, despite not being asked, and by another that I should use my time more wisely to make a great implementation. What is the done thing here? The only thing close that the brief mentions is making clear where I've used other libraries.

Is there anything else I should consider submitting with the implementation as well? Thinking of technical specification such as class diagrams etc, or anything really.

Thanks!


texts: Unity : shader that uses mesh.uv to tile texture atlas and mesh.uv2 to tile light atlas

texts:
I'm using a texture atlas and a light atlas to tile a mesh. I have the texture atlas working fine. I can apply textures and create a sort of tile map on my coded mesh. At the moment I'm using the built-in Self-Illum Diffuse shader.

The problem with this shader (and all others I've tried) is that it uses the same UV map for both the texture and the illumination, the result is, ie, that all grass tiles appear with the same level of light.

What I would like to do is apply two different UV maps: UV to tile the textures, and UV2 to tile the lighting. This would allow me to tell Unity which tiles should be lit up and which should not. The end result I'm looking for is that I will be able to display cubes that are close to a light source texture bright, and those further away darker.

I've attached a very ugly drawing of what I hope to achieve (I've drawn a 2D map but I'm actually working with a 3D mesh, IE: a deformed plain, and the Light Atlas of course has a Alpha layer).

I've got the UV maps nailed down and applied to the mesh. What I'm looking for is a way to tell a shader to read the two UV maps separately.

I would expect what I'm doing to be quite common and am really surprised that Unity doesn't have this built-in somewhere.


texts:
I am wondering if there are any books on designing virtual economies.

I have encountered some books which have a few lines or paragraphs written about virtual economies, but they mainly highlight how difficult it is to design and control a virtual economy; they don't give any useful advice on how to design a virtual economy.


texts: What is balance needed between testing the game mechanic (play testing) and testing the code

texts: I do not work in the industry and I wondered very broadly what percentage is given over to play testing versus getting the bugs out.  Or does no-one really work it like this?


texts: Version Not Final, Does Not Represent Actual Game Footage?

texts:
Just curious about this.  Frequently, a lot of gameplay videos from big studios have small subtitled text at the lower part of the screen, reading something like:

Pre-Alpha Gameplay -- Footage not Final
Game Footage not Final
Pre-Alpha, Game here is not final

Is there some sort of reason they do this?  Is there some sort of legal ramification that they need to go through by adding this?   I have especially seen some gameplay vids whose titles are "Alpha x.x.x", yet still, in the video itself, it always something like "footage not final, game may change".


texts: Casting a directional line of which an object is coming from

texts:
I want to create a directional line ( curve / linear ) depending where the direction is coming from.

In some games, similar to Angry Birds, a dotted guideline is shown to provide where the gameObject is going.

I want to create something like that. But not from the starting point.
When i mean starting point, it simply means a dotted guideline from where the gameObject is released.

What i want is a dotted guideline from the end point. However, this end point is fixed.
How i imagine this is, i have a gameObject. When this gameObject is near to land around this end point, it will show the dotted guideline.

Am i asking too much ? Sorry if i am, a structural guideline of how to write this code would be great.

Thanks.

Edit

So this how i want it visual.
In Diagram ( A ) it shows a dotted line through the whole course of the path.

However what i want is shown in Diagram ( B ). It is split into two parts, a orange and red path. I only want the red path. But for a clear understand i included the red path. I only want the object to land or around that spot of Diagram ( B ).

What i dont want is from Diagram ( C ). Because it is not landing in the spot of Diagram ( B ). I dont want it to show anything. I only want the red dotted line from Diagram to appear when it is near or going to land in that spot of Diagram ( B ).

Thanks


texts:
I have create a enemy AI script. These enemies are animals in my game.
What I want is that the enemy can detect the edges of a platform.

using UnityEngine;
using System.Collections;

public class EnemyAI : MonoBehaviour {

    public float walkSpeed = 2.0f;      // Walkspeed
    public float wallLeft = 0.0f;       // Define wallLeft
    public float wallRight = 5.0f;      // Define wallRight

    float walkingDirection = 1.0f;
    Vector2 walkAmount;

    float originalY; // Original float value

    void Start () {
        this.originalY = this.transform.position.y;
    }

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

        walkAmount.x = walkingDirection * walkSpeed * Time.deltaTime;

        if (walkingDirection > 0.0f && transform.position.x >= wallRight) {
            walkingDirection = -1.0f;
            Flip();
        } else if (walkingDirection < 0.0f && transform.position.x <= wallLeft) {
            walkingDirection = 1.0f;
            Flip();
        }

        transform.Translate(walkAmount);
    }

}

First of I store the original Y value inside a variable, so the object will be positioned on the platform I chose. Then in update it will do the walk animation.

Problem

I am now searching for a solution, so that the gameObject of enemy can detect the edges of the platform and turn away from it.

Looking out for some suggestions!


texts: Where can I publish my Windows Indie game?

texts:
I've just finished an XNA game for the Windows Phone 7 and XBLIG.  At the moment, the game is a 'lite' version, so is free, but the next version will have a small price-tag.

I also did a Windows version.  Where's the best place to publish it?


texts:
I am attempting to implement a sort of, smooth camera that has angle offsets from the player as they turn, creating a cinematic effect as well as visual feedback for when the player turns.

Here is an example of the desired functionality.
(Starts at 1:06)
http://youtu.be/uJ6tD-k_RuA?t=1m6s

One idea I was thinking of (if even feasible) is to store a "desired quaternion" of orientation of where the camera wants to look (preferably the player's quaternion of orientation)  and a "current quaternion" of the cameras orientation and SLERP to the desired quaternion. Then possibly set a max angle between the two rotations to cap how large the angle offset could be.

What are the ways of doing that?


texts:
Various online sources talk in sufficient detail about gamma correction. By following them, I achieved a rendering pipeline that looks somewhat like this:

// Both are set to 2.2
uniform float gammaIn;
uniform float gammaOut;

void main()
{
    vec3 color = pow(texture(material.albedo, texCoord).rgb, vec3(gammaIn));
    // Do lighting and then HDR tone mapping here.
    //   color = ...
    FragColor = pow(color, vec3(1.0 / gammaOut));
}

That is the easy part.

Now, many games implement the gamma correction adjustment slider that is meant to accommodate for display differences in various monitors that players may have. This presents some questions that I couldn't find any definitive answer to:

Which value should the adjustment slider affect? I reckon it will be gammaOut because gammaIn deals with decoding of the sRGB picture and assuming that all textures are sRGB, this should always be the const 2.2. With this approach a lower gammaOut means darker picture.
What's the reasonable value range for the slider? Should it start at 1.0 or somewhere higher? Where should it end?
If I were to display the "barely visible / invisible" comparison combo picture to help the user with doing the adjustment correctly, what should be the color values for the "should be barely visible" dark picture and its background and ditto for the "should be invisible" bright picture and its background?


texts:
I have a world map of 14048x7134, the game starts with the zoom completely out and during the operation it zoom in and zoom out and pan in all directions, it can get really near the surface, at almost a 1:1 ratio between the screen and the map information. It is going to be draw in a 1024x768 screen.

Scale a 14048x7134 to fit 1024x768 in each frame it's way far from efficient, so I am wondering...
What strategies there are to solve this problem?
Is there any tool or library to help in this process?


texts: Why won't my block Spaces/Holders hold my blocks when I drag onto them in Unity?

texts:
In my game I am trying to have numbered blocks and math operators be able to be dragged down into their respectively color coded holders (white holders = Numbers, black holders = operations). The spawn in color coded blocks called spawners. If you drop a block you were dragging in a space that isn't a holder, then the block would immediately snap back to its respective spawner.

However, I am now encountering this issue where 99% of the time when I drop the block onto its respective holder, the block snaps back to its spawner instead of staying there.
Here's the minimum reproducible code for dragging the blocks:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;

[RequireComponent(typeof(Collider2D))]
public class DragDrop : MonoBehaviour, IDragHandler, IBeginDragHandler, IEndDragHandler
{
    [SerializeField] private SpriteRenderer _spriteRenderer;
    public SpriteRenderer _SpriteRenderer => this._spriteRenderer;
    [HideInInspector]public static bool isInSpace;
    [HideInInspector]public Vector3 initialPos;

    private void Start()
    {
        initialPos = transform.position;
        isInSpace = true;
    }

    public void OnDrag(PointerEventData eventData)
    {

        if (isInSpace == false)
        {
            Vector3 movement = new Vector3(
            x: (eventData.delta.x/3) * Time.deltaTime,
            y: (eventData.delta.y/3) * Time.deltaTime);

            this.transform.localPosition += movement;
        }
    }

    public void OnBeginDrag(PointerEventData eventData)
    {
        isInSpace = false;
    }

    public void OnEndDrag(PointerEventData eventData)
    {
        if (isInSpace == false)
        {
            transform.position = initialPos;
        }
    }

#if UNITY_EDITOR
    private void Reset()
    {
        this._spriteRenderer = this.GetComponent<SpriteRenderer>();
    }
#endif
}

And Here's the code for receiving the blocks:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;

public class RecieveBlock : MonoBehaviour, IDropHandler
{
    public void OnDrop(PointerEventData Block)
    {
        if (Block.pointerDrag != null && Block.pointerDrag.tag == gameObject.tag)
        {
            Block.pointerDrag.GetComponent<RectTransform>().anchoredPosition = GetComponent<RectTransform>().anchoredPosition;
            DragDrop.isInSpace = true;
        }
    }

}

I have no idea why it doesn't set off the isInSpace bool to be true and stay there.
Heirarchy Image For Number Blocks:

Heirarchy Image For Operation Blocks:

Heirarchy Image For Holder Blocks:

Thank you for reading.


texts: Get Skeletal Mesh Vertex Position in Niagara

texts:
I have a custom HLSL node in a simulation stage in Niagara. One of the input variables to this node is of type Skeletal Mesh and I want to get the position and normal of a given vertex on that skeletal mesh by the index of the vertex.
In other words, I want to do the equivalent of the GetSkinnedVertexDataWS node, but in HLSL. Is this possible?
I couldn't find any documentation on it. I tried this code
bool myBool;
float3 VertexPosition;
ParticleMesh.GetSkinnedVertexDataWS<Attribute="Position">(i, myBool, VertexPosition);
float3 VertexNormal;
ParticleMesh.GetSkinnedVertexDataWS<Attribute="Normal">(i, myBool, VertexNormal);

where 'i' is the index of the vertex I want (from a loop), but I get the error:

"'GetSkinnedVertexDataWS_SystemParticleMesh_AttributePosition': cannot convert output parameter from 'float3' to 'bool' SPH_Emitter, Particle GPU Compute Script".

I also tried a few variations to no avail.
How can I solve this?
Edit:
Picking through the USH files in "\UE_4.26\Engine\Plugins\FX\Niagara\Shaders\Private", and looking in "NiagaraDataInterfaceSkeletalMesh.ush" in particular, it would seem that the call should be GetSkinnedVertexWS not GetSkinnedVertexDataWS.
However, when I make this change the error I get now is

/Engine/Generated/NiagaraEmitterInstance.ush(1563,3-14):  Err0r X3004: undeclared identifier 'ParticleMesh' SPH_Emitter, Particle GPU Compute Script,

This makes no sense to me. ParticleMesh is most definitely declared - as I say, it's an input to the custom HLSL node.
I don't know what the error refers to when it mentions "NiagaraEmitterInstance.ush" either. There's a "NiagaraEmitterInstanceShader.usf" but no USH file.
This has been an entire weekend wasted with zero progress. It doesn't help that there's next to no documentation. Nor does it help that I have to click an arbitrary parameter on the emitter on and off to reveal the error in the Niagara Log for 0.2s, whack the print screen key and paste the screenshot into Photoshop just to examine the error log, every single time I make a change.


texts: Tilemap collision in component based entity system

texts:
I am trying to set up a collision system for a tilemap in my component based entity system, but having trouble with figuring out how to do so.

Currently I have the following approach:
My tilemap consists of a Tilemap_Component, which just holds the array, a Tilemap_Render_Component, which holds the Tileset image, and a Tilemap_Collision_Component, which holds the information which tile value is handled as a wall.

To make an entity collideable with the tilemap it needs currently the following components:
Movement_Component, which holds the X/Y Velocity, Position_Component, which holds X/Y Position and Tilemap_Collider_Component, which holds the information if the object only collides with walls or as well with some other objects in the tilemap.

Now my problem is the following:
It is very hard to determine what to do with an object which collides with the tilemap. If I set velocity to zero, it is possible to glitch through walls because Movement and Input are handled in other systems than the collisions.
If I just change the Position of the object, there occur two problems: One is, that the object starts to flicker because it has moved a bit. The other is, that I would have to know how big the object is which is colliding with the wall.
Now I could just say that a Render_Component is required for objects which can collide with the tilemap and then use the image information in the Render_Component of the object and the Tilemap_Render_Component of the tilemap to calculate collision, but I think this is a bit against the intention of component based system.

What would be your suggestions? How could I handle this problem?
Or, as well: Was anyone of you faced to such a problem? How did you solve it?


texts: Algorithm to verify if a shape is inside another

texts:
I have a rectangular canvas and I need to verify whether a shape is totally inside that canvas or not. The shape can be lines, ellipses, arcs, rectangles and arbitrary polygons.

Does anyone know a lib with this kind of algorithm, preferably in java?

I searched and found just Slick2D, but it has a bug exactly on the method that verify if shape contains another shape.

Just to exemplifly, in the figure only shapes 2, 4, 5, and 7 are inside the canvas.


texts: SpriteBatch.Draw() rectangle is different from destinationRectangle passed in

texts:
When I ask SpriteBatch to draw a rectangle as within the following method :

    public static void DrawSolidRectangle(Rectangle rectangle, Color color)
    {
        // the output from this is shown in the screenshot
        System.Console.WriteLine(rectangle.ToString());
        spriteBatch.Draw(pixel, rectangle, color);
    }

I am getting different sized rectangles to the rectangles I am providing. This is an issue I am having after resizing the window. As you can see in the screenshots, the difference in width of the two rectangles is only 2 pixels and there is an offset of 1 pixel, while the two gray rectangular draw results clearly have greater than a 3 pixel difference in width.

screen shot of issue http://users.tpg.com.au/gavinw77//SpriteBatchIssue.jpg

Does anyone know what's going on ? Is this a known issue with SpriteBatch or the BackBuffer after resizing or what ?


texts: Knockback enemy based off of direction sprite is facing

texts: Today I am trying to make it so if I hit the enemy then the enemy will be knocked backwards in the direction the sprite is facing. I am rotating the sprite around 360 degrees using a joystick on the screen and wanted to know the best practice or ways to accomplish this.  I have come up with a few ideas but none of them make use of the sprites angle he is facing just a check to see if I hit the bottom then move him upward and so forth. I am just stumped on how to apply the sprites angle to the enemies x and y coordinate and move him accordingly. Has anyone tried this and have suggestions or things to look for?


texts:
I'd like to implement a surface of revolution.

I already implemented creating Vertices based on a 2D line.
I now want to get the indices to render the mesh with GL_TRIANGLES

Here's the code to create the 3D Vertices out of a 2D line:

void createVertices(vector<Vector2>& points,unsigned int iterations)
{
    int i;
    int j;

    unsigned int index;

    vector<Vertex> newVertices;
    vector<unsigned int> newIndices;
    for(j = 0; j < points.size();++j)
    {
        for(i =0; i < iterations;++i)
        {
            Vector2 p = points.at(j);
            float theta = M_PI*2.0*(float)i/(float)iterations;
            float x = sinf(theta)*p.x;
            float z = cosf(theta)*p.x;
            newVertices.push_back(Vertex(x,p.y,z));
        }
    }
}

and here's the code that will be called to save the Vertices:

void addVertices(vector<Vertex>& vertices,vector<unsigned int>& indices)
{
    this->vertices = vertices;
    this->indices = indices;

    unsigned int verticesSize = vertices.size() * sizeof(Vertex);
    unsigned int indicesSize = indices.size() * sizeof(unsigned int);

    float* vertexBuffer = new float[vertices.size()*sizeof(Vertex)];

    createBuffers(vertices,vertexBuffer);

    glGenVertexArrays(1,&VAO);
    glBindVertexArray(VAO);

    glGenBuffers(1,&verticesVBO);
    glBindBuffer(GL_ARRAY_BUFFER,verticesVBO);
    glBufferData(GL_ARRAY_BUFFER,verticesSize,vertexBuffer,GL_STATIC_DRAW);

    glGenBuffers(1,&indicesVBO);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,indicesVBO);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER,indicesSize,&indices[0],GL_STATIC_DRAW);

    delete[] vertexBuffer;
}

someone has a basic idea?


texts:
I'm currently using LibGDX and Tiled map editor to render isometric maps. I'm having a two related difficulties.

The first issue is, when do I render units that will end up changing position often and to which layer? At first I thought that I would render units with a wall layer so that walls behind of and in front of the unit are drawn correctly. However, the problem with this is that if a unit (i.e. a character) steps in front of say an object in some sort of top-level decoration layer, part of that object will be drawn on top of the unit.

The second issue is how to deal with layers that have static objects that units will often be stepping in front of or behind. Let's say you have a decoration layer where you will place trees. The problem with this layer is that depending on where some objects are placed in the layer, they will overlap inconsistently. For example, the following:

I know this is related to painter's algorithm, but I'm using LibGDX's tile map renderer so the extent to which I have control over drawing the map is rendering different layers at a time and switching out cells/tiles in a layer.


texts:
I have created a text file called "useraccounts.txt". All I want to do is to read the file using the filehandle class but I always get this exception:

Exception in thread "LWJGL Application" com.badlogic.gdx.utils.GdxRuntimeException: Cannot open a stream to a directory: useraccounts.txt (Local)

Here is my code:

FileHande accountsFile = Gdx.files.local("useraccounts.txt");
String text = accountsFile.readString();

Any explanation is appreciated!


texts: Where in a typical rendering pipeline does visibility and shading occur?

texts:
I am taking a computer graphics course. The book and the lecture notes are vague on the on the order of flow between the different steps in the rendering process. For example, if we have specified a view in a scene, and then want to perform a projection transformation for that given view, then we have to go through a sequence of transformations. In the end we end  up with a normalized "viewcube" ready to be mapped 2D after clipping. But why do we end up with a cube (ie 3D thing), when a projection results in projecting the 3D objects to 2D. (depth information is lost?) The other line of reasoning is that all information further needed is stored within the "cube" and that visibility detection and shading is performed with respect to this cube and then we perform rasterezation.

edit: (More explicit question)
Is shading and visibility checks performed after projections/normalization and clipping.


texts: Count the number of Vulnerable and Invulnerable crops

texts:
I have this code that counts how many GameObjects (crops) in the scene

GameObject[] crops;

and the code to get the health component of each crops

    Health[] health;
    crops = GameObject.FindGameObjectsWithTag("Crop");
    health = new Health[crops.Length];
    for (int i = 0; i < crops.Length; i++)
    {
        health[i] = crops[i].GetComponent<Health>();
    }

I can now access the state of these crops using

    health[i].Invulnerable //this is a bool from the Health.cs script

now I want to count the crops that are Vulnerable and Invulnerable. How can I achieve that? Thanks!


texts:
I've been into javascript game programming with html5 and canvas lately. So far I've only been able to implement a game loop with setInterval, but I'm aware this means using fixed timestep. I've always used game engines with the "delta time" approach, I'm sorry I can't recall how that timestep was called. But anyway, I had several questions.

How could I implement a game loop with the delta time approach?
Will I get benefit from it in any particular way?

Also any information you point out related to that is welcome.


texts:
I have a multiplayer game done with Phaser, which runs in the browser and on a node.js server.

The server is authoritative, every 50ms or so it sends the game state object to all clients. The clients receive the state and update all instances accordingly. The game runs at 60fps, and the physics and AI are the same on clients on server, so if there is no user interaction the game will evolve exactly the same (the next frame on the server will be equal to the next one on the client). This should make sync much easier, but I have a problem:

When the client receives the state from the server, the state is no longer up to date (as there is the latency between server and client).

Here is a drawing:

Server: State1 -> State2 -> State3 -> State4 -> State5
................................................*-------------------V
Client : State1 -> State2 -> State3 -> State4 -> State5State3

So, when the client receives State3, it is no longer usable as it has already been at State3. This makes the game always rewind a few frames when it receives the update from the server. How can I solve this, taking in account that the same game engine runs on both client and server (so prediction is much easier).

I would try "rendering the game in the past" as I have seen in other cases, but I do not really think I can break Phaser physics/render loop connection.


texts: Implementing a lexicon for a word-based game with C# or C++

texts:
In my game project I have a lot of word existance checks based on some word bank. As usual arrays or map/set are not realy appropriate for this due to their speed/memory usage, I want to use Ternary Search Tree. After some googling I've realised that there's not so much info or code ready to use there. So I want to implement it myself.

Question is - can I write it in C++ and then export to Unity with cross-platform support? To be more precise: will I be able to use this cpp library on Android and iOS? Or maybe I should just write it in C# which, I believe, will be slightly less efficient?


texts:
I'm looking to create a fairly large environment, and as such would like to implement a quadtree and use LOD on it. I've looked through numerous examples and I get the basic idea of a quadtree. Start with a root node with 4 vertices covering the whole map and divide into 4 children nodes until I meet some criteria (max number of triangles)

I'm looking for some very very basic algorithm or explanation with respect to drawing the quadtree. What vertices need to be stored per iteration? When do I determine what vertices to draw? When to update indices and vertices? Hope to integrate the bounding frustum? Do I include parent and child vertices?

I'm looking for very simple instruction on what to do. I've scoured the internet for days now looking, but everyone adds extra code and a different spin without explanation.

I understand quadtrees, but not with respect to 3d rendering and lod. A link to an outside source will probably have been read by myself already and won't help.

Regards,
Byron.


texts: unity: how to make instantiated gameobject to have rectTransform of the canvas? (c#)

texts:
public GameObject canvas;  // the canvas

GameObject changerSign = Instantiate(changerPopup,
    new Vector3(235, 350, 0),
    this.transform.rotation);
changerSign.transform.SetParent(canvas.transform);

this will make a UI at the screen. while it does make the object as wanted, the rect transform won't get fixed(?) to the newly set parent(the Canvas), but instead to where it was first made. how could I get it under canvas's rect transform? could be some too basic question, but couldn't find any answer anywhere so far :(


texts: importing images as pixel-perfect from flash to Unity

texts:
I am not sure if this works, it just feels like it should. So I have this character in flash:

And what I want to do is import him into Unity, and making him pixel-art. (And yes, for those wondering; I am hugely inspired by Binding of Isaac at the moment.)

Is it possible to not get the "shady" pixels, and just pure colors?


texts: How do I stop my first person character going through walls?

texts:
As per my code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UIElements;
using Cursor = UnityEngine.Cursor;

public class FirstPersonController : MonoBehaviour
{
    public float speed = 5;
    public float jumpPower = 4;

    Rigidbody rb;
    CapsuleCollider col;

    private GameObject player;
    private float minClamp = -45;
    private float maxClamp = 45;
    [HideInInspector]
    public Vector2 rotation;
    private Vector2 currentLookRot;
    private Vector2 rotationV = new Vector2(0,0);
    public float lookSensitivity = 2;
    public float lookSmoothDamp = 0.1f;
    public Camera cam;
    public GameObject crossHair;
    bool isActive;

    // Start is called before the first frame update
    void Start()
    {
        Cursor.visible = false;
        Cursor.lockState = CursorLockMode.Locked;

        rb = GetComponent<Rigidbody>();
        col = GetComponent<CapsuleCollider>();
        player = transform.gameObject;
        crossHair = GameObject.FindWithTag("CrossHair");

    }

    // Update is called once per frame
        void Update()
    {
        float Horizontal = Input.GetAxis("Horizontal") * speed;
        float Vertical = Input.GetAxis("Vertical") * speed;
        Horizontal *= Time.fixedDeltaTime;
        Vertical *= Time.fixedDeltaTime;
        transform.Translate(Horizontal, 0, Vertical);

        if (isGrounded() && Input.GetButtonDown("Jump"))

        {
            rb.AddForce(Vector3.up * jumpPower, ForceMode.Impulse);
        }

        if (Input.GetKeyDown("escape"))
        {
            Cursor.lockState = CursorLockMode.None;
        }

        if (Input.GetButtonDown("Sprint"))
        {
            speed = 15;
            //Debug.Log("Sprint Button Held Down");
        }

        if (Input.GetButtonUp("Sprint"))
        {
            speed = 5;
            //Debug.Log("Sprint Button Let Go");
        }

        if (Input.GetKeyDown(KeyCode.H))
        {
            isActive = !isActive;
        }

        if (isActive)
        {
            crossHair.SetActive(true);
        }
        else
        {
            crossHair.SetActive(false);
        }

        rotation.y += Input.GetAxis("Mouse Y") * lookSensitivity;
        rotation.y = Mathf.Clamp(rotation.y, minClamp, maxClamp);
        player.transform.RotateAround(transform.position, Vector3.up, Input.GetAxis("Mouse X") * lookSensitivity);
        currentLookRot.y = Mathf.SmoothDamp(currentLookRot.y, rotation.y, ref rotationV.y, lookSmoothDamp);
        cam.transform.localEulerAngles = new Vector3(-currentLookRot.y, 0, 0);
    }

    private bool isGrounded()
    {
        return Physics.Raycast(transform.position, Vector3.down, col.bounds.extents.y + 0.1f);
    }

}

I can't figure out what I am doing wrong in my code, I tried to write a first person controller from scratch.

The full project can be downloaded from: https://github.com/Some-T/FirstPersonController-CSharp

My player goes through any wall or object easily despite it having colliders on the objects and a rigidbody and collider on the player.

I have gone through my code line by line and I cannot work out what is wrong? If someone could please advise me what to change or add to my code to fix this, or / and explain the concept, presumably physics related, as to why this is going wrong please?


texts: Make gameObject “stick” to another gameObject after it has collided with it?

texts:
Currently, I am using the following code to make objects stick to other gameObjects.

rb = GetComponent<Rigidbody>();
rb.isKinematic = true;
gameObject.transform.SetParent (col.gameObject.transform);

It works perfectly, but it causes many other problems... For example, after colliding, it can no longer detect collisions... Is there an alternative to this code (which makes a gameObject stick to another one after collision)?


texts: C++ text based football -- lookup table and AI logic help

texts:
I am trying to develop a one-player text based football game in C++ strictly in the console without graphics. I am developing the game logic here below vs the CPU and I also need to do the vice versa (CPU vs User). How could I do this without a ton of if statements. I am not sure how to accomplish this same code below as a lookup table and I know I need some randomness so it is not predictable.

For this example below, the scenario would be which down are we in (4th in this example), how many yards to go (2 yards), the offensive's team running attribute (choice = Bears), the defense run attribute (o_choice = Bengals) and the play called (playbook_choice = 1 which is QB Sneak). Any help would be much appreciated, I have been banging my head against on the wall on this. I have not incorporated the attributes ratings below into the code below because I am not sure how. The Bears would have offensive running and pass ratings, and defensive running and pass ratings (so 4 ratings in total), same goes for the Bengals.

    //test logic
if (playbook_choice == 1 && choice == 1 && o_choice == 2) { //if qb sneak is called by the user controlled bears vs the cpu bengals

    int current_down_yards = 0,down = 4 ,yards = 2; // current down is 4th and 2  --- setting the down and distance
    cout << "It is 4th down and 2 yards to go" << endl; // print it out to the user --- setting the down and distance

    if (down == 2 || down == 3 || down == 4 && yards < 3) { //if its 2nd , 3rd of 4th down  and less than 3 yards to go
        current_down_yards = rand() % 16; // give a rate of completion of randomness from 1-15 yards for a QB sneak --- need to take account for the strength
        // of the defense's attribute rating and offense's running rating -- to include for a loss as well as a gain in yardage
        cout << "The QB ran for " << current_down_yards << " " << "yards" << endl;
    }
}


texts: Loading PNG textures for use in Android OpenGL ES1

texts:
I'm very new to Android and OpenGL coding (I have previously used ogre3d).  I am trying to find an efficient way to load PNG textures.  It is currently taking around 8 secs to load 3 512x512 textures on a fairly fast phone (Motorola Defy)

There seems to be a problem with the texture being upside-down (I used a Matrix to flip it below).  Secondly, the order of the colour channels are incompatible, therefore each pixel needs changed.  This (I believe) is the cause of the slowness, is there a way to make the BitmapFactory load it in a channel order that is compatible with opengl?   Is there a better approach here?

Here is the code: -

// Will load a texture out of a drawable resource file, and return an OpenGL texture ID:
private int loadTexture(GL10 gl, Context context, int resource, boolean loadMipMaps) {
    // We need to flip the textures vertically:
    Matrix flip = new Matrix();
    flip.postScale(1f, -1f);

    // This will tell the BitmapFactory to not scale based on the device's pixel density:
    BitmapFactory.Options opts = new BitmapFactory.Options();
    opts.inScaled = false;

    // Load up, and flip the texture:
    Bitmap temp = BitmapFactory.decodeResource(context.getResources(), resource, opts);
    Bitmap bmp = Bitmap.createBitmap(temp, 0, 0, temp.getWidth(), temp.getHeight(), flip, true);
    temp.recycle();

    int id = loadTextureFromBmp(gl,bmp, true);

    bmp.recycle();

    return id;
}

protected static int loadTextureFromBmp(GL10 gl, Bitmap bmp, boolean reverseRGB) {
    ByteBuffer bb = ByteBuffer.allocateDirect(bmp.getHeight()*bmp.getWidth()*4);
    bb.order(ByteOrder.nativeOrder());
    IntBuffer ib = bb.asIntBuffer();

    for (int y=bmp.getHeight()-1;y>-1;y--)
            for (int x=0;x<bmp.getWidth();x++) {
                    if (reverseRGB) {
                            int px = bmp.getPixel(x,y);
                            int alpha = (px & 0xFF000000) >> 24;
                            int red = (px & 0xFF0000)>>16;
                            int green = (px & 0xFF00)>>8;
                            int blue = (px & 0xFF);
                            ib.put((alpha << 24) | (blue << 16) | (green<<8) | (red));
                            //ib.put(Integer.reverseBytes(bmp.getPixel(x, y)));
                    }
                    else {
                            ib.put(bmp.getPixel(x,y));
                    }
            }
    ib.position(0);
    bb.position(0);

    int[] tmp_tex = new int[1];

    gl.glGenTextures(1, tmp_tex, 0);
    int tex = tmp_tex[0];
    gl.glBindTexture(GL10.GL_TEXTURE_2D, tex);
    gl.glTexImage2D(GL10.GL_TEXTURE_2D, 0, GL10.GL_RGBA, bmp.getWidth(), bmp.getHeight(), 0, GL10.GL_RGBA, GL10.GL_UNSIGNED_BYTE, bb);
    gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_LINEAR);
    gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, GL10.GL_LINEAR);

    return tex;

}