texts: How to add multiple floors to a map in a text-based game?

texts:
I decided to learn how to make games during this quarantine. I am reading Mission Python, a book that teaches how to make games using python and pygame. I'm halfway through it, but the game only has one map.

I'm trying to challenge myself by adding a basement and an upstairs room, but the book doesn't have anything on making multiple floors.

Current code for my map:

###############
##    MAP    ##
###############

MAP_WIDTH = 5
MAP_HEIGHT = 10
MAP_SIZE = MAP_WIDTH * MAP_HEIGHT

GAME_MAP = [ ["Room 0 - where unused objects are kept", 0, 0, False, False] ]

outdoor_rooms = range(1, 26)
for planetsectors in range(1, 26): #rooms 1 to 25 are generated here
    GAME_MAP.append( ["The dusty planet surface", 13, 13, True, True] )

GAME_MAP  += [
        #["Room name", height, width, Top exit?, Right exit?]
        ["The airlock", 13, 5, True, False], # room 26
        ["The engineering lab", 13, 13, False, False], # room 27
        ["Poodle Mission Control", 9, 13, False, True], # room 28
        ["The viewing gallery", 9, 15, False, False], # room 29
        ["The crew's bathroom", 5, 5, False, False], # room 30
        ["The airlock entry bay", 7, 11, True, True], # room 31
        ["Left elbow room", 9, 7, True, False], # room 32
        ["Right elbow room", 7, 13, True, True], # room 33
        ["The science lab", 13, 13, False, True], # room 34
        ["The greenhouse", 13, 13, True, False], # room 35
        [PLAYER_NAME + "'s sleeping quarters", 9, 11, False, False], # room 36
        ["West corridor", 15, 5, True, True], # room 37
        ["The briefing room", 7, 13, False, True], # room 38
        ["The crew's community room", 11, 13, True, False], # room 39
        ["Main Mission Control", 14, 14, False, False], # room 40
        ["The sick bay", 12, 7, True, False], # room 41
        ["West corridor", 9, 7, True, False], # room 42
        ["Utilities control room", 9, 9, False, True], # room 43
        ["Systems engineering bay", 9, 11, False, False], # room 44
        ["Security portal to Mission Control", 7, 7, True, False], # room 45
        [FRIEND1_NAME + "'s sleeping quarters", 9, 11, True, True], # room 46
        [FRIEND2_NAME + "'s sleeping quarters", 9, 11, True, True], # room 47
        ["The pipeworks", 13, 11, True, False], # room 48
        ["The chief scientist's office", 9, 7, True, True], # room 49
        ["The robot workshop", 9, 11, True, False] # room 50
        ]

#simple sanity check on map above to check data entry
assert len(GAME_MAP)-1 == MAP_SIZE, "Map size and GAME_MAP don't match"


texts: What is the better way to speed up gameplay as the level rises?

texts:
I started with game programming couple of weeks back. For the starters I tried to develop ZigZag (link takes you to 2 min gameplay).

I am done with the logic of gameplay by now. It runs well and all. Now I want to speed up the gameplay as user passes some score. Say after 100 points increase the speed of the ball.

I have two options:

Control the speed using time-delay by varying time.delay(var).
Actually increasing the speed of the moving ball

Not sure which one is a good idea in long term, I'm looking for help from experienced game developers.

You can checkout the source code: https://github.com/ravi-ojha/zigway/blob/master/zigway.py


texts: Unity3d 5 - default assets RollerBall+MultipurposeCameraRig rotation/tilt problems

texts:
I started a new Unity3d 3D project. I imported the Player, Camera and Prototyping assets.

I placed a FloorPrototype64x01x64 and scaled it *2 on all axis. I reset it to 0,0,0 position and rotation.

I placed the RollerBall prefab and also reset it. I then set Y position to 0.5 to move it up on top of the floor.

I placed the MultipurposeCameraRig and its Transform values are all reset to begin with. I can see it has a child Pivot object with 2 in Y and -3 in Z (making it a point above and behind the Rigs transform). This looks good.

Since the camera has a script to target the object with the "Player" tag, it gets a hold on the RollerBall which has that tag.

When i start the player i can move the ball around with the arrow keys. The thing is, even though i go straight "up" the camera tilts a bit after less than a half rotation of the ball. The camera stays behind (on z axis) no matter what way i'm going. Once i play around with it, the camera get more wacky and if i stop pressing any keys and let the ball speed slowly decrease, then the camera goes nuts and start turning around all axis - bringing it on the side and below the floor.

I tried playing a round a bit with the camera both to fix this bug and to make the camera stay behind the ball (like a normal first/third person view/race-car view where you see the back of the character). I do the following:

On the auto cam script i enable Follow Velocity, and i disable Follow Tilt. On the cameras RidigBody i freeze X and Z rotation.

Now i get the camera to stay behind the ball like i want - i can keep the "up" key pressed and use the "left" and "right" to turn. This behaves like a normal Racing game.

But I still got the same weird behavior. When i start the game, the camera tilts slighty to the right and if i slow down the ball, the camera goes wonky. Since i froze the Z and X it stays level with the floor, but it twists and turns around the Y axis, making it impossible to navigate property. Once i get some speed on the ball again, the camera seems to behave again.

TL;DR
The MultipurposeCameraRig's rotation seem to not work at slow Player speeds, how can i fix this?


texts:
I am trying to come up with a smooth wandering motion for my game-object using Unity. What I currently doing is rotate the object by some random angle calculated every 1.5 second delay. But I am aiming getting a smooth rotation whenever it transitions to a different randomly generated angle.

Below is my script attached to my character.

 void Update () {
     if (canWander && (currTime + delay < Time.time)){
        changeAngle();
        currTime = Time.time;
     }
     if(canWander){
        Wander();
     }
}

private void changeAngle(){
    float prevPosY = transform.position.y;
    Vector3 waypoint = Random.insideUnitSphere + new Vector3(10,prevPosY,10);  //waypoints are generated based on random unit sphere + ( bounds of the plane they are on )
    Vector3 relative = transform.InverseTransformPoint (waypoint);
    float angle = Mathf.Atan2 (relative.x, relative.z) * Mathf.Rad2Deg;
    transform.Rotate (0, angle, 0);
}

private void Wander(){
    transform.position += transform.forward * Time.deltaTime * acceleration;
    if (acceleration < maxSpeed) {
        acceleration += 0.5f;
    }
}

So the character wanders with newly generated random angles every time but its not a smooth transition. It suddenly transitions to the new angle and it does not feel realistic at all. What could I possibly change with my current code to make it more smooth and realistic?


texts: How can i Zoom and Drag The Multiple Image in RelativeLayout

texts:
i try but it did not see the effect for the zoom and Rotate the image                 ..Here is my code....

ima1 = (ImageView) findViewById(R.id.image);
    ima1.setOnTouchListener(new View.OnTouchListener() {

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            // TODO Auto-generated method stub
            int x_cord = (int) event.getRawX();
            int y_cord = (int) event.getRawY();

            layoutParams1 = (RelativeLayout.LayoutParams) ima1
                    .getLayoutParams();
            switch (event.getActionMasked()) {
            case MotionEvent.ACTION_DOWN:
                savedMatrix.set(matrix);
                start.set(event.getX(), event.getY());
                mode = DRAG;
                lastEvent = null;
                break;

            case MotionEvent.ACTION_POINTER_DOWN:
                oldDist = spacing(event);
                if (oldDist > 10f) {
                    savedMatrix.set(matrix);
                    midPoint(mid, event);
                    mode = ZOOM;
                }
                lastEvent = new float[4];
                lastEvent[0] = event.getX(0);
                lastEvent[1] = event.getX(1);
                lastEvent[2] = event.getY(0);
                lastEvent[3] = event.getY(1);
                d = rotation(event);
                break;

            case MotionEvent.ACTION_POINTER_UP:
                mode = NONE;
                lastEvent = null;
                break;
            case MotionEvent.ACTION_MOVE:
                if (mode == ZOOM) {
                    float newDist = spacing(event);
                    if (newDist > 10f) {
                        matrix.set(savedMatrix);
                        float scale = (newDist / oldDist);
                        matrix.postScale(scale, scale, mid.x, mid.y);
                        layoutParams1.leftMargin = x_cord;
                        layoutParams1.topMargin = y_cord;
                        ima1.setLayoutParams(layoutParams1);
                        System.out.println("=== Mode Zoom = " + mode + " == " + scale ) ;
                    }

                } else if (mode == DRAG) {

                    System.out.println("==== DRAG  " + x_cord + " - "
                            + y_cord);
                    if (x_cord > windowwidth) {
                        x_cord = windowwidth;
                    }
                    if (y_cord > windowheight) {
                        y_cord = windowheight;
                    }
                    layoutParams1.leftMargin = x_cord;
                    layoutParams1.topMargin = y_cord;
                    ima1.setLayoutParams(layoutParams1);

                } else if (lastEvent != null
                        && event.getPointerCount() == 2) {
                    /*newRot = rotation(event);
                    float r = newRot - d;
                    float[] values = new float[9];
                    matrix.getValues(values);
                    float tx = values[2];
                    float ty = values[5];
                    float sx = values[0];
                    matrix.postRotate(r, mid.x, mid.y);
                    System.out.println("=== Mode Rotate = " + mode);*/
                }
                break;

            }
            ima1.setImageMatrix(matrix);
            return true;
        }
    });
}

my Layout XML file is ...

<ImageView
    android:id="@+id/image"
    android:layout_width="50sp"
    android:layout_height="50sp"
    android:clickable="true"
    android:src="@drawable/ic_launcher" >

</ImageView>

<ImageView
    android:id="@+id/image1"
    android:layout_width="50sp"
    android:layout_height="50sp"
    android:layout_x="118dip"
    android:layout_y="30dip"
    android:src="@drawable/ic_launcher" >
</ImageView>


texts: How add a sprite to canvas using JavaScript?

texts:
I'm very new to sprites and I'm trying to figure out how to use them. I want to use a simple solution. Something like this:

var c = document.getElementById ('canvas)
var ctx = c.getContext ('2d');
    ctx.upload('image/testImage');

I'm very sorry if the solution is an obvious one, I'm not very good at JS. I am using pure JavaScript, I don't really like using engines.


texts: Unity: Rolling a ball around a spherical planet with forces

texts:
I'm trying to make a game in Unity where the player character is a ball (a sphere), and the game world is a planet (a very large sphere) that the ball can roll around on. The ball can be rolled in any direction, via the arrow keys. If the player holds the right arrow, the ball should roll smoothly to the right, all the way around the planet not leaving the ground, until it eventually reaches back to where it started. The camera follows the ball third person such that the ball always appears in the same position in the screen and the planet appears to be moving underneath it.

My question is, how can I use rigidbody.AddForce() to roll the ball in the way described above? What I think I need to do is to take the vector I get from taking the input values on the horizontal and vertical axes:

float moveX = Input.GetAxis ("Horizontal");
float moveY = Input.GetAxis ("Vertical");

Vector3 inputMovement = new Vector3 (moveX, 0.0f, moveY);

And rotate it somehow, so that I'm applying that vector as force to the ball but in the direction that's tangential to the point on the planet that the ball is currently on, and then apply it as force to the ball's rigidbody. So if you're looking at the planet head on, and the ball is at 3 o'clock, pressing the right arrow key should apply the force directly downwards.

Can anyone help me out here? I think it's probably really simple but I'm having trouble figuring it out exactly.


texts: How does real-time raytracing draw reflections of off-screen geometry?

texts:
I know what raytracing is, but I'm a bit curious how games are able to reflect off-screen geometry using raytracing in real-time.

I tried looking up the technical details but most of the articles are "what it is"


texts: How can I raycast between two moving objects in Unity?

texts:
How can I raycast between two moving objects?

I want to raycast from a moving enemy to a moving player.  I dont know how to actually code to make the direction work.

using UnityEngine;
using System.Collections;

public class Enemy_Manage_Two : MonoBehaviour {

    public GameObject player;

    // Use this for initialization
    void Start () { }

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

        player = GameObject.FindGameObjectWithTag ("Player");
        //Debug.Log (player.transform.position + " " + transform.position);

        Ray ray = new Ray (transform.position, player.transform.position);
        RaycastHit hit;

        Debug.DrawRay (transform.position, player.transform.position,
            Color.red);

        if(Physics.Raycast(ray, out hit)) {
            gameObject.renderer.material.color = Color.blue;
        } else {
            gameObject.renderer.material.color = Color.white;
        }
    }
}


texts: Should I use Coroutines to change variables in inspector smoothly?

texts:
I want to change the aperture of the depth of field in the camera smoothly by using Mathf.SmoothDamp and a Coroutine, however, since I'm new to game development, I don't know if this is the right way to do it. Any suggestions?

Code:

using System.Collections;
using UnityEngine;
using UnityEngine.UI;
using UnityStandardAssets.ImageEffects;

public class GameStartController : MonoBehaviour {
    public Button startButton;
    public GameObject cubeSpawner;

    // Use this for initialization
    private void Start() {
        startButton = startButton.GetComponent<Button>();
    }

    public void StartGame() {
        EnableCubeSpawner();
        SpawnStartingCubes();
        HideStartMenu();
        StartCoroutine("FocusCamera");
        PlayBackgroundMusic();
    }

    // Enables the cube spawner, so it can start spawning cubes
    private void EnableCubeSpawner() {
        cubeSpawner.SetActive(true);
    }

    private void SpawnStartingCubes() {
        cubeSpawner.GetComponent<CubeSpawner>().GenerateStartingCubes();
    }

    private void PlayBackgroundMusic() {
        var audio = GameObject.FindWithTag("Audio").GetComponent<AudioController>();
        audio.PlayBackgroundMusic();
    }

    private void HideStartMenu() {
        startButton.transform.parent.GetComponent<CanvasGroup>().interactable = false;
        startButton.transform.parent.GetComponent<CanvasGroup>().alpha = 0f;
    }

    private IEnumerator FocusCamera() {
        var camera = GameObject.FindWithTag("MainCamera").GetComponent<Camera>();
        var velocity = 0f;

        while (Mathf.Abs(camera.GetComponent<DepthOfField>().aperture) > 0.001f) {
            Debug.Log(Mathf.Abs(camera.GetComponent<DepthOfField>().aperture));

            camera.GetComponent<DepthOfField>().aperture = Mathf.SmoothDamp(camera.GetComponent<DepthOfField>().aperture, 0f, ref velocity, 0.3f);
            yield return null;
        }

        camera.GetComponent<DepthOfField>().aperture = 0f;
    }
}


texts: Flip the whole Directx output horizontally (mirror the output)

texts:
I would like to flip the whole fullscreen directX output horizontally so that the final output is presented mirror inverted.

Is there a way to create a IDirect3DDevice9 instance which produces mirrored output? Or even better: is there a way I can mirror the output just before the final call to the  Present(...) method of the IDirect3DDevice9?

Update/Clarification:
The underlying objective is to be able to use a projector which needs vertically flipped input.
The software I am currently using allows to register callbacks and hands over a handle to the IDirect3DDevice9 instance.
After my method is called and returns, the directx output is presented. This repeats after each frame.

I would like to flip the presented output horizontally.

I tried the following:

Use settings of the projector to flip the image (not supported)
Find a setting in the Operating System (windows7 doesn't support flipping of the image)
Find a setting in the graphics driver (AMD Catalyst) but only rotation is supported, not horizontal flipping

I have only little experience with directx so please bear with me (this is also why I would appreciate sample code or at least pointers to the right direction).

Update2:
I found out that I should be able to call SetTransform on the Direct3DDevice9 handle to change the D3DTS_PROJECTION with a proper Matrix. However this does not work in my example application.


texts: Does texture splatting always sample 4 x N textures per fragment (regardless of the weights)?

texts:
Texture splatting - usually - is done by vertex painting, where each channel R-G-B-A is assigned as a different texture weight.

Due to the way shaders are executed, doesn't it mean that the fragment shaders will ALWAYS sample 4+ textures even if the weights are (1,0,0,0) or (0,1,0,0)?

Lets say some parts of the terrain are almost exclusively grass and the other part of the terrain is exclusively dirt, which means the times when more than one texture sample is necessary is very, very rare - on the transitions, but regardless 4 textures are sampled?

Or do GPUs perform some sort of optimization to minimize the impact of this?


texts:
I'm looking for a clean way of making sprites that look like the following glowing circle, except in any arbitrary colour.

Originally we thought we could start with a gray-scale version of the above image (shown below) and then use the tint parameter in spriteBatch.Draw to change the colour of the glow.

The problem is that because spriteBatch.Draw uses multiplicative blending to blend the tint and the colour the white parts don't stay white, they become the colour of the tint. The next image shows (approximately) what this looks like.

The other solution we thought of is to have two separate sprites, a white interior and a grayscale glow, and then we apply the tint to the glow and draw that on top of the white interior. This produces the desired effect (to a degree) but is annoying on our part since it requires is to double all the sprites we want to draw this way.

Is there any other cleaner solution that produces the desired effect for an arbitrary colour?


texts:
I need help optimizing my Draw(); function to draw only what is visible in the viewport. Currently I'm drawing the whole Map array in a diamond shape. How can I make my function store only what is visible?

Here is an image explaining it better:

Black tiles are X axis, White tiles Y axis. Green tiles are what I would like the function to store, and the Orange rectangle is the viewport.

I'll include the relevant part of my code aswell:

for(i=0;i<Map.length;i++) {
for (j=0;j<Map[i].length;j++) {
tileX = (i - j) * (tile.width / 2);
tileX += (canvas.width /* 2*/) - (tile.width / 2);
tileY = (i + j) * (tile.height / 2);
tileY -= (canvas.height /* 2*/);

    c.drawImage(tile, tileX, tileY);
}
}

I've been trying to figure out how to solve this, but since I'm no genius I can't. Help appreciated.


texts: How define coordinates for bodies in outer space

texts:
What is a simple way of representing celestial bodies in outer space using a coordinate system? There are actual scientific coordinate systems (see https://en.wikipedia.org/wiki/Celestial_coordinate_system) but they may be too complicated to really understand and bring up the barrier of entry to my game.

I could just end up using a two-dimensional system to make things simple, but I'd like to inject some realism into the game and make it 3D. Any thoughts?

Edit: This is for a completely text-based game. The coordinates are for the user to situate themselves in 3D space and for me to be able to calculate distances between celestial objects.


texts: Securing a TCP connection on iOS for an MMO

texts:
I am currently building an iOS MMO and I'm leaning towards using TCP as my networking protocol over the higher level HTTP (for the speed difference and the fact that it does not require the client to poll constantly for updates.)

Now, through my research I know that with MMO and any client-server multiplayer games, you should never trust what the client sends to the server. As an extension of that, you wouldn't want anybody to read your packets to see the contents so it's harder for them to send correctly formatted data to the server. (Maybe I'm paranoid.)

The only problem is, where in HTTP there is great support for a secure channel in HTTPS through SSL where the setup occurs mainly server-side, I am not aware of a way to achieve the same thing on TCP. Is there any resource I could be referred that could help me achieving similar security, or at least good enough, on both the iOS side and server-side?

On a side note, if the answer involves doing the encryption and decryption on the client-side, would that severely impact the performance of my application?

Thanks!


texts:
I'm creating a level editor in Unity. I need to detect when an object is intersecting another as I don't want to allow the user to place an object when it is colliding with something else.

In the below diagam, there is a corner road piece and a tree. The dashed red line represents the mesh bounds of the road and the blue dashed line represents the mesh bounds of the tree.

My current approach is to use Physics.OverlapBox with mesh.bounds. In the diagram, visually, it is clear that the tree does not overlap the road. However, the bounds do overlap, therefore I cannot place the tree there.

Whats the best way to check if they are actually colliding in an efficient way? The level editor could potentially have thousands of objects.

EDIT:
I have since tried using Physics.ComputePenetration. Primitive-primitive checks work ok, primitive-mesh collider checks work ok, but mesh collider-mesh collider checks fail. From what I understand a concave mesh collider cannot interact with another concave mesh collider. Is there a workaround for this or must I momentarily make it convex before checking overlap? I just don't want to lose the accuracy of the concave collider.


texts: Graphical mesh lags behind collision shape in BulletPhysics debug drawing

texts:
In Bullet Physics when I debug draw physics world the graphical mesh lags behind the collsion shape.

m_DynamicsWorld->stepSimulation(1 / 60.0f, 10);

btTransform trans, trans2;
trans2 = m_RigidBodies.at("CubeMesh")->m_Body->getWorldTransform();

m_RigidBodies.at("CubeMesh")->m_Body->getMotionState()->getWorldTransform(trans);
/*
 * using
 * m_RigidBodies.at("CubeMesh")->m_Body->getMotionState()->getWorldTransform(trans);
 *
 * causes the graphical mesh to lag behind the collision shape in DebugDraw call
 * Checking with debugger shows that the lag error keeps on increasing
 * */
//
//
glm::mat4 M;
trans.getOpenGLMatrix(glm::value_ptr(M));
m_RigidBodies.at("CubeMesh")->GetGraphicalObject()->Model = M;

if (m_DebugDraw) {
    m_DynamicsWorld->debugDrawWorld();
}

If I use the OpenGL matrix from trans2 then debug drawing is perferct.
But with trans the graphical mesh lags behind the collision shape in debug draw.

I am using btDefaultMotionState when setting the CubeMesh rigid body.

btTransform tr;
    tr.setIdentity();
    tr.setOrigin(btVector3(0.0f, 90.0f, 0.0f));
    cubeMesh->m_PhysicsBody->m_MotionState = new btDefaultMotionState(tr);

Can anyone explain reason for this lag?


texts: Problems exporting animations to Unity 5

texts:
I've finished a model in SpeedTree Cinema v7.1.1 and the model exports correctly, but I can't figure out how to export the wind animation to Unity 5. The only problem is that the wind animation itself doesn't export.

I think that the problems are one of the following:

The way I export the mesh (.FBX ascii).
The settings in the export process.

I'll add some images so you understand better.

(Image 1.) In here you can see the export settings, the important aspects, regarding the animation, are in the 'Extra Data' tab, in there I included Wind, there are other options which I will describe in the next paragraph.

(Image 2.) In the 'Include' section, in the 'Extra Data' tab I can choose from a variety of things, but I don't know which one will work for exporting the wind animation to Unity 5.

In the 'Extra Data' tab there is also a sections where it says 'Format', under Include, in the 'Format' section the options are FBX/MC, FBX/PC2 and MDD. In the 'Files' sector the options are One or Per Frame.

If you know or think you know how to do this, please tell me, any help will be appreciated.

Thank you.


texts:
I'm trying to create a glow shader for a neon style game but I'm having a little trouble with rendertargets. Right now all I want is something VERY simple where I change the rendertarget, draw to it and then pass it into the shader. A lot of the examples I've looked at do the first part but don't include how to pass it all through a shader. Right now I'm not really concerned about the glow part, I just want to get it passing through a shader so I can work on the glow part.

edit - new code:

graphicsDevice.SetRenderTarget(renderTarget);

..
..
..

graphicsDevice.SetRenderTarget(null);

renderTargetTexture = (Texture2D)renderTarget;
loader.GlowShader.Parameters["glowTexture"].SetValue(renderTargetTexture);

for (int l = 0; l < loader.GlowShader.CurrentTechnique.Passes.Count; l++)
{
    loader.GlowShader.CurrentTechnique.Passes[l].Apply();
}

renderQuad.Draw();

And the glow shader (this is probaly really messy but I'm not really fuzzed about that right now, I just want the basic thing to work):

float4x4 World;
float4x4 View;
float4x4 Projection;

Texture glowTexture;

sampler glowSampler = sampler_state
{
texture = <glowTexture>;
magfilter = LINEAR;
minfilter = LINEAR;
mipfilter = LINEAR;
AddressU = clamp;
AddressV = clamp;
};

struct VertexShaderInput
{
float4 Position : POSITION0;
};

struct VertexShaderOutput
{
float4 Position : POSITION0;
};

VertexShaderOutput VSOutline(VertexShaderInput input)
{
VertexShaderOutput output;

float4 worldPosition = mul(input.Position, World);
float4 viewPosition = mul(worldPosition, View);

output.Position = mul(viewPosition, Projection);

return output;
}

float4 PSOutline(VertexShaderOutput input, float2 pixel:VPOS) : COLOR0
{
float2 uvPixel = (pixel + 0.5) * float2(1.0 / 1600, 1.0 / 900);
    return tex2D(glowSampler, uvPixel);
}

technique Outline
{
pass Pass1
{
    AlphaBlendEnable = TRUE;
    DestBlend = INVSRCALPHA;
    SrcBlend = SRCALPHA;

    VertexShader = compile vs_3_0 VSOutline();
    PixelShader = compile ps_3_0 PSOutline();
}
}

On a side note, if I try running this and drawing it using sprite batches it works so I think up until "rendertargetTexture = (Texture2D)renderTarget" everything is correct. It's just when I try to use the quads that nothing appears still.

        graphicsDevice.Clear(ClearOptions.Target | ClearOptions.DepthBuffer, Color.DarkSlateBlue, 1.0f, 0);
        using (SpriteBatch sprite = new SpriteBatch(graphicsDevice))
        {
            sprite.Begin();
            sprite.Draw(renderTargetTexture, new Vector2(0, 0), null, Color.White, 0, new Vector2(0, 0), 1, SpriteEffects.None, 1);
            sprite.End();
        }


texts: What is the universal "Distance Point" for human vision?

texts:
I'm not sure if this is the technical term, but I'm asking: At what rate do things scale bigger and smaller as they move toward and away from the human eye?

I know the equation for the linear perspective grids below are,

(size changed by this %) = 5/((distance to object) + 5) for the grid on the left
and
(size changed by this %) = 3/((distance to object) + 3) for the grid on the right

The '3's and the '5's come from the distance from the distance point to the vanishing point.
On the grid on the right the objects smaller at a bigger rate as they move back than they do on the grid on the rate that has a distance point of 5.

for example: a circle with a 1' diameter at (distance to object) = 0
will be 0.5' at 5' away because...
0.5 = 5(5 + 5) = 5/10 = 1/2

I know one point perspective is not nearly the most accurate model, but I'm only interested is calculating the size of objects depending on their size, or vice versa. Maybe you have a better equations that scales objects the same way the eye perceives.

Right now I only know what it isn't. It's not depth of field because that has to do with what's in focus.
It's not the range of vision in terms of degree or depth perspective because the eye(s) can see things shrink at the same rate with one eye looking at things going straight away from me.

In both of my grids the hieght from the horizon is 5' but things scale bigger and smaller at the same rates away from you whether you're on the ground or in a hot air balloon.

I suppose whatever the different setting there is between a fish eye and my eye is what I'm asking.

So, please. What is the distance point for the human eye?


texts:
VR is already at a point where it can render some impressive 3D landscapes. But it is awful at rendering text. This renders things like VR Desktop as basically unusable.

Question: Why is text resolution so bad in VR? I'm talking about from a technical standpoint?

EDIT: Here is a quote from an article about text resolution in VR:

  “Text is tough in VR. It’s hard to read, given the resolution of today’s HMDs and it’s hard to write, since you’re typically blind in a headset and it’s annoying to be tied to a keyboard at a desk when you’d rather walk and move around in VR. I tolerate these problems with RiftSketch by making the text in the editor extremely large. I can only see 20 lines of code at a time in VR whereas my physical desktop has a 4K monitor where I’m usually looking at 140 lines of code per file with several files open side-by-side.”

My question is why, from a technical perspective, is this the case? If we can render i.e. Shrek in VR, why can't we render clear text?


texts: Efficiently Handling Entity-Interactions in a Tile-Based World

texts:
I've been programming Roguelike games lately and there's a common problem I always run into. I can't seem to find a satisfactory solution for handling Monster-Monster interactions.

For the intents and purposes of this question, let's assume my Game-Map just is an array of bytes.

struct Map{
 unsigned char tiles[100][100];
};

Now, I've got Monsters, which have an X and a Y position.

struct Monster{
 unsigned int x, y;
};

Handling Monster-Map interactions is trivial. For example, if a monster wants to move to the left, I just have to check if tiles[x - 1][y] is a passable tile. This is very nice because no-matter how large the map is, I only have to check one tile.

But here's where I run into problems. What if a monster wants to breath fire onto a tile to the left. To ignite any monster that might be on the tile, I'd have to iterate through every monster in the entire world, checking if it's x, y matches the coordinates of the tile. This is not-so-nice, as the cost of breathing fire scales linearly with the amount of monsters in the world. If only there were a way to access monsters using tile-coordinates...

Which leads me to one solution. Tiles could hold a pointer to a monster. When a monster moves to a tile, it sets the previous tile's pointer to a nullptr and sets the current tile's pointer to this.

struct Map{
 unsigned char tiles[100][100];
 Monster* resident;
};

Now, when a monster breaths fire, it just ignites whatever monster is on that tile by using the tile's monster-pointer. Now the cost of breathing fire is constant, and the cost of moving is constant. Perfect!

But...

Now a tile is 9 bytes instead of 1 byte. sizeof(map) has more-than octoupled! Ouch!

My question is: What other solutions could be used to solve this problem? Maybe one's that meet in the middle on memory usage vs. number of operations.


texts:
Here's my interpretation of dot notation:

a = [2,6]
b = [1,4]
c = [0,8]
a . b . c = (2*6)+(1*4)+(0*8) = 12 + 4 + 0 = 16

What is the significance of 16? Apparently it's a scalar.

Am I right in thinking that a scalar is the number we times a unit vector by to get a vector that has a scaled up magnitude but the same direction as the unit vector? So again, what is the relevance of 16? When is it used? It's not the magnitude of all the vectors added up.

The magnitude of all of them is calculated as follows:

sqrt( ax * ax + ay * ay ) + sqrt( bx * bx + by * by ) + sqrt( cx * cx + cy * cy)
sqrt( 2 * 2 + 6 * 6 ) + sqrt( 1 * 1 + 4 * 4 ) + sqrt( 0 * 0 + 8 * 8)
sqrt( 4 + 36 ) + sqrt( 1 + 16 ) + sqrt( 0 + 64)
sqrt( 40 ) + sqrt( 17 ) + sqrt( 64)
6.3 + 4.1 + 8
10.4 + 8
18.4

So I don't really get this diagram:

Attempting with sensible numbers:

a = [1,0]
b = [4,3]

a . b = (1*0) + (4*3) = 0 + 12 = 12

So what exactly is a . b describing here? The magnitude of that vector? Because that isn't right:

the 'a.b' vector = [4,0]
sqrt( x*x + y*y )
sqrt( 4*4 + 0*0 )
sqrt( 16 + 0 )
4

So what is 12 describing?


texts: Why does execution continue when a delay is hit

texts:
I am working on a tile based game. I have a board generator and on the hard level I have to create 900 game tiles and add them to the screen. This takes about 3 to 4 seconds to complete. I started moving the UI code to C++ but ran into tons of issues and read that UI in C++ isn't recommended as its bug prone and difficult to work with. So I moved it back to blueprints and to avoid hogging all the CPU for 3 to 4 seconds I implemented a system to layout the board one row at a time with a short delay between to free up the CPU. This works beautifully and the board is laid out one row at a time and with the delay the FPS still hangs around 50 while doing it so sweet.

But I am running into a problem with the delay nodes. I layout a row, delay for a short period and layout the next row and so on. The proplem is as soon as I hit the first delay node, execution picks up AFTER the event containing the delays finishes.
1. While debugging, this breakpoint is the first one hit as expected.
2. Execution then enters the Layout10x10EasyBoard event as it should where a delay is triggered between rows.
3. Before the delay is finished execution picks up here and continues down the line before the delay even finishes.
4. Then this breakpoint is hit and we continue showing the rest of the game tiles.

It's my understanding that execution will stop at a delay so what I think should happen is the Layout10x10EasyBoard should finish execution before picking up at number 3. But that is not happening. The code at the end of the line requires all the tiles to be created before continuing and since the delay seems to have no effect on execution, that code is not working correctly. Does anyone know why the delay is not stopping execution?


texts:
I would like to mask a camera to only render to a certain (non-square) region of the screen, to be used as an overlay, for splitscreen, or any other application.
The goal is obviously to prevent any unnecessary rendering from that camera, so I specified performance, but I'm also happy to hear the easiest to implement option as well.
What I'm considering so far:

Stencil shader on a mesh in front of the camera - but my understanding is that doing so would require modifying all shaders on world objects, which isn't ideal. Is there an easier way I'm missing?
Transparent mesh with a cutout - I could cut out a hole in a mesh and the solid part would block rendering of objects behind it, but I'm not sure how to make that part be transparent so other things can render

I'm using Unity 2019 LTS and the built-in render pipeline
I feel like there must be a simple answer I'm missing but maybe I'm wrong?


texts: OpenGL How to render a voxel based world scene with many objects

texts:
I am working on a voxel game engine using OpenGL binding for JVM languages (scala is my case) - LWJGL 3 for OpenGL version 4.5 . Currently I'm stuck with chunk rendering (32*32*32 blocks). To render any object I firstly give it an unique ID, treating similar objects, like simple blocks, as one with different transformations, create one VAO data thing in initialization stage and after all preparation is done, I render a whole chunk looping through each block, passing its data to the shader and then calling drawElements with appropriate offset, taken from ID. This way fps drops from 3000(with 3 axis lines and a huge grid object rendered separately) to 1-2. So how should I correctly render a chunk ?

I used https://sites.google.com/site/letsmakeavoxelengine/home/basic-block-rendering tutorial as reference.

Fps dropping code:

def render(shader:Shader): Unit ={
   for(x <- 0 until SIZE) {
      for (y <- 0 until SIZE) {
         for (z <- 0 until SIZE) {
            val obj = blocks(x)(y)(z)
            if(obj != null){
               val M = obj.getTransformationMatrix() * Matrix4F.matrixTRANSLATION(obj.getPosition())
               shader.setUniformMat4f("M", M)
               shader.setUniformMat4f("MI", M.inverse())
               shader.setUniformBool("lightInteraction", obj.lightInteraction)
               shader.setUniform1f("smoothness", obj.smoothness)
               shader.setUniform3f("matD", obj.matDiffuse)
               shader.setUniform3f("matS", obj.matSpecular)
               GL13.glActiveTexture(GL13.GL_TEXTURE0); // Texture unit 0
               glBindTexture(GL_TEXTURE_2D, obj.getTextureID())
               Shader.full.setUniform1i("tex", 0)
               RenderRegistry.getRenderManager().render(obj.getID, obj.getRenderType())
            }
        }
     }
  }
}

EDIT: for those who are interested, instanced arrays helped me a lot !
Link for a tut: http://learnopengl.com/#!Advanced-OpenGL/Instancing


texts:
I have multiple ParticleSystems with TextureSheetAnimation pointing to the same texture, using different offsets/rows to choose different textures.

They seem to batch with each other, but they're also being split by Unity into multiple batches in a strange manner.

Here's a Frame Debugger view:

These 4 Draw Dynamic are on the same atlas, using Mobile/ParticlesAdditive shader.

The reason of breaking batching is:

  Objects have different batching keys. This is usually caused by using
  different vertex streams on ParticleSystems or by mixing Lines and
  Trails, or by mixing lit and unlit geometry.

All of the ParticleSystems have a simple setup, some Color Over Lifetime, some Velocity Over Lifetime etc.

The strange thing is that Unity breaks batching like it makes one batch, puts half of the stars and half of the smokes into that, and then, makes another batch from these two.

So they do batch, and the don't o.O

I couldn't find and help on the web about this issue.
I'd be glad for help.


texts: How do I set a touch listener in a child scene in AndEngine?

texts:
In my game, I want to implement touch listener for my child scene objects. Basically I tried all the possible way to implement this that I have usually done for my normal scenes, but those methods do not work here. Could somebody provide some guidance for setting touch area listener in child scene?

Here is my code:

    menuScene.setTouchAreaBindingEnabled(true);

    menuScene.registerTouchArea(resumeButtonSprite);
    menuScene.registerTouchArea(retryButtonSprite);
    menuScene.registerTouchArea(exitButtonSprite);

    menuScene.setOnAreaTouchListener(new IOnAreaTouchListener() {

        @Override
        public boolean onAreaTouched(TouchEvent pSceneTouchEvent,
                ITouchArea pTouchArea, float pTouchAreaLocalX,
                float pTouchAreaLocalY) {
            System.out.println("Touch");
            return true;
        }
    });

In this code, menuScene was a child scene activity.

Also after research I found that my engine was stopped while the child scene was activated so the touch event is not detected. I want to implement a pause menu in my game so any desirable solution for a pause menu implementation would help.


texts: Array Rectangle Collision Handling Inconsistency XNA 4.0

texts:
I made a simple collision detection prototype.Here's the code for the Player class's collision handler:

public void handleCollision(GameObject OtherObject)
    {
        if(this.CollidesWith(OtherObject))
        {
            if(OtherObject is Stage)
            {
                float rightEdgeDistance = OtherObject.BoundRect.X - (Position.X + this.BoundRect.Width);
                float leftEdgeDistance = OtherObject.BoundRect.X + OtherObject.BoundRect.Width - Position.X;

                float TopEdgeDistance = OtherObject.BoundRect.Y - (Position.Y + this.BoundRect.Height);
                float BottomEdgeDistance = OtherObject.BoundRect.Y + OtherObject.BoundRect.Height - Position.Y;

                float Left_Right_SmallerDistance = Math.Min(Math.Abs(rightEdgeDistance), Math.Abs(leftEdgeDistance));
                float Top_Bottom_SmallerDistance = Math.Min(Math.Abs(TopEdgeDistance), Math.Abs(BottomEdgeDistance));

                float smallerDistance = Math.Min(Math.Abs(Left_Right_SmallerDistance), Math.Abs(Top_Bottom_SmallerDistance));

                if (smallerDistance == Math.Abs(leftEdgeDistance))
                {
                    Position.X = OtherObject.BoundRect.X + OtherObject.BoundRect.Width;
                    Velocity.X = 0;
                }
                else if (smallerDistance == Math.Abs(rightEdgeDistance))
                {
                    Position.X = OtherObject.BoundRect.X - this.BoundRect.Width;
                    Velocity.X = 0;
                }
                else if (smallerDistance == Math.Abs(BottomEdgeDistance))
                {
                    Position.Y = OtherObject.BoundRect.Y + OtherObject.BoundRect.Height;
                    Velocity.Y = 0;
                }
                else if (smallerDistance == Math.Abs(TopEdgeDistance))
                {
                    Position.Y = OtherObject.BoundRect.Y - this.BoundRect.Height;
                    Velocity.Y = 0;
                }
            }
        }

and here's my Player class's Input Handler method I made:

public void inputHandler(GameTime gameTime,GameObject OtherObject)
    {
        Velocity = Vector2.Zero;

        if (Keyboard.GetState().IsKeyDown(Keys.W))
            Velocity.Y -= moveSpeed * (float)gameTime.ElapsedGameTime.TotalSeconds;
        if (Keyboard.GetState().IsKeyDown(Keys.S))
            Velocity.Y += moveSpeed * (float)gameTime.ElapsedGameTime.TotalSeconds;
        if (Keyboard.GetState().IsKeyDown(Keys.A))
            Velocity.X -= moveSpeed * (float)gameTime.ElapsedGameTime.TotalSeconds;
        if (Keyboard.GetState().IsKeyDown(Keys.D))
            Velocity.X += moveSpeed * (float)gameTime.ElapsedGameTime.TotalSeconds;

        handleCollision(OtherObject);
        Position += Velocity;
    }

Also here's my Update method In the Main Game Class.

protected override void Update(GameTime gameTime)
    {
        if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
            this.Exit();

        for (int i = 0; i < 3; i++)
            player.Update(gameTime, stage[i]);
        powerUp.Update(gameTime,player);
        base.Update(gameTime);
    }

It works, but when I use array it becomes buggy for some elements of the arrays as in the character can still move a bit inside of the rectangle when I press the key to go down and it will stay outside of the top of the rectangle only if I let go of the key and vice versa.

The rectangles are an array of 3. If I were to move and test the 3rd box. It will work perfectly.But if test the 2nd, it will sink in a bit and the 1st a bit more than the 2nd.
I use for loop for the update and draw the array elements. I see that the pattern is, the 1st is the first one to be checked in the Main Update method is will suffer the worst collision handling, while the last one will always be perfect. I tried other ways to handle the collision but to no avail. Why is that? And how can I counter this? Help please!


texts: IwGame (Marmalade): Does CIwGameSprite support SVG? How?

texts:
I have a small question about Marmalade IwGame engine.

Does the CIwGameSprite support SVG (I've read that yes it does)

If it does support SVG, how does it handle it,

Does it convert that Vector graphic to Pixel Graphics and cache it as an image then?

If it does not then how about the game performance? How does it handles animation, does it redraw the SVG each time?

How about scaling, if it does Caches images, Can I scale an SVG before scaling it?

Hopefully Someone can help

Thank you in advance

Ahmed


texts: HLSL Textured Light: outputs only a specific part of the texture (new problem)

texts:
Problem 1

I am trying to create a spotlight that instead of giving the circle within the spotlight a simple color, applies a texture to it. However, where the texture is supposed to be is only a black circle: image.

Solution: the position I used for my texture wasnt correct.

old and faulty code:

float4 TexturedSpotlightPixelShader(VertexShaderOutput input, float2 TextureCoordinate : TEXCOORD0) : COLOR0
{
    //I left out all the other code in the shader, full code is at the bottom of the thread
    color = tex2D(SpotlightTextureSampler, TextureCoordinate);
}

better code that solved my 'black problem (but created a new one):

float4 TexturedSpotlightPixelShader(VertexShaderOutput input) : COLOR0
{
    //I left out all the other code in the shader, full code is at the bottom of the thread
    color = tex2D(SpotlightTextureSampler, input.Position);
}

where at that point input.Position was set to the worldPosition in the vertexshader (which turned out was the reason for problem 2)

Problem 2

My spotlight now applies the texture, however the texture is repeated multiple times in miniature, as such: image

Solution:
I added these lines in the vertex shader:

input.Position3D.w = 1.0f;
output.Position = mul(viewPosition, Projection);

and by adding/changing these lines in the pixelshader:

float2 TextureCoordinates;
TextureCoordinates.x =  input.Position.x / input.Position.w / 2.0f + 0.5f;
TextureCoordinates.y = -input.Position.y / input.Position.w / 2.0f + 0.5f;
color += tex2D(SpotlightTextureSampler, TextureCoordinates);

however, there was still a third problem.

Problem 3

The third and probably (I hope :P) the last problem, my spotlight now only shows a part of my texture and manually resizing the image (in the image file, not in my code) doesnt change what part of the texture is shown, as such: image

Solution:
In my vertexshader I used the 2D positions (viewmatrix multiplied with the projection matrix) where I should have used a viewmatrix not based from my camera but from my spotlights point of view (and a projection matrix also for my spotlight's point of view)

My new code:

float4x4 View2, Projection2;

VertexShaderOutput SimpleVertexShader(VertexShaderInput input)
{
//left out a lot of code here
output.Position = mul(mul(worldPosition, View2), Projection2);
}

Full Code

Link to the shader code and the link to the xna/c# code.


texts: How can I mass-duplicate or "paint" Unity objects?

texts:
Let's say I have a basic map with a single box on it.

I want to make many, many more of these cubes, so they can cover a large portion of the map, like this:

Each box needs to be exactly one unit away from the adjacent boxes, so there is no overlap.

My idea was to clone the first box so the entire blue map is covered, then manually delete some of them to make the path.

In other software, there are ways to clone/duplicate large numbers of objects so that they fill an area, or follow a certain set of transformations. I cannot figure out how to do this in Unity.

I have tried manually duplicating the box and setting its location (so I have two properly-positioned boxes), then selected both of those and duplicating (so I have four boxes total), duplicating those, etc, but as soon as I select multiple boxes, I can't type in a location without all the selected boxes going there (so if I type a y-location of 12, every single selected box will be crammed on top of each other on y=12).


texts: What would be the best way to create a cone representing the field of view of an entity in Godot Engine?

texts:
I would like to create a game in which PC and NPCs would have a field of view, shown as a cone in the front of the entity (see picture for an example).

As it would be the first game I develop using Godot Engine, I am wondering what would be the best way to implement this feature. Also if possible, in later versions of the game, I would like to be able to make the decor stop the field of view, like what is done in Monaco: What's yours is mine.

Would you have any recommendation?


texts:
Is it possible to write application using OpenGL ES 2.0 "emulator" from AMD (AMD OpenGL ES SDK) and then use the same code (compile again, of course) in my iOS / Android / Whatever application ? The point is, that I write code faster in Visual Studio (where I have some fancy tools). Is it possible to do it that way ?

An second subquestion. So far, I have no experience with OpenGL, I know DX 9/11. Is there a big change (besside initialization) in those APIs in term of "learn basics of OpenGL if I know DX pretty well".


texts: What are the legal implications of creators streaming their development?

texts:
Is there any question of losing ownership of their work if people stream themselves coding? I can understand that streaming modeling, animations, and game design would be fine because even if you see someone do it it will take time to do, but what about code?

Are there worries about other people recording their streams and using their code?
Is there some special case for these games like being open source or non proprietary?


texts: Unity Visual Effect: Play() has no effect

texts:
I am making my first visual effects, and I make effect, when my ship is flying. So I am want to play it only when the ship is actually moving. I would suppose it's easy, you call Play(), it will play. You play Stop() it will stop. But when I call play, nothing happens.
public void Update()
{
    _ship.Rotate(Input.GetAxis("Horizontal"));

    var move = Input.GetAxis("Vertical");
    _ship.Move(move);
    if (move > 0)
    {
        FlyEffect.Play();
        FlyEffect.SetVector3("Velocity", new Vector3(0, -_ship.Speed * move, 0));
    }
    else
    {
        FlyEffect.Stop();
    }
}

When I let in Initial Event Name OnPlay, it is playing as it should be. But nothing from the script... What I am missing here?


texts: Is having a master builder object a bad idea?

texts:
I have wondered about using the following approach to creating Entity objects in a personal project. What I want is to be able to keep track of all Entity objects that get created, so whenever an instance is created, it should automatically get added to a bookkeeping list.

The approach I thought of using is to create a class that can hand out new Entity objects, rather than allowing them to be created directly. This class is called EntityFactory. It's not the factory pattern though. Basically, I define my Entity base class with a private constructor and made EntityFactory a friend class so that it could instantiate Entity objects and hand them out.

The only downside I can see is that I would have to pass around the EntityFactory object.

Will there be other problems? Is this a bad idea? If so, what alternatives are there to have automatic tracking of all Entity objects that get instantiated.


texts: The underlying mechanism in 'yield return www' of Unity3D Game Engine

texts:
In the Unity3D game engine, a common code sequence for getting remote data is this:

WWW www = new WWW("http://remote.com/data/location/with/texture.png");
yield return www;

What is the underlying mechanism here?

I know we use the yield mechanism in order to allow the next frame to be processed, while the download is being completed. But what is going on under the hood when we do the yield return www ?

What method is being called (if any, on the WWW class)?
Is Unity using threads?
Is the "upper" Unity layer getting hold of www instance and doing something?

EDIT:

This question is specifically about Unity3D internals. I'm not interested in explanations of how yield statement works in C#. Instead, I'm looking for an inside view of how Unity deals with these constructions, to allow, for example, to WWW to download a piece of data in a distributed manner across several frames.


texts: C++ Multithreading: accessing objects together

texts:
I'm kinda new to C++ Multithreading, and I'm keeping it simple right now. I will keep things simple and write psuedo-code. I'm making a Turn Based Strategy Game but let's keep it at Chess for now.

I have a basic draw thread and update thread.

function DrawThread
    CurrentScreen Drawn
end

function LogicThread
    CurrentScreen Update
end

Both of these functions run in their seperate threads.
Now I've run into a few problems.

For example: My pieces (units) are stored in a vector in the CurrentScreen

Class MapScreen
public:
    GetPieces returns VectorOfpieces

private:
    VectorOfpieces
end

The draw thread constantly draws the Chess pieces.

function Drawn
    for each chesspiece in VectorOfpieces
        draw chesspiece
    end
end

I have a cursor that moves grid-based and on, for example, ENTER checks if there is a Chess piece underneath it. (I've omitted any other code that has nothing to do with it)

function PollInput
    if KeyPressed is ENTER
        CheckUnderNeath
    end
end

function CheckUnderNeath
    for each chesspiece in MapScreen.GetPieces
        if chesspiece position is cursor position
            return chesspiece
        end
    end
end

Now as you might have guessed this Cursor update is in the other thread

function Update
    Cursor PollInput
end

And as you might have seen coming miles away, both threads will eventually end up using the same vector at the same time, causing a crash.

Is there any easy implementation to fix a problem like this, as my 2-3 problems right now are eventually down to this problem, threads bumping heads.

What bothers me is this crash isn't consistant.
Because it's a vector I will get a "map/set iterator not dereferencable" error.

I'd appreciate a C++ answer eventhough my question was in Psuedocode. Thanks in advance!

TL:DR One thread tries to update the position of the same pointer the other tries to draw.


texts: Realtime rendering using a ray tracing engine

texts:
I want to render an object that has a mesh with one million hexagonal elements(100 * 100 * 100).

Lights, shadows and textures is not important and each element has a solid color.
and finally, the actions I want to have, is simply rotating the object, zooming and panning.

I am wondering what ray tracing engine is better for my conditions. or, do I have to take another approach?

any help will be appreciated.


texts: What are the rest of the blending functions used for?

texts:
In general, I know of five ways to make use of blending functions (these are for OpenGL, but replace glBlendFunc() with SetRenderState(D3DRS_SRCBLEND) and SetRenderState(D3DRS_DESTBLEND) for DirectX):

glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA): Alpha blending (not premultiplied)

glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA): Alpha blending (premultiplied)

glBlendFunc(GL_ONE, GL_ONE): Additive blending

glBlendFunc(GL_ZERO, GL_SRC_COLOR): Multiplicative blending

glBlendFunc(GL_DST_COLOR, GL_SRC_COLOR): 2x Multiplicative blending (somewhat obscure)

But there are so many other values you can use when setting your blending function, and not only I've never seen them in use, but also have no idea what they could be used for. In particular, I don't see what GL_DST_ALPHA could be used for.

What the rest of the blending functions used for?


texts: WPF or WinForms for Game Development and learning resources?

texts:
I'm looking to create a game framework for my own personal use...
I want to use WPF, but I'm unsure if that is a wise choice...

The games I will be writing should not require high performance graphics, so I am hoping to build on native classes...  I do not want to rely on external DLL's unless I generate them myself.

The games will be for young children, say 4 to 8.  Most will be learning puzzles or simple shooters.

The most advanced will be a platform game (non-scrolling screen like the old Atari Miner 2049er game).

I think I know how to write something like the old Atari Chopper Command (partially written and my 4 year old loves it, but I used WinForms and GDI), Pac-Man, Tetris, Astroids, Space Invaders, Slider Puzzle, but I do not really know how to write the platform game...  In my mind, I'm getting caught in collision detection and how to make a character jump and how to make a character walk up a slope or steps...

Can anyone point me to information on developing a platform game in C#?

Would you suggest WinForms or WPF for game development?

I'm not looking for great graphics and speed, just entertaining game play...


texts: How can I create a "cracked glass" material?

texts:
I'm trying to figure out how the cracked and chipped glass effect in a Bioshock Infinite Burial at Sea Episode 2 works.

My current guess is that it is essentially a transparent shader with gloss. It would have a map defining the direction of reflections from the environment, with the cracks being significantly different from the mesh's normals. It would also include some kind of model of the angular dependence of the amount of refraction/transmission to reflection so that it can roughly approximate Fesnel's equations.

It doesn't appear to be a full refractive model, so I'm wondering how exactly this is implemented? Am I right with what I have said above?


texts:
A user of ours has an issue whereby they cannot run our application, which requires DX11 API support and hardware support for DX10.1. The strange this about this issue is that the user is running Windows 10, having upgraded from Vista(!).
His DXDiag output looks like this:
         Operating System: Windows 10 Pro 64-bit (10.0, Build 10240) (10240.th1.150930-1750)
             Language: English (Regional Setting: English)
  System Manufacturer: Dell Inc.
         System Model: Studio 1747
                 BIOS: Default System BIOS
            Processor: Intel(R) Core(TM) i7 CPU       Q 720  @ 1.60GHz (8 CPUs), ~1.6GHz
               Memory: 4096MB RAM
  Available OS Memory: 4084MB RAM
            Page File: 3956MB used, 3839MB available
          Windows Dir: C:\WINDOWS
      DirectX Version: 10.1

...

---------------
Display Devices
---------------
      Card name: ATI Mobility Radeon HD 4650
   Manufacturer: Advanced Micro Devices, Inc.
      Chip type: ATI display adapter (0x9480)
       DAC type: Internal DAC(400MHz)
    Device Type: Full Device
     Device Key: Enum\PCI\VEN_1002&DEV_9480&SUBSYS_02EB1028&REV_00
 Display Memory: 2809 MB
 Dedicated Memory: 1017 MB
  Shared Memory: 1792 MB
   Current Mode: 1600 x 900 (32 bit) (60Hz)
   Monitor Name: Generic PnP Monitor
  Monitor Model: unknown
     Monitor Id: SEC544B
    Native Mode: 1600 x 900(p) (60.209Hz)
    Output Type: Internal
    Driver Name: aticfx64.dll,aticfx64.dll,aticfx32,aticfx32,atiumd64.dll,atidxx64.dll,atiumdag,atidxx32,atiumdva,atiumd6a.cap,atitmm64.dll
Driver File Version: 8.17.0010.1129 (English)
 Driver Version: 8.970.100.9001
    DDI Version: 10.1
 Feature Levels: 10.1,10.0,9.3,9.2,9.1
   Driver Model: WDDM 1.1
Graphics Preemption: DMA
 Compute Preemption: DMA
       Miracast: Not Supported
Hybrid Graphics GPU: Not Applicable
 Power P-states: Not Applicable
Driver Attributes: Final Retail
Driver Date/Size: 1/13/2015 17:45:56, 1094024 bytes

I am by no means a DirectX expert, but my understanding was that all post W7 OS's had DX11+ support baked in to the operating system, and that updates are provided via Windows Update. I've never seen this particular issue before, and am not sure what the next step is. The user says that they are fully up to date wrt Windows Update.
Just to clarify a little more, here is a quote from a Q&A on the steam site:

DirectX has two components - the API on the computer (the software) and the GPU (the hardware). You need both to have "support" for a specific DirectX version. What you get when you look at DxDiag is the API version installed on your operating system. It gives you the software. This number is useless if you don't have the equal number for your hardware.
DirectX 11 API (the software) comes standard with Windows 7 and Windows 8.

The issue we are having is that we use the DX11 API via SharpDX, and use feature level 10.1. So we need the DX11 API, which we had assumed was always available for > W7. It seems that this is not the case for this user, and it's the first time we have seen this.


texts: Client side prediction buffer size considerations for jitter

texts:
I am currently having a FPS game with client side prediction. Every 20ms, the client sends it's input to the server. The server buffers 5 ticks worth of input (100ms) and starts consuming the inputs each tick and sends a world snapshot to the client. The client then validates the predictions and corrects the simulations if there is a misprediction. The setup works fine under ideal network conditions. However when the latency suddenly spikes from say 50ms to 400ms, the client's tick packet is delayed which causes the server to eat through all of the available inputs in the buffer and resort to using the previous tick values to perform server simulation. When the client input finally arrives at the server late, the server discards the input because it has already processed the input for that particular tick (using old input values).
How do I handle this edge case of latency increasing and decreasing? Sure I could use a larger buffer size for the inputs, but that will cause delays between client state and server state. Using a smaller buffer will cause the server to stall from inputs if there is a jitter that is more than the duration required by the server to process the inputs. I was under an impression that I would need some kind of dynamic buffer size that expands and contracts. However, I am out of ideas to implement something like this.
Does anyone have a solution?


texts: Blurry Background Images When Player is moving

texts:
So I've been developing a platformer and the when the player moves around the world the background images and tiles become really blurry. I've tried a number of fixes. I've made sure that the position given out by the camera and player are both whole numbers as you can see in the video below.

http://www.youtube.com/watch?v=1AFuP1yXhY4&feature=youtu.be

On top of that I've also made it a point to use PointWrap in every SpriteBatch call made in the game

spriteBatch.Begin(SpriteSortMode.Texture,
                   BlendState.AlphaBlend,
                   SamplerState.PointWrap, null, null, null,
                   camera.TransformMatrix);

None of these works are really working, could someone please give me some other suggestions to try ?


texts: GLSL variables as main function params vs on their own line?

texts:
I am learning OpenGL and GLSL. I was taught that the in/out variables should be formatted like this:

in vec3 something;
out vec3 somethingElse;

int main()
{
    // etc...
}

However, I ran across code like this online (ShaderToy):

int main(in vec3 something, out vec3 somethingElse)
{
    Is there a difference?
}

Is there any difference?


texts:
I am currently in preparation on making a game. This game will be looks like Lifeline by 3 Minute Games, which is a story text-based game.

My game will have the same concept with it. Where there will be a scrollable history of conversation between player and characters in game. However, my game will has more than one conversation history. He will be able to interact with more than one character. Therefore, when the game start, it will show list of interactable characters in game, and player can choose who he will interact with when any available.

I am planning to make it with Unity. But I don't know is it possible to create some scrollable history of text, each with different content, like chat history, in Unity.

So I wanna ask your opinion, is it good to just continue with using Unity, or should I change the game engine I use? If I should change, what is the best game engine to cope with this kind of game?

Thank in advance :)


texts: Unity3D: Touch and Objects have different coordinate systems

texts:
I would like to associate the same script to different empty objects I just use as placeholders in the game. The aim is to exploit their positions so that when the user touch a point in the screen, close to one of these objects, a dedicate GUI appears. The problem is that though the two objects are different their scripts seem to influence each other so that when the game is running and I touch one of these two objects both the gui appears. What am I doing wrong?

Some hours later...
This happens because the object and the touch are in two different coordinate systems. For instance though I touch the object I get (-0.77, 0.46) for the object and (12.1,95.2) for the touch which, I guess, is measured in pixel. How to transform one into the other?

....
private var check: boolean;
var topCamera : Camera;
var customSkin : GUISkin;

function Update () {
   if (Input.GetMouseButtonDown(0)){
      if(Input.mousePosition.x > this.transform.position.x - Screen.width*0.20 && Input.mousePosition.x < this.transform.position.x + Screen.width*20){
        if(Input.mousePosition.y > this.transform.position.y - Screen.height*0.2 && Input.mousePosition.y < this.transform.position.y + Screen.height*0.2){
                check = true;
        }
    }
}

if(check){
   //the camera zooms forward
}else{
   //the camera zooms backward
}
}

function OnGUI () {
if (this.check){
var w = Screen.width;
var h = Screen.height;
var bw = 0.083;
var bws = 0.001 *w;
GUI.skin = customSkin;
GUI.Box(new Rect(w*0.6,h*0.3,w*0.38,h*0.45), "Stuff");
customSkin.box.fontSize = 0.04*h;
customSkin.textField.fontSize = 0.08*h;
customSkin.button.fontSize = 0.04*h;
textFieldString = GUI.TextField (Rect (w*0.62, h*0.39, w*0.34, h*0.1), textFieldString);
if (GUI.Button (Rect (w*0.62,h*0.50, w*bw, h*0.1), "+")) {
    if (this.check){
        this.check=false;

    }else{
        this.check = true;
    }
//...
}
 //...
    }


texts: Compute spheres 2D speeds in perspective projected animations

texts:
I created two animations that consist of spheres moving in a perspective projected 3D space, which means that the size and speed of the spheres vary with the distance: they increase when they are closer to the viewer (the camera) and decrease when they move farther away from the viewer. Both animations are played on a computer 2D screen.

In the Random Movement Animation, the spheres are moving randomly in different directions (GIF 1). In my code, I computed their spherical coordinates (sphere.position.xyz) with the two angles theta and Phi (see below the formulas used for the position and their derivates).

In the Optic Flow Animation, it is the camera that moves along the z-axis (camera_z -= .1) and the spheres don't move (GIF 2).

In the context of a neuroscientific experiment, I need to match the perception of speed between the two animations, thus I need to first compute the 2D speed in both animations (By 2D, I refer to the screen coordinates rather than the world coordinates). What are the respective speed formulas for each animation? Does the speed of each sphere in the optic flow calculation equal to the camera's speed?

How I generated Spheres coordinates in the Random animation:

for sphere in spheres:

        sphere.position.xy = np.random.uniform(-25, 25, size=2)
        z = np.random.uniform(near_z, far_z)

        sphere.position.z = z
        sphere.position.x *= z/-50
        sphere.position.y *= z/-50

        sphere.theta_deg = np.random.rand(1) * 360
        sphere.phi_deg = np.random.rand(1) * 360

        theta_rad = sphere.theta_deg * np.pi / 180
        phi_rad = sphere.phi_deg* np.pi / 180

        sphere.dx = speed * np.sin(-phi_rad - theta_rad) / frameRate
        sphere.dy = -speed * np.cos(phi_rad + theta_rad) / frameRate
        sphere.dz = -speed * np.cos(theta_rad) / frameRate


texts: How can I calculate "All squares within R" in a natural looking manner?

texts:
I'm working with a square grid, and I have a couple of effects that target all squares within R; in other words, a circular (or spherical) effect.

But, circles being, well, circular, and squares being... less so, things obviously have to be approximated. For instance:

But! I feel that some of these approximations don't quite give the approximation I want. For instance, consider this square:

It's obvious that the majority of the square falls within the circle, but using a pure "square counting" method (i.e., all squares within R of the origin), it gets left out.

Is there a better algorithm to grab all squares for which the majority of their area lies within the circle?


texts: Handling multiple input mapped to single in-game controls

texts:
I am trying to map multiple input types to single in-game controls using libGDX's InputProcessor and ControllerListener interfaces. Currently, I have created a single InputType interface which is inherited by the following enumerations:

Keys
MouseButtons
Buttons (Gamepad)
Axis (Gamepad)

The InputType interface declares a single method getCode(); as all inheriting enumerations have their own codes.

I have created a Keyboard class which implements InputProcessor and a Gamepad class which implements ControllerListener. Both classes extend from a generic InputHandler class which stores a Set<T extends InputType>. I also created a Mouse class and AxisHandler class which work similarly, although as touch events are handled within the InputProcessor and axis events handled within the ControllerListener, the Keyboard and Gamepad classes contain instances of these classes respectively.

Finally, to map multiple input types to single controls, I created a ControlMap class which stores an EnumMap<Controls, InputType[]>, where Controls is an enumeration containing all controls that are present within the game (MOVE_UP, MOVE_DOWN, ATTACK, etc.)

The obvious problem with this is that I'm going from an event-driven approach to polling. Every time input is processed, I'm storing the associated InputType accordingly, and this can create an overhead after some time.

My game uses a component-based architecture, so in my MovementSystem I'd check whether controls are down by using if (Controls.controlDown(Controls.MOVE_DOWN)). I can't seem to find any other way of approaching this problem just yet. There is no apparent drop in performance; when input isn't being handled, nothing is stored. Is my method fine as it is and am I over thinking the problem too much?

My UML is terrible but here's how I can best describe the process:


texts: Algo for Minimum no of solving in a level like Bubble Blast2

texts: Is their any way to make a algo to know minimum no of way to solve in Bubble Blast 2. I am trying to make a clone of it. My real problem is only to determine the minimum no of tap to finish the game. I can play and find them but if level are more then 100 , it is time consuming . In Bubble Blast 2 there are 10000+ levels. So is there any way to solve this problem?


texts: I can't find any clear directions on how to get started. I only see a Windows installer for MonoGame but what little documentation I've found seems to say you install it on the Mac and do the work there. If someone could simply tell me which parts go where that would be a big help.


texts: Percentages for different platform generation

texts:
I have a level manager, which creates levels and levels create platforms.

Levels can contain a variety of platforms.

I dont really understand how I can say:

  I want a 10% of one platform being made, 30% chance of another, and 70% chance for anotgher and so on...

At the moment I have a method that looks like this:

   private void creationManager(float moveChance, float breakableChance, float superJumpChance)

I'm not sure how I can use these values and probabaility to determine which type of paltform is created.

Any ideas?


texts: Is it more efficient to transform vertices on the CPU or the GPU?

texts:
Working on optimizing the rendering core of my game engine and I have a couple of questions.

Is it more efficient to transform vertices to world space on the CPU before you send then stream to the GPU, or is it better to do this on the GPU?  If done on the GPU this means I have to send the world matrix to the GPU for every different mesh however the GPU is highly optimized to deal with these calculations.  It seems to me that doing it on the CPU would save some time, however, because I can transform the vertices and send over world positions all at one time.


texts: Spatial Jitter problem in large unity project

texts:
I have a very large environment where i am getting very weird view of objects as picture given below:

As you can see there are black lines/spot, maybe the vertex lit problem. Currently I am using Standard specular shader. Remember this problem is only occuring at the end of the project (away from origin like position -17000, 0, 144)

As a workaround i tried to change my shader to Unlit and i found this shader

 Shader "Unlit/UnlitAlphaWithFade"
 {
     Properties
     {
         _Color ("Color Tint", Color) = (1,1,1,1)
         _MainTex ("Base (RGB) Alpha (A)", 2D) = "white"
     }

     Category
     {
         Lighting Off
         ZWrite Off
                 ZWrite On  // uncomment if you have problems like the sprite disappear in some rotations.
         Cull back
         Blend SrcAlpha OneMinusSrcAlpha
                 //AlphaTest Greater 0.001  // uncomment if you have problems like the sprites or 3d text have white quads instead of alpha pixels.
         Tags {Queue=Transparent}

         SubShader
         {

              Pass
              {
                         SetTexture [_MainTex]
                         {
                     ConstantColor [_Color]
                    Combine Texture * constant
                 }
             }
         }
     }
 }

This shader has almost solve the problem but i have to tweak and set colour of each object as be default it is not according to my expectation.


texts: How do you remove the default sky in Unreal?

texts: I'd rather texture/animate my own sky. How do I remove the default sky?


texts: How do I check collision when firing bullet?

texts:
I'm currently creating 2D game from top perspective. I'm having problems with bullets. Yes, I currently simulate their movement so user can see them (about 2x ). Moving them with

// this is static
Direction = new Vector2(mouse.X, mouse.Y) - new Vector2(player.x, player.y);
Direction.Normalize();
Speed = 900f;

//this is called in Draw(GameTime gameTime)
Position += Direction * 9f * Speed * (float)gameTime.ElapsedGameTime.TotalSeconds;

actually it's working perfectly, however, they're too fast so I can't check their collision each frame and I need to re-play their way each frame. How would I do it? And how would I do this available for both server (which doesn't use XNA as I want to port it to Linux later) and client (using XNA)?

Here's an image which shows the problem (1. bullet is before target 2. bullet is behind target, so it can no longer intersect the target. My goal is to calculate whether it intersected the target before)

I have almost forgot to mention! These objects are moving, these are player, that means that user can get out of the bullet's trace


texts: Are most cross-platform C++ libraries really not cross-platform for game developing?

texts:
Sorry for my poor English.

Some cross-platform C++ libraries are useful for game developing, e.g., Eigen, Skia, OpenCV, Tensor Flow.  I am not sure whether they are really limited to officially stated supported platforms (desktop and mobile only) without supports on game console and web platforms.  Thank you.
 I just want to conform it.  Let me know whether those libraries are indeed very limited in terms of cross-platform portability for game developing.


texts: How to create a trail like this in Unity?

texts:
I want to create a trail like this game...

When the plane flies it creates this trail...

It's possible because the game itself was made in Unity...

But I can't find any options to do so...

Any help would be much appreciated...


texts: Are there definitive, unambiguous terms for hexagon tile orientations?

texts:
I have been working on a tile map editor and plan to support two orientations for hexagons. I have seen various terms used, but these all seem ambiguous to me.

Horizontal, Vertical (ambiguous: does this mean they line up horizontally, or stack horizontally?)
Flat, Pointed (ambiguous: Are they flat on the sides or top and bottom?)

I would like to find unambiguous terms for the following two orientations for hexagons -- ideally, these would be definitive and succinct (I could refer to these as "Flat on Top" and "Pointed on Top" but would prefer something more technical and authoritative).

Edit: I was holding out for something more technical, but it's hard to argue with Amit. For me, "pointed" sounds more formal than "pointy," so I am going to use the following (a decision reinforced by DMGregory's answer): Flat-top and Pointed-Top.


texts: How to rewind time on just the main character?

texts: I have a 2D sidescrolling game and I want the character to be able to rewind time on him if he messes up. I don't want anything else to change, just the main character's position. Any idea how I can do this?


texts:
I have problem with bullet collisions. You can see problem on this video (around 0:18):

http://goo.gl/DiVP8l

Objects are "embeded" inside vertical bars - that is not correct - they should be bouncing like at the beggining of the video. I am using sphere and box as bullet bodies. I have also enabled CCD, that improves stability a little, but problem is still there.

Pulsing bars are controlled with this code:

dist = distance I need the bar to change its position in a single frame
float g = (2 * dist) / (times.dTime); //dTime = 1/60
bars[i]->GetBulletBody()->setLinearVelocity(btVector3(0, 0, 0));
bars[i]->GetBulletBody()->setGravity(btVector3(0, speedUpFactor * g, 0));

I have constant update rate of physics and world, set to be 1/60 s.


texts:
I'm working on a global startegy game that uses a 2D tiled map. The map is to be 8000x8000 tiles large (this size is fixed, the map stays the way it is throughout the game), since I'm covering a large real-world area, but have to do so in detail. I want to store this map in a txt file. To do so I want to use simple IDs for the tiles, but that still leaves me with 2 bytes per tile and a total of about 185 Mb for my txt file, which is far too large.
So I went ahead and thought of ways to reduce the size of the file that contains the map. This is what I came up with:
Instead of stupidly defining an ID per field, I define regions, lines and specific fields:

region: a rectangle of any size (requires 23 bytes, regardless of its size)

line: a straight line of any length in any simple compass-direction (north, west, east, south) (requires 20 bytes, regardless of its length)

specific field: a specific single field (requires 13 bytes, due to the coordinates that have to be given)

using these three simple "objects" I managed to reduce the size of the file significantly. I may want to add that fields that have already been defined can be overwritten. Take the following rectangle for example:

1 1 1 1 2

1 1 1 1 2

2 2 2 2 2

This could be defined as a 5x3 rectangle of 2s with a 4x2 rectangle of 1s overwriting part of it (total of 46 bytes, as opposed to 195 bytes when defining every field specifically)

The problem I have now is the following:
I'm trying to write a map-editor to simplify the process of making such a map. Obviously this editor should automatically generate the map-file, using the previously described objects to reduce the size. The question is, how do I go about writing such an algorithm, meaning one that finds optimal or near-optimal combinations of regions, lines and specific fields, possibly without taking 3 hours to do so? The algorithm that qucikly came to mind was your typical straightforward approach of going through all possible rectangles, picking out those that work best, then going through the undefined fields and defining lines and then specifying the rest specifically, but as you can probably tell, this approach takes a lot of time, so I'd rather avoid it. I had the idea of splitting the large map into smaller parts, but in the process the algorithm loses some of its precision, as this would eliminate rectangles and lines that cross over two or more of these smaller parts.

So, does anyone perhaps have an idea how to optimize the algorithm, or maybe even a better approach? I'd be very grateful for some help here, since I can't quite go on writing the game without the map in place...

I realise this is a lot of text and perhaps an even bigger problem, but anyways

Thanks in advance,

LegionaryCohort


texts: DOTween: How to make a spring bounce effect?

texts: I am looking how to make a bouncing effect with DOTween, like when the object is attached to a spring. How can I make an effect like this?


texts: Unity3D Tag as a public variable in editor

texts:
How do you incorporate Tag strings into a scripts editor found in the inspector?

What it is I'm babbling about: When you create a public GameObject fooObject in a script, it shows up as a box that can have Game Objects dragged onto in its editor. It also has a small clickable dot that shows every Game Object that could be selected.

Now, say I have a public string fooString that would specifically be used for referencing the Tag strings of Game Objects (such as if (fooObject.tag == fooTag) or another use). Is there a way to define that string so that in the script's editor it strictly allows tag names to be used with it? I'm assuming with a similar clickable dot or a drop down menu of every selectable tag.

Although I could just manually type my string, a solution like the one above would have big object-orientated advantages. For example, if I was to change the name of this tag, it would change the string variable accordingly, as if the variable was a reference to such tag.

[Note to the moderators: I looked for an answer to this question for nearly 2 hours now to no avail. I understand that I may be missing some specific wrong word choice, in which case this question easily could have already been answered here. If this is closed as a duplicate, then, a quick comment explaining my mistake would be greatly appreciated.]


texts: How to make a ball move with constant velocity after a collision?

texts:
In my scene there is a player and a ball a few units above the ground. The ball has a rigidbody2D attached with zero gravity.

I built a "cage" with square sprites to simulate the edges.

I would like that after the player has hit the ball, the ball moves with a constant speed (no matter how strong the collision with the player is).

I want to recreate something like this after the collision:
https://www.youtube.com/watch?v=zsdPYFPTdw0

I wrote this code:

{
    private Rigidbody2D rb;
    private Vector2 lastVelocity;

    private ConstantForce2D cf;

    private Vector2 direction;
    private Vector2 surfaceNormal;
    [HideInInspector]
    public float speed = 5;

    [HideInInspector]
    public float setTime = 5;

    [HideInInspector]
    public float smooth = 6;
    private bool timeEnded = false;

    private void Awake()
    {
        rb = GetComponent<Rigidbody2D>();
        cf = GetComponent<ConstantForce2D>();
    }

    private void Update()
    {
        Debug.Log(rb.velocity.magnitude);

        if (timeEnded)
            rb.velocity = Vector2.Lerp(rb.velocity, Vector2.zero, smooth * Time.deltaTime);
    }

    private void FixedUpdate()
    {
        lastVelocity = rb.velocity;
    }

    private void OnCollisionEnter2D(Collision2D collision)
    {
        // QUANDO VIENE COLPITO
        if (collision.collider.tag == "Player")
        {
            surfaceNormal = collision.contacts[0].normal;
            direction = surfaceNormal.normalized;

            //cf.force = direction * speed;
            rb.AddForce(cf.force = direction * speed * Time.fixedDeltaTime);

            StartCoroutine(StopBall());
        }

        // QUANDO COLPISCE IL MURO
        if (collision.collider.tag == "Wall")
        {
            Vector2 surfaceNormal = collision.contacts[0].normal;
            rb.velocity = Vector2.Reflect(lastVelocity, surfaceNormal);
        }
    }

    IEnumerator StopBall()
    {
        yield return new WaitForSeconds(setTime);

        timeEnded = true;
    }
}

I still don't understand why the speed doesn't remain constant, why sometimes it's zero and why it depends on the force with which I hit it.


texts: Is it possible to tell Unity3d to ignore part of its hierarchy?

texts:
One aspect of the game I'm making is each level is made up of room objects, which contain the sprites, physics objects and so on. When you enter a level the whole level is deserialsed and loaded into memory but only the room you are currently in is considered, nothing else is drawn, updated or whatever.

I was wondering how I would achieve this in Unity3d. I can imagine having a hierachry with lots of rooms with the various room contents as children, can I tell unity to ignore everything (for updating, drawing, physics and so on) in the hierarchy but the current room and its children?


texts: Tween - keeping a constant velocity at different distances

texts:
I am using a tweening library to move my units around. The problem is that the speed varies depending on the distance that the unit has to move because of the  tweening:

var time = 1000;
var tween = new TWEEN.Tween({ x: startX, y: startY })
    .to({ x: endX, y: endY }, time)
    .start();

^No matter the x and y values it will always take the same amount of time.

I tried fixing this by dividing the distance by the speed:

// distance = speed * time
// time = distance / speed
var x = endX - startX;
var y = endY - startY;
var distance = Math.sqrt(x * x + y * y);

var time = distance / speed * dt;
var tween = new TWEEN.Tween({ x: startX, y: startY })
    .to({ x: endX, y: endY }, time)
    .start();

However it still doesn't move at the same speed! Grr!

I made a snippet that shows a square endlessly moving in a rectangle, when done correctly ( which this isnt... ) it should move at the same velocity no matter the distance.

var rect = document.getElementById("rect");

var pos = [ [0, 0], [200, 0], [200, 50], [0, 50] ];
var i = 0;
var time = 1000;
var speed = 10 * 1000; // 10px per second

var tweenStart = { x: 0, y: 0 };
var tweenEnd = { x: pos[i][0], y: pos[i][1] };

var tween = new TWEEN.Tween(tweenStart)
    .to(tweenEnd, time)
    .onUpdate(function () {
        rect.style.top = this.y + "px";
        rect.style.left = this.x + "px";
    })
    .onComplete(function () {
        tweenStart.x = pos[i][0];
        tweenStart.y = pos[i][1];
        i += 1;
        if (i >= pos.length) i = 0;
        tweenEnd.x = pos[i][0];
        tweenEnd.y = pos[i][1];
        // time = distance / speed
        var x = tweenEnd.x - tweenStart.x;
        var y = tweenEnd.y - tweenEnd.y;
        var distance = Math.sqrt(x * x + y * y);
        time = distance / speed * dt;
        tween.start();
});

setTimeout(initiate, 0);

var now, then, dt;

function tick() {

    now = perfNow();
    dt = now - then;
    then = now;

    TWEEN.update();

    requestAnimationFrame(tick);

};

var perfNow = (self.performance && self.performance.now) ? self.performance.now.bind(performance) : Date.now;

function initiate() {

    var x = tweenEnd.x - tweenStart.x;
    var y = tweenEnd.y - tweenEnd.y;
    var distance = Math.sqrt(x * x + y * y);
    time = distance / speed * dt;

    tween.start();

    then = perfNow();

    tick();

};
body {
    margin: 0;
    overflow: hidden;
}
div {
    position: absolute;
    width: 10px;
    height: 10px;
    background-color: black;
}


texts:
Hey all, I'm making a simple side-scrolling game, and I would appreciate some input!

My collision detection system is a simple bounding box detection, so it's really easy to implement. However my collision resolution is ridiculous! Currently I have a little formula like this:

if (colliding(firstObject,secondObject))
  firstObject.resolve_collision(yAxisOffset);
if (colliding(firstObject,secondObject))
  firstObject.resolve_collision(xAxisOffset);

where yAxisOffset is only set if the first object's previous y position was outside the second object's collision frame, respectively xAxisOffset as well.

Now this is working great, in general. However there is a single problem. When I have a stack of objects and I push the first object against that stack, the first object get's "stuck," on the stack. What's I think is happening is the object's collision system checks and resolves for collisions based on creation time, so If I check one axis, then the other, the object will "sink" object directly along the checking axis.

This sinking action causes the collision detection routine to think there's a gap between our position and the other object's position, and when I finally check the object that I've already sunk into, my object's position is resolved to it's original position...

All this is great, and I'm sure if I bang my head against a wall long enough i'll come up with a working algorithm, but I'd rather not =). So what in the heck do you think I should do? How could I change my collision resolution system to fix this?

Here's the program (temporary link, not sure how long it'll last)
(notes: arrow keys to navigate, click to drop block, x to jump)

I'd appreciate any help you can offer!


texts: Is there any notification when my data uploaded to VRAM is erased?

texts: When my data (vertices, textures, et cetera) is purged from VRAM, how I can know that?


texts: Clearing screen in Pygame so content on the screen is not lost, but updated

texts: I am creating a Tetris game using Pygame. It generates a random shape from a list and draws it onto the screen. However, when the arrow key is pressed by the user, it draws the shape again without removing the previous one.The problem is that I can't use screen.fill(White) as it will remove the other shapes at the bottom of the grid. How can I refresh the screen without removing the shapes at the bottom of the grid, and so that it doesn't draw the shape multiple times. The first image shows the original shape, and the second image shows the result of pressing the arrow key.


texts:
I have a very simple app which removes buttons and re-adds buttons to certain layouts when a button is clicked. The problem is, this process is taking a very long time. My question is: How can I make this process faster

I have a simple program which swaps two buttons:

Remove view (button)
Generate random number, and from my button array list, get the button in the array list with the index of that random number
Remove that random view (button)
Add the two buttons in each others places.

Now, the problem is that I want the buttons to swap places right after I click on a button. Instead, the program is taking about three seconds to do the above four tasks after I click the button.

Here is the code:

    red.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(final View v) {

                // Remove the clicked button from it's frame layout parent.
                    ViewManager p = (ViewManager) v.getParent();
                    p.removeView(v);
                    // Find another button randomly.
                    Random rng = new Random();
                    View v2;
                    do
                    {
                        int i = rng.nextInt(4);
                        v2 = buttons.get(i);
                    }
                    while (v2 == v); // Loop until you get a different button to swap with.
                    // Remove the other button from it's frame layout parent.
                    ViewManager p2 = (ViewManager) v2.getParent();
                    p2.removeView(v2);
                    // Now simply insert each button into the other buttons frame layout.
                    p.addView(v2, v2.getLayoutParams()); //Adding v2, the random button, into where v, the button clicked, was before(p)!
                    p2.addView(v, v.getLayoutParams()); //Adding v, the button clicked, into where v2, the random button, was before(p2)
                }
   }
       });

So, having done my research, I learned that one thing that may be slowing me down could be the fact that the main UI is handling all of this work. So, I decided to put all of this code inside of a thread to run in the background:

 red.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(final View v) {

            new Thread(new Runnable() {

                @Override
                public void run() {

//ALL THE CODE I PROVIDED UP THERE

}).start();

But putting this code in a thread gave me another exception. This is probably happening because I am trying to update the UI (remove and add buttons) from the thread.

 android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.

So, I don't know how I should approach this problem, since I do need to change my views...

Another thing that could be slowing down my app (from the research I did) is that my layout might be inflating after a while, due to such a giant layout. My layout is pretty big, so that may be it:

I doubt it is the layout though, as the screen loads pretty fast. What happens is that when I click a button, the screen freezes for three seconds, and then updates the UI with the completed tasks.

Could I somehow take up more memory to be faster as an app? The whole basis of my app runs on being able to complete those four tasks and update the UI as soon as the user presses on a button. What else should I do? I have also added this line in my manifest after looking at similar questions:

android:largeHeap = "true"

Now, what else should I do? Thanks so much for your help, I really appreciate it. I have been stuck on this all day...so I really (REALLY!) would like any feedback.

Thanks so much for your time


texts: Unity>How to make a Box Collider( or any other collider) fits the gameObject perfectly?

texts:
I have downloaded and imported the Robot Kyle model in Unity 3D...and the problem with me is I want to add a Box or Capsule Collider to it...but I can't fit it perfectly...

So what shall I do?


texts: Where should the collision response/resolution code go?

texts:
I've got a collision response/resolution function that does the same for any pair of two entities. It's is in the World class right now.

But right before that function is invoked, I have some entity-specific logic:

A specific pair of entities should never have their collisions resolved (this is literally to keep the player from hitting itself with a carried object)
When two specific entities collide, an event should be triggered

Because of this, I'm starting to wonder if I should move the collision resolution function as a method into Entity, that'd allow me to use polymorphism. However, this sound very messy to me: If both entities involved in a collision can resolve it, how can I figure out which one should do it?

Is there another way to move these special cases out of World?


texts: Which coordinate space is the canonical default for each shader pipeline stage?

texts:
I'm working with Direct3D 11 and HLSL. I use four different shaders (vertex, hull, domain and pixel).

I always have troubles using the right coordinate space in my shaders. Could somebody identify the appropriate space for the vertex, hull, domain and pixel shader stages?