texts: How to make my Diamond-Square-algorithm less 'random'?

texts:
I'm currently writing a world generator for a Tilemap-Engine in C++.
But there is a little problem concerning the Water to Land ratio.
My DiamondSquare-class returns a field of random float-values between 0 and 1, and my condition to let my tilemap-class generate a Land-Tile on the given spot, is that the returned value is bigger than 0.5. The problem is, that the amount of values bigger or smaller than 0.5 fluctuates with every call of my float-field-generation function, so that i often only have a few little Islands/a few little lakes on my map. How could i manipulate my code, so that a 50/50 distibution is more likeley to happen?

include "DiamondSquare.h"
include <Windows.h>
pragma comment (lib, "winmm.lib")
floatfield /*typedef floatfield is std::vector<std::vector<float>>*/ DiamondSquare::generate(int n, float randomness) {

// Initializing stuff
srand(timeGetTime());
fieldSize = pow(2,n)+1;
randField.resize(fieldSize);
for (int i=0; i<fieldSize; i++)
{
    randField[i].resize(fieldSize);
    for (int j=0; j<fieldSize; j++)
    {
        randField[i][j] = 0;
    }
}
stepDist = pow(2, n-1);
m_randomness = randomness;

// Setting corner point values
randField[0][0] = (float)(rand()%1001)/1000;
randField[fieldSize-1][0] = (float)(rand()%1001)/1000;
randField[0][fieldSize-1] = (float)(rand()%1001)/1000;
randField[fieldSize-1][fieldSize-1] = (float)(rand()%1001)/1000;

// Core Algorithm
for (int i=0; i<n; i++)
{
    for (int k=0; k<pow(2,i); k++)
    {
        for (int l=0; l<pow(2,i); l++)
        {
            // Getting position of current tile
            int xPos = k*2*stepDist+stepDist;
            int yPos = l*2*stepDist+stepDist;
            // Getting Average of sorrounding tiles
            randField[xPos][yPos] = (randField[xPos-stepDist][yPos-stepDist]+randField[xPos+stepDist][yPos-stepDist]+
                                      randField[xPos+stepDist][yPos+stepDist]+randField[xPos-stepDist][yPos+stepDist])/4;
            // Random displacement
            if (rand()%2 == 1)
                randField[xPos][yPos] += (float)(rand()%1001)/1000/pow(randomness,i+1);
            else randField[xPos][yPos] -= (float)(rand()%1001)/1000/pow(randomness,i+1);

            // Doing the same for the Square-Step tiles left of and above     the current tile
            squareAvg(xPos-stepDist, yPos, i);
            squareAvg(xPos, yPos-stepDist, i);

            // If diamond-step-tile is part of the right side row
            if (k == pow(2,i)-1)
                squareAvg(xPos+stepDist, yPos, i);
            // If diamond-step tile is part of the bottom row
            if (l == pow(2,i)-1)
                squareAvg(xPos, yPos+stepDist, i);
        }
    }
    stepDist /= 2; // Self explanatory
}
return randField; // Return random field.
[![Often, insted of maps like this, there is stuff like 10% water or 10% land][1]][1]}

void DiamondSquare::squareAvg(int x, int y, int i) {
// Testing if square-Tile lies at on of the sides of the map, if so, adding         0 (i tried implementing wrapping, but this option generated better looking     landscapes)
randField[x][y] = (x!=0) ? randField[x-stepDist][y] : 0;
randField[x][y] += (x!=fieldSize-1) ? randField[x+stepDist][y] : 0;
randField[x][y] += (y!=0) ? randField[x][y-stepDist] : 0;
randField[x][y] += (y!=fieldSize-1) ? randField[x][y+stepDist] : 0;
// If 4 values were added /= 4, otherwise /=3.
if (x!=0 && x!=fieldSize-1 && y!=0 && y!=fieldSize-1)
    randField[x][y] /= 4;
else randField[x][y] /= 3;
// Displacement
if (rand()%2 == 1)
    randField[x][y] += (float)(rand()%1001)/1000/pow(m_randomness,i+1);
else randField[x][y] -= (float)(rand()%1001)/1000/pow(m_randomness,i+1);
}

Is it maybe even possible to preciseley control n<0.5 to n>0.5 ratio ? That would be ideal. I just don't know how and where to manipulate the code.
That's about it.


texts: Modeling "singletons" in an Entity-Component System

texts:
I'm writing a basic Asteroids implementation as an exercise in learning how to think in entities and components, and most of it is fairly straightforward. But one thing I keep running into is situations where a given system needs a certain entity/component and I know there's only ever one of it. Examples:

MovementSystem needs to know the bounds of the World component so it knows when to wrap to the other side of the screen
LevelSystem needs to know the GameState component so it knows whether it should create new asteroids
InputSystem needs to know the state of the Keyboard component

(etc.)

The ECS I'm using is hand-rolled but conceptually similar to Adam Martin's Entity System RDBMS Beta - Java. What I find myself doing repeatedly for cases like the above is asking the EntityManager for "all" components of the given type and taking the "first" (aka only) one:

World world = entityManager.getAllComponentsOfType(World.class).iterator().next()

This works but seems clunky, and makes the code annoyingly non-obvious. Alternatives I've thought of:

make each system loop over 'all' of these components, just as they would any other component type
add explicit support for 'singleton' components to the EntityManager
don't use components for these things; inject them into the systems some other way, and live with the fact that this makes the design significantly less pure

Is there a typical or well-known solution to this problem?


texts: Calculating distance from viewer to object in a shader

texts:
Good morning,

I'm working through creating the spherical billboards technique outlined in this paper. I'm trying to create a shader that calculates the distance from the camera to all objects in the scene and stores the results in a texture. I keep getting either a completely black or white texture.

Here are my questions:

I assume the position that's automatically sent to the vertex shader from ogre is in object space?
The gpu interpolates the output position from the vertex shader when it sends it to the fragment shader. Does it do the same for my depth calculation or do I need to move that calculation to the fragment shader?
Is there a way to debug shaders? I have no errors but I'm not sure I'm getting my parameters passed into the shaders correctly.

Here's my shader code:

void DepthVertexShader(
   float4 position : POSITION,
   uniform float4x4 worldViewProjMatrix,
   uniform float3 eyePosition,
   out float4 outPosition : POSITION,
   out float Depth
)
{
   // position is in object space
   // outPosition is in camera space
   outPosition = mul( worldViewProjMatrix, position );
   // calculate distance from camera to vertex
   Depth = length( eyePosition - position );
}

void DepthFragmentShader(
   float Depth : TEXCOORD0,
   uniform float fNear,
   uniform float fFar,
   out float4 outColor : COLOR
)
{
   // clamp output using clip planes
   float fColor = 1.0 - smoothstep( fNear, fFar, Depth );
   outColor = float4( fColor, fColor, fColor, 1.0 );
}

fNear is the near clip plane for the scene
fFar is the far clip plane for the scene


texts: Can I change the background color where a sprite is shown in the inspector?

texts:
this is how a sprite shows in the inspector.
It's white pixelart with transparent background.
Is there a way to change the background checkered pattern color in the inspector so I can actually see the sprite?

Note: I don't want to change any color in the game, just the background in the inspector, in the editor, so there's some contrast and I can actually see the sprite pattern.


texts: Efficient way to store information about neighbour chunks

texts:
I've finally managed to implement an infinite chunk loading system for my voxel engine. Since every chunk needs to have information about the border of the neighbouring chunks, I need to access them fast. First some information about how I'm storing the voxel data: I have an Integer array of block information on each chunk (rather than byte because of the read/write access speed), which is stored in an Dictionary(Vector3i chunkPos, Chunk chunk).
When building a chunk I have to access the voxel data of the chunk and of the neighbouring chunks several times.

Without information about their neighbours it currently looks like this:

So I've tried the following two things:

getting the chunk data every time like this:

public static int getBlockAt(int x, int y, int z) {
    Vector3i chunkIndex = new Vector3i(
        x >> ChunkManager.logChunkSize,
        y >> ChunkManager.logChunkSize,
        z >> ChunkManager.logChunkSize
    );

    if (chunkManager.chunkData.ContainsKey(chunkIndex)) {
        return chunkManager.chunkData[chunkIndex].data[x & ChunkManager.chunkMask, y & ChunkManager.chunkMask, z & ChunkManager.chunkMask]} return 0;

storing chunkSize + 2 information on each chunk, which makes editing much, much slower, but improves chunk loading alot

In general I want to implement something like using approach 1 only when the block data isn't on the chunk.

I really don't know how I could do it! Do you have an idea, or experience from writing voxel engines?

Thanks in advance!


texts: How do I retain previously drawn graphics?

texts:
I've created a simple program that draws lines from a fixed point to a random point each frame. I wanted to keep each line on the screen. However, it always seems to be cleared each time it draws on the spriteBatch even without GraphicsDevice.Clear(color) being called. What seems to be the problem?

protected override void Draw(GameTime gameTime)
{
   spriteBatch.Begin();
   DrawLine(spriteBatch);
   spriteBatch.End();

   base.Draw(gameTime);
}

private void DrawLine(SpriteBatch spriteBatch)
    {
        Random r = new Random();

        Vector2 a = new Vector2(50, 100);
        Vector2 b = new Vector2(r.Next(0, 640), r.Next(0,480));

        Texture2D filler= new Texture2D(GraphicsDevice, 1, 1, false, SurfaceFormat.Color);
        filler.SetData(new[] { Color.Black });

        float length = Vector2.Distance(a, b);
        float angle = (float)Math.Atan2(b.Y - a.Y, b.X - a.X);
        spriteBatch.Draw(filler, a, null, Color.Black, angle, Vector2.Zero, new Vector2(length,10.0f), SpriteEffects.None, 0f);

    }

What am I doing wrong?


texts: Are there any preexisting maps for a Minecraft-like level I could use in my engine?

texts:
I am working on a tiny cube-based engine like Minecraft. I was wondering if there is a way for me to get large blocky terrain in a text format that I can use for rendering on my engine?

I don't want to start on procedural generation now, I just want a resource where I can get the coord list for a pretty looking terrain.

Alternatively, is it possible for me to parse the Minecraft world files and use that data to generate terrain/buildings in my code?


texts:
I'm working on a multiplayer game played through the browser.  It's not a real-time game which is why I decided to go with a database, however I'm pretty weak with SQL and starting to run into problems.

Right now I'm working on the inventory system, the requirements being:

A Player can have 0 or more of each item
Certain items have a max limit
Certain items can only be bought with a minimum XP

I have a table for my Player and Item.  How should I store the inventory relationship?  I feel like I'll need a separate table for this, rather than a simple ManyToMany relationship, but I'm not sure what it would look like.  My first thought is a table that has a player ID and the counts of each item that player has.  I would need a column for each item I have which doesn't seem very maintainable... does that seem right?

And what's the best way to ensure the max limit and minimum XP constraints?  The proper way seems to be a constraint in the database, but I can't think of a way to query items that the player is eligible to buy.

Thanks!


texts:
I am making a maze game in Java, where you have to escape the maze without being caught by the randomly-moving AI.

The code I am using to decide which direction the enemy moves in causes the character to change direction way too fast. It currently chooses a random number, which corresponds to the direction in which the AI moves.

How can I edit this method so it only chooses a random number every 3 seconds?

if(new Random().nextInt(4) == 0){
    xMove = speed;
}
if(new Random().nextInt(4) == 1){
    xMove = -speed;
}
if(new Random().nextInt(4) == 2){
    yMove = speed;
}
if(new Random().nextInt(4) == 3){
    yMove = -speed;
}


texts: Why would I want to set a minimal OpenGL version before creating the context?

texts:
Typical GLFW applications have these lines after glfwInit():
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);

And similarly:
glfwMakeContextCurrent(window);

I get that glfwMakeContextCurrent is needed before sending calls to the OpenGL API, but the doc says

You can require a minimum OpenGL version by setting the GLFW_CONTEXT_VERSION_MAJOR and GLFW_CONTEXT_VERSION_MINOR hints before creation

But why would I want that? Why would I cut options for OpenGL versions? I did not understand that, if I am interpreting it correctly in the first place


texts: Why do adventure game puzzles often have a single clue/solution?

texts:
When recently playing an adventure game (Dreamfall Chapters) it hit me that most adventure games I've played have had only a single solution to the "puzzles" they require you to solve. This frequently means a single clue the player has to "get" or they may be in for a long session of "brute force" combing through everything they can find in the game world. (I remember this happening to me several time in classics such as Sam & Max Hit the Road.)

In comparison, a frequently cited piece of advice for Game Masters that want the players to follow clues in a tabletop roleplaying game is the Rule of Three, which basically states that every conclusion should be supported by (at least) three clues that the players see. As a corollary, every "chokepoint" problem should have three ways to solve it.

Is there a game design reason for why a similar rule isn't necessary for video games? Or are single-solution puzzles just lazy design?


texts: Deslect targeted enemy question. How to change back to original color

texts:
In the code below I have now:

Press tab, enemy changes green.
Press tab again, (deselecting the target) enemy changes to blue.

What I want to happen:

Press tab, enemy changes to green.
Press tab again, (deselecting the
target) green goes away. (enemy is its original color)

Here is my current code:

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

public class Targetting : MonoBehaviour {
    public List<Transform> targets;
    public Transform selectedTarget;

    private Transform myTransform;

    // Use this for initialization
    void Start () {
        targets = new List<Transform>();
        selectedTarget = null;
        myTransform = transform;

        AddAllEnemies();
    }

    public void AddAllEnemies()
    {
        GameObject[] go = GameObject.FindGameObjectsWithTag("Enemy");

        foreach(GameObject enemy in go)
            AddTarget(enemy.transform);
    }

    public void AddTarget(Transform enemy)
    {
        targets.Add(enemy);
    }

    private void SortTargetsByDistance()
    {
        targets.Sort(delegate(Transform t1,Transform t2) {
                return Vector3.Distance(t1.position, myTransform.position).CompareTo(Vector3.Distance(t2.position, myTransform.position));
                });
    }

    private void TargetEnemy()
    {
        if(selectedTarget == null)
        {
            SortTargetsByDistance();
            selectedTarget = targets[0];
        }
        else
        {
            int index = targets.IndexOf(selectedTarget);

            if(index < targets.Count -1)
            {
                index++;
            }
            else
            {
                index = 0;
            }
            DeselectTarget();
            selectedTarget = targets[index];
        }
        SelectTarget();
    }

    private void SelectTarget()
    {
        selectedTarget.renderer.material.color = Color.green;
    }

    private void DeselectTarget()
    {
        selectedTarget.renderer.material.color = Color.blue;
        selectedTarget = null;
    }

    // Update is called once per frame
    void Update()
    {
        if(Input.GetKeyDown(KeyCode.Tab))
        {
            TargetEnemy();
        }
    }

}


texts: LibGDX - SpriteBatch's .draw() method requiring float[]

texts:
Please excuse my lack of knowledge with LibGDX, as I have just started learning it.
I am going through some simple tutorials, and in one of them, I draw a string onto the screen like so:

// the following code is in the main file in the core project folder:

// this is in the create() method:
private SpriteBatch batch;
batch = new SpriteBatch();

// this is in the render() method:
batch.draw(batch, "Hello world", 200, 200);

I am getting an error saying: The method draw(texture, float[], int, int) in the type SpriteBatch is not applicable for the arguments (SpriteBatch, int, int)

So, LibGDX wants a float array to draw instead of a string?

Thanks in advance.


texts:
Unity text is very blurry. How can I fix it?
To be honest, I have no idea why it behaves this way:

Hope that someone faced the same problem and will be able to share how it was tackled.


texts: How can I update my materials to work with LWRP?

texts:
I'm using Unity 2019.1.6f1.

When I open a new scene with  the LWRP template project, I see errors from all materials in the scene. For example, the Jigsaw appears in my scene but in console window I see a message telling me:

  Jigsaw_Mat material was not upgraded. There's no upgrader to convert Lightweight Render Pipeline/Lit shader to selected pipeline
  UnityEditor.Rendering.LWRP.LightweightRenderPipelineMaterialUpgrader:UpgradeProjectMaterials()

All materials show this message, and I don't know what to do to fix these materials. How can I resolve this error?


texts: Different way to pass uniforms to seperate draws in glMultiDrawElementsIndirect

texts:
Given OpenGL version 4.3 and GLSL 430, what would be the best way to pass a matrix to each model in a draw call to glMultiDrawElementsIndirect?

I am thinking of going the way of a TBO and indexing it based on my own attribute passed in to each model that tells the shader which draw call it is currently on. That technique is not my favourite as I have to create another buffer for something that should be basic functionality for the type of draw call (think gl_DrawID), so I have come here to ask what I could do instead.

(gl_DrawID is not supported on my current system. Although it really should be: AMD catalyst 14.4 with OpenGL 4.4 support)


texts: Avoid shaking artifacts in 3D continuous collision detection

texts:
I am programming a 3D game physics engine that uses continuous collision detection to avoid my objects from being able to "tunnel" through the geometry.

Here is basically how it works:

Execute a swept-object/world collision check
Move the object up to the exact point where it collides
If no time is remaining, everything is done, just stop
Else, update the velocity so that the object "slides" in a direction orthogonal to the collision normal before returning to step 1. This is the formula I use for this sliding (I just remove the component of the motion in the normal direction): velocity = velocity - (velocity dot normal) * normal

My problem occurs in this kind of situation:

(Do not take into account faces other than A and B, their only purpose is the emphasize the 3D aspect of the shape)

In the first frame, the object first follows the black arrow, then collides face A. It slides correctly on face A (first red arrow) and then climbs on face B (second red arrow). The problem with this algorithm is precisely the fact that it can climb on the opposite face: after several consecutive frames (here the other frames are the cyan and green ones), the general motion will follow the good path (the intersection line of planes A and B), but with a local left-right shaking artifact that I would appreciate getting rid of.

Any idea to solve this would be greatly appreciated.


texts:
I want to create a RagDoll body in andEngine which can run and jump over different jumpObjects. Can any one give a nice tutorial on how to create RagDoll body and how to move it, like jump and running.

Thanks in Advance.


texts: How does Minecraft render its sunset and sky?

texts:
In Minecraft, the sunset looks really beautiful and I've always wanted to know how they do it.

Do they use several skyboxes rendered over eachother? That is, one for the sky (which can turn dark and light depending on the time of the day), one for the sun and moon, and one for the orange horizon effect?

I was hoping someone could enlighten me... I wish I could enter wireframe or something like that but as far as I know that is not possible.


texts: Trying to project a point onto a cubemap

texts:
I've got a simple test program with a camera within a cubemap (skybox). You can look around, and it feels like you're in a 3D room, but really it's just a cubemap image.

Now I want to draw a point (well, ultimately, a large number of points) on the screen, such that it appears to be anchored at a point on the cubemap. For example, if the cubemap is of a room, then I want to put a point on the "wall", and have it appear to be stationary when you look around.

Given that there is no actual environment, it's just a cubemap, the points I want to project are represented as x/y rotational angles, rather than absolute 3D vertices. I tried calculating the position manually, using the camera x/y angles and interpolating across the screen. However because the cubemap is distorted at the edges due to the camera's projection matrix, my linear calculations don't match up, so the point appears to wobble as you look around.

I know I need to incorporate the camera's projection matrix to get it to appear in the correct position, but I'm not sure how. I'm using the CML math library, and I noticed it has a project_point() function, but it works with absolute 3D coordinates, so I don't know how that helps me when starting with angles instead of coordinates.

If someone could get me pointed in the right direction, I would appreciate it.

Edit: After reading other questions on polar coordinates, I came up with this for converting x/y angles (relative to the camera view angle) into a 3d coordinate that I could project onto the screen:

x = sin(horizontal_angle) * cos(vertical_angle)
y = sin(horizontal_angle) * sin(vertical_angle)
z = cos(horizontal_angle)

This almost works, I feel like I'm close. I can rotate the camera left and right, and the point appears to remain stationary. However, as soon as I rotate it up or down as well, the point moves rather significantly. However I I haven't been able to figure out why that is so far.


texts: Unlocking XNA game update rate and preventing unnecessary Draw calls and heavy logic Updates

texts:
I had some input problems which can be partially solved by unlocking game update rate. Now the input updates as fast as possible, but the game also calls the main Draw method a lot too. I believe there are some calls that may be omitted without causing any noticeable problems, and I'd like to know how I can do it.

I tried using code similar to frame rate counter code, but it just doesn't work. It either doesn't skip frames, or skips them all. Here it is:

double time = 0;
protected override void Draw(GameTime gameTime)
{
    double frameRate = 1.0 / 60;
    time += gameTime.ElapsedGameTime.TotalSeconds;
    if (time > frameRate)
    {
        time = time % frameRate;
    // the rest of the draw call

When the game window is active, only dark purple color is visible I guess that's application's default background color when nothing is being drawn. When the game window is not active, frame rate drops from infinity (though I get about 4000 fps) to around 50 (which is unusual, since the default frame rate is 60, but it's not an issue).

If I set frameRate value to lower than 1/50 (like 1/10) it becomes obvious that draw calls are skipped and the dark purple background is visible (and resources are being saved), but only when the window is inactive. So the game behaves as expected, but only when it is not in focus, which is not the way it is supposed to be played :)

How do I fix this?

I'd like to extend this to work on heavy logic updates, so they too are not done more than enough times per second. The game should only update input as fast as possible, and I believe, reducing the number of logic update and draw calls frees up resources for input update to use, increasing their frequency.

This is how I ended up doing this:

double interval = 1d / 60; // draw and do heavy updates only 60 frames per second
double time;

protected override void Update(GameTime gameTime)
{
    LightUpdate(gameTime);

    time += gameTime.ElapsedGameTime.TotalSeconds;

    if (time > interval)
        time = time % interval; // or while (time > interval) time -= interval;
    else
    {
        SuppressDraw();
        base.Update(gameTime);
        return;
    }

    HeavyUpdate(gameTime);
}

Saves frames, light update rate rose from 2k to 110k @100Hz which is a tremendous success!


texts: 2D helicopter game, how to create corridor walls?

texts:
I'm looking into adapting the classic "helicopter" game (i.e. http://www.addictinggames.com/helicopter.html), but I haven't yet figured out how to create the walls-generation engine.

Any pointers into the pseudocode? I'm not so interested in the objects in the middle- only the methodology for generating the sides in a way which increases with difficulty (closes in more, has more unexpected curves) as the game progresses.


texts:
I am using the following code to handle experience points gains:

reqXP = (Level ^ 2 + Level + 3) * 4

    If (currXP >= reqXP) Then

        Level = Level + 1
        expPoints = expPoints + 3

        excessXP = currXP - reqXP

        currXP = excessXP

        excessXP = 0

    End If

lbl_XP.Text = "Experience : " & currXP & " / " & reqXP

However, whenever I level up, it won't update the reqExp Label until I get my next batch of experience points.

What do I need to change to make this work?


texts: How can I achieve a pseudo-3D camera effect like this?

texts:
I am trying to achieve a pseudo-3D camera effect similar to this:

I have gotten the following results using a 3D camera and billboards:

I am now running into the following problems:

In the first billboard example, the size discrepancy between when the sprites are at the "front" and "back" is too great. I need to have them be more similar to the above.
The bottom y-coordinate of the sprites never seem to change in my example, but they do (slightly) in the example that I want.
I need to be able to control how close to the right and left edge of the screen the sprites go to.

In the first billboard example I setup my camera like so:

// (float fovxDegrees, float aspect, float znear, float zfar)
this.simpleCamera.Perspective(75f, 1.5f, 0.01f, 400);

// (Vector3 eye, Vector3 target, Vector3 up)
this.simpleCamera.LookAt(new Vector3(0, 5f, 10f), Vector3.Zero, Vector3.Up);

My sprites are positioned at the following locations:

new Vector3(-4f, 1f, 0f);
new Vector3(-4f, 1f, 1f);

Full CSharp code: http://pastebin.com/9G0FDNLs

Billboard HLSL: http://pastebin.com/uB8e3gXU

If you want the grid: http://pastebin.com/R5UCBNWt


texts: Making a multi-pieced rectangular breakable body with Farseer

texts:
Using Farseer 3.3.1  I want to create a rectangular BreakableBody with many pieces.  Right now here is my code:

Vertices polygon = PolygonTools.CreateRectangle( 2.5f , 1.25f );
List<Vertices> triangulated = FlipcodeDecomposer.ConvexPartition(polygon);
BreakableBody breakableBody = new BreakableBody(triangulated, World, 1);
breakableBody.MainBody.Position = Vector2.Zero;
breakableBody.Strength = 5;
World.AddBreakableBody(breakableBody);

This code turns the rectangle into two pieces (cut from corner to corner).  I have tried four of the five decomposing methods (Flipcode, Bayazit, CDT and Earclip).  I also haven't been able to find any good examples of a rectangle being divided into multiple pieces.

Preferably, I am looking for a way to create random sized pieces, but cutting it into 32 cubes ( 8 x 4 ) would be fine also.


texts:
You can pretty easily read variables, but what about writing them to the lua file?

Ive given it a little go, but it doesnt seem to work...

void Lua::setBool(string path, string var, bool val) { //"Lua" is a class with my Lua functions (such as get bool, get float...)
    lua_State *L = luaL_newstate();
    luaL_openlibs(L);
    if (luaL_dofile(L, path.c_str())) { // For some reason, "!luaL_dofile" triggers if i input the path Correctly
        string msg = "Unable to open file " + path;
        MessageBox(NULL, msg.c_str(), "Lua IO", MB_ICONERROR);
    }

    lua_pushboolean(L, val);
    lua_setglobal(L, var.c_str());

    lua_close(L);
}

And yes, ive inputted "var" and "path" correctly.


texts: How to Iterate thru game object and access scripts by name?

texts:
I'm using a "toggle visibility" script on many objects in my scene, and in my gameController class I'm storing references to them in an array like this:
public Fields[] fields;

then I access them by the array index:
fields[0].setVisibility(true);

This works fine, but this list is growing and everything is getting unmaintainable.
So I would like to iterate thru the references to the objects, find the script by its game object name, and call the required function setVisibility(state).
A call, if possible should look like this:
GameObjectName.ScriptName.FunctionCall.State

In this way, I would have a clear overview of my code.
Is this possible in Unity C#?


texts: Texture organization and budgeting for a HD Sprite Based Game

texts:
I've been making a game that features 2 traditionally animated playable characters, hd backgrounds, props, and extra special effect animations. Things have gone well so far, but I have a few questions regarding HD animated sprites and the use of texture atlasing.

The first: What are some best practices to determine the total texture budget of a modern 2d game? So far, I have considered the following: The characters on their own take up roughly 256 x 256px worth of screen space, but of course that size will vary depending on the intended size of the character. I expect each character to have more than 10 - 12 unique animated sequences. The frames per animation will obviously vary as well depending on the animation length and level of detail. Assuming each animation has about 15 frames, that would mean that a single character's texture atlas could be something around the lines of 3072 x 3072px (or rounding up to the nearest power of two). Two characters would obviously require double the texture size in memory.

Basically, how do I determine if a budget is "acceptable" for modern hardware? How can I tell if it's ok that, at worst, two characters require 6144x6144px worth of memory space?

Secondly: Is it better to load all of our sprite's resources on one huge atlas texture? Or separate textures for each animation? For example, instead of one big "character.tga" file with every animation, you could have "character_idle" and "character_attack" and "character_win" which could be loaded as separate resources. On one hand, it would probably both be slower to load and harder to manage if every animation was a separate texture resource. On the other hand, if you only needed to have a characters "idle" animation, you could choose to only load that animation.


texts: Is there a simple way to stop enemies standing in the same spot?

texts:
So: top-down game, my enemies chase the player, when they get within a certain distance they stand still and fire. If they're all coming from the same direction they all end up standing in the same spot (i.e. standing "within" each other), as I'm not currently doing collision detection between enemies - they are free to pass over each other.

What's a simple way around this? Either some form of collision detection or some ai?


texts:
I'm trying to make a simple pong clone and want the ball to curve when the racket was moving on hit.
To test out curves I removed all the rackets and just have a ball bouncing around in a rectangle, curving in the positive Y direction.

I tried simulating gravity on the Y axis, but the outcome is weird.
The bigger the rectangle, the faster the velocity gets over time.
In a small rectangle, I lose velocity and the ball slows down.

I do the following:
On each tick I check if I should do a curve, if so, then I increase the curve force and add it to the Y velocity (curves only appear on Y)

if (this->DoCurve)
{
    //check if we don't exceed the maximum curve force
    if (this->CurveForce < this->CurveMaxForce)
        this->CurveForce += this->CurveIncrease*delta;

    //add curve force to Y
    this->Velocity += FVector(0.f, this->CurveForce, 0.f) * delta;
}
//move object to new location
SetLocation(this->CurrentLocation + this->Velocity * delta);

When I hit a wall, I want the curve to stop until I hit the next wall.

//if we are already curving, stop it and reset
if (this->DoCurve)
{
    //subtract the force we added to make it move normal again
    this->Velocity -= FVector(0.f, this->CurveForce, 0.f);
    this->CurveForce = 0;
}

this->DoCurve = !this->DoCurve;

//reflect
FVector ReflectedVelocity = (-2 * FVector::DotProduct(this->Velocity, Hit.Normal) * Hit.Normal + this->Velocity);
//ignore Z axis
ReflectedVelocity.Z = 0.f;

//ReflectedVelocity.Normalize(); // this makes the ball stuck in a wall
this->Velocity = ReflectedVelocity;

Basically I have no idea what I'm doing.

What I want:
When the ball hits a racket and it is moving I want the ball to move in a curve fast first, then slow down, like the racket gave it a boost.

My approach is very flawed, what would be the correct way?


texts: AABB swept collision response with voxel world

texts:
I followed this tutorial: link and I was able to make it work with 3d voxel world collisions.

But the problem I have is with collision response. I want to make player slide against the wall if he is running against it, but instead he gets stuck at each voxel edge.

That is happening because I am getting normals with AABB swept test from voxels that are a part of the wall. (Yes, I am doing broadphase check first).

In the image above is 2d representation of my problem. Voxels are black rectangles, blue one is player, red is swept check area and green lines are normals.

Possible solutions I thought of are:
 - Merging voxels into bigger collision boxes based on neighbours, but I think that would cause other problems when holes appear and player size increases.
 - Ignore collision normal if there is neighbour voxel along side normal. This is what I have currently in my code and works fine for sliding against walls while on ground, but fails when falling against them: http://ideone.com/xdsr2d

Because there's many voxels in that are colliding and order of collisions (the order of voxels and normals that I receive after aabb swept test) is hardly predictable neither sollution seams to be good enough.

I would appreciate any help because I've been bashing my head around this problem for quite a while.

(Also if there's anything wrong with my question do tell, this is my first time post on gamedev.stackexchange)


texts: Unity: How is a Mesh Collider "performance expensive"?

texts:
Do Mesh Colliders slow down performance simply by existing or only
when they are colliding?
Do they directly impact FPS or do they slow down the in-game physics?


texts: Unity Applying Global Light Settings fog to a non-main camera

texts: Is it possible to apply fog to a non-main camera?


texts: Moving Windows Mixed Reality main camera in Unity3D programatically

texts:
I'm trying to programmatically move the main camera i.e. player's point of view/origin in a Windows Mixed Reality but for some reason it's not working for me (using newest latest stable Unity 2018 and HoloToolkit through which I've setup my WMR project)...
I've done the following:

m_MainCamera = Camera.main;
m_MainCamera.transform.position.Set(100f, 100f, 100f);
UnityEngine.XR.InputTracking.Recenter();

if (Input.GetKeyDown(KeyCode.A)) happens, but even though the code gets run, my VR view position remains unchanged, and I'm guessing at 0,0,0 (or whatever is set initially)...so how exactly do they do those movements in the WMR's UI cliff house when you use the motion controller to point to place you want to transport your view...do they actually move all of the objects showing instead?

Or am I missing something really trivial when I can't move except for by moving my own body inside of VR? Maybe HoloToolkit is disabling it somehow... But how do I reenable it then to move to a predetermined places within a large life sized 3D model objects please?

TIA


texts:
WP7 textures are supported in the Reach-Profile that WP7 devices falls into. But XNA converts all my ressources upon adding them to a project to RGBA8, that's insane, the displays of WP7 devices are 16 Bit!

Information: WP7 SDK 7.1 (XNA 4), Visual Studio 2010

Question part 1: How can I add a RGB565 texture to a XNA project and what is the correct way to load them inside a game?

Question part 2: Is there a reasonable 16 Bit texture format (within Reach) that supports alpha with MORE than 1Bit?

Question part 3: Is the normal rendertarget (I think that's what the screenbuffer is?) already 16 bit?


texts: In a multiplayer JavaScript game client, is it a good idea to poll the server periodically to refresh online user list, or keep track of joined/left users? Is there a better option?


texts: How to smoothly track and draw player movement?

texts:
I am currently using C# XNA Framework to simply connect some development concepts that I've learned/used over the past few months. Right now I have a Web Service that keeps track of connected clients and their 2D positions. I have a very small map that uses triangles to represent clients and their positions.

What I am seeing is my client updates very smooth (because I update my own position locally before sending it off to the web service), however, other triangles come in and appear choppy.

I use a web service that is called approximately every 20ms (and responds pretty quickly might I add). However, I know that XNA framework calls its update/draw methods approximately 60 times per second correct? Given this, there is ALWAYS going to be the appearance of choppiness.

Is there some strategy or pattern to handling this? I thought about implementing a method on the client side that basically says, give me start position and end position and I'll transition the triangle between the two points smoothly. But this may not be the right answer.

What are folks thoughts?

I am using a NetTcpBinding from WCF (Duplex). Is this technology simply too slow?

Is the right strategy simply to let the Service always tell me where the other clients are and the client simply draws them there?

Or does the client compute other information and make assumptions etc?

Thanks for any information on this topic!


texts: Libgdx - changing tiledmap smoothly, Tween engine maybe?

texts:
First question here, so bare with me if I make a mistake or two. Long story short I'm currently developing a side scroller game in java with libgdx, which uses tiledmaps from the tiledmap creator software. When the player has run for some time the map is automaticly changed to a new one, using some code which looks similar to this:

void changeMap() {
Gdx.app.postRunnable(() -> {
 testMap = new TmxMapLoader().load("someMap.tmx"); renderer.getMap().dispose(); renderer.setMap(testMap);
 }); }

My problem is that the map is changed instantly with no smooth transition at all, like one sec the player is on the old map, the next he starts instantly on the new one, which is quilte unprofessional in My opinion. I would like to create some smooth transition between the two. Maybe just a simple fade in, fade out. Any thing is Better than how it is now.

I have searched google, tried different "solutions" using the tween engine, tried Making a transition screen which first fades in over the playscreen, but when i try to fade back the playscreen is just stoppede etc. I'm really emptied for ideas, so it would be awesome if one of you experts could point me in the right direction. Or maybe Come up with a simple solution. I am experienced with java so any idea here will be apriciated.

This is written from a phone, so sorry for any spelling mistakes.


texts: Rotation based on x coordinate and x velocity?

texts:
-(void) accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration
{

float deceleration = 0.3f, sensitivity = 8.0f, maxVelocity = 150;

// adjust velocity based on current accelerometer acceleration
playerVelocity.x = playerVelocity.x * deceleration + acceleration.x * sensitivity;

// we must limit the maximum velocity of the player sprite, in both directions (positive & negative values)
playerVelocity.x = fmaxf(fminf(playerVelocity.x, maxVelocity), -maxVelocity);

}

Hi, I want to rotate my sprite based on the velocity and accelerometer input. My sprite can move along the X axis like so:

<--------- sprite ----------->

But it always faces forwards, if it is moving left I want it to point slightly to the left, the degree of how far it is pointing to be judged from the velocity. This should also work for the right.

I tried using atan but as the y velocity and position is always the same the function returns 0, which doesn't rotate it at all.

Any ideas?

Regards,

Lewis.


texts: How can I update a sprite sheet without affecting the sprites already being used?

texts:
Every time I overwrite my sprite sheet with additional or updated sprites, I have to reattach the textures to all of my Animations and Sprite Renderers.  How can I update a sprite sheet without affecting the sprites on that sheet which are already being used?

During the development of even a small game, hundreds of textures are being used.  And new textures are being added and updated every day.  This results in many hours spent reattaching textures which could otherwise be used being productive.  What strategy can I use to prevent this?

This is an example of what I mean:

I have a sprite sheet with 40 textures. All of its sprites are attached to their relative GameObjects. I decide I want to change the color of one of my sprites' hat. I go into gimp and load the sprite sheet. I change the color of the hat. I overwrite the old sprite sheet.

Back in Unity, all of the textures are no longer attached to their respective GameObjects. I go in and splice the sprite sheet again and manually reattach all of the textures. Then I decide I like the old hat better. I go back into gimp, change the sprite sheet, and am then forced to reattach all of the textures...again. There has to be a better way! (Also would like to be capable off adding new sprites in addition to editing old ones.)


texts: How to improve this shader's performance?

texts:
I have a scene with 150000 instances. I use glsl and opengl 4.0. Shader A is 2 times slower than shader B. I.e. with shader A I get 20fps, with shader B I get 40fps on average. What can I do to improve shader A?

Shader A:

#version 400

struct Light {
   vec3 position;
   vec3 intensities; //a.k.a the color of the light
   float ambientCoefficient;
   float attenuation;
};

uniform bool useLight;
uniform mat4 modelMatrix;
uniform bool useTex;
uniform sampler2D tex;
uniform Light light;
uniform vec4 diffuseColor;

in vec2 fragTexCoord;
in vec3 fragNormal;
in vec3 fragVert;

out vec4 finalColor;

void main() {
    vec3 normal = normalize(transpose(inverse(mat3(modelMatrix))) * fragNormal);
    vec3 surfacePos = vec3(modelMatrix * vec4(fragVert, 1));

    vec4 surfaceColor = vec4(0,0,0,1);

    if(useTex) {
        surfaceColor = texture(tex, fragTexCoord);
    }
    else {
        //surfaceColor = diffuseColor;
        surfaceColor = vec4(0,1,0,1);
    }

    if(useLight) {
        vec3 surfaceToLight = normalize(light.position - surfacePos);

        //ambient
        vec3 ambient = light.ambientCoefficient * surfaceColor.rgb * light.intensities;

        //diffuse
        float diffuseCoefficient = max(0.0, dot(normal, surfaceToLight));
        vec3 diffuse = diffuseCoefficient * surfaceColor.rgb * light.intensities;

        //attenuation
        float distanceToLight = length(light.position - surfacePos);
        float attenuation = 1.0 / (1.0 + light.attenuation * pow(distanceToLight, 2));

        //linear color (color before gamma correction)
        vec3 linearColor = ambient + attenuation*(diffuse);

        //final color (after gamma correction)
        vec3 gamma = vec3(1.0/2.2);
        finalColor = vec4(pow(linearColor, gamma), surfaceColor.a);
    }
    else {
        finalColor = surfaceColor;
    }
}

Shader B:

#version 400

struct Light {
   vec3 position;
   vec3 intensities; //a.k.a the color of the light
   float ambientCoefficient;
   float attenuation;
};

uniform bool useLight;
uniform mat4 modelMatrix;
uniform bool useTex;
uniform sampler2D tex;
uniform Light light;
uniform vec4 diffuseColor;

in vec2 fragTexCoord;
in vec3 fragNormal;
in vec3 fragVert;

out vec4 finalColor;

void main() {
    finalColor = vec4(0,0,0.7,1);
}


texts: Projection Matrix Causes Clip Cuttoff Problem

texts:
I'm trying to setup my renderer and I'm configuring the matrices. I currently have a View Matrix and a Projection Matrix which I then multiply and send to the shader(there's no need for model matrix since I'm just testing).

The problem is I just can't seem to get the projection matrix right. My model of a sphere appers cut in half in the center of the screen, I can move it around but once the Z value for the transform in the matrix goes beyond 1(Vulkan's max value for NDC) the model cuts off.

This is the code for the view matrix:

ViewMatrix(3, 0) = CamPos.X;
ViewMatrix(3, 1) = -CamPos.Y;
ViewMatrix(3, 2) = CamPos.Z;

The numbers on the left are the rows and those on the right the columns. Matrices are row-major. And my renderer's coordinate system is left handed.

This is the code for the projection matrix:

auto f = 1 / tan_half_fov;

_Matrix(0, 0) = f / _AspectRatio;
_Matrix(1, 1) = -f;
_Matrix(2, 2) = _Far / (_Near - _Far);
_Matrix(2, 3) = -1;
_Matrix(3, 2) = (_Near * _Far) / (_Near - _Far);

The matrix is just an identity matrix and the every frame it gets set those values. tan_half_fov is 0.41421356, since it's tan(45 deg / 2). _Near is 1, and _Far is 500.

The vertex shader:

void main()
{
    gl_Position = inData.Pos * vec4(inPos, 1.0);
}

inPos is the vertex data input for vertex position and inData.Pos is the ViewProjection matrix.

The matrix multiplication code is working alright, I tested it. When sending to the shader just the view matrix the sphere appears all flat on the screen and moves around correctly. I am using Vulkan.

Any help is appreciated!


texts: Get and destroy gameobject component of same type

texts:
I want to destroy any graphic component on a gameobject , example is image,raw image, sprite , ect .But i don't have the list of all graphic component so i don't know how to loop through it . The reason is because i want to replace the component with the same type , for example i want to add Text component , but i can't add it if there is already graphic component attached in the gameobject because there can only be one graphic component in a gameobject , so i need to destroy the graphic component first , how do i do it ?
I personally prefer the answer on c# but any programming language is accepted !


texts: How can I convert THREE JS Texture to WebGL texture

texts: I am a C++ OpenGL programmer trying my hands on Web Developement. I have created Three JS Render Target and rendered my scene to it. The output is correct. Now I have a need to convert output of Render Target i.e THREE.Texture, to WebGLTexture. I don't want to use doElement.toDataURL() or something like that.


texts: What is the revenue split between me and Google in the Play store?

texts: I want to sell an app on the Google Chrome store for $0.50. How much of this will I pocket after Google's cut?


texts:
Hello I've been developing this game for awhile and now trying to implement save data via Json.
I've gotten to where when the app is first launched it will write the Json file with the variables I would like the game to save, but it only writes part of the class that I am passing.

Here is my implementation

@Override
    public void create()
    {

        batch = new SpriteBatch();
        file = Gdx.files.external("/bin/save.json");
        create.setFirstSpawn(true);
        create.setSpawnX(-7);
        create.setSpawnY(417);
        create.setTime(0);
        create.setMap("cabinMap");

        if(!file.exists()) {
            Json json = new Json();

            json.setOutputType(JsonWriter.OutputType.json);
            file.writeString(json.prettyPrint(create), false);

        }
        if (file.exists()) {
            JsonReader jread = new JsonReader();
            JsonValue base = jread.parse(file);
            SpawnX = base.getFloat("SpawnX", -7);
            SpawnY = base.getFloat("SpawnY", 417);
            map = base.getString("map", "cabinMap");
            time = base.getFloat("time", 0);
firstSpawn = base.getBoolean("firstSpawn", true);
        }
        if(map == "cabinMap") {
            this.setScreen(new cabinMap(this));
        }
        if(map == "tMap") {
            this.setScreen(new tMap(this));
        }
        if(map == "lowerTMap") {
            this.setScreen(new lowerTMap(this));
        }
        if(map == "rightTMap") {
            this.setScreen(new rightTMap(this));
        }
        else {
            this.setScreen(new cabinMap(this));
        }
    }

Here is the class that I am passing

public class create
{
    boolean firstSpawn;
    float SpawnX;
    float SpawnY;
    float time;
    String map;

    public void setFirstSpawn(boolean firstSpawn)
    {
        this.firstSpawn = firstSpawn;
    }

    public void setTime(float time)
    {
        this.time = time;
    }

    public float getTime()
    {
        return time;
    }

    public void setMap(String map)
    {
        this.map = map;
    }

    public String getMap()
    {
        return map;
    }

    public boolean isFirstSpawn()
    {
        return firstSpawn;
    }

    public void setSpawnX(float spawnX)
    {
        SpawnX = spawnX;
    }

    public float getSpawnX()
    {
        return SpawnX;
    }

    public void setSpawnY(float spawnY)
    {
        SpawnY = spawnY;
    }

    public float getSpawnY()
    {
        return SpawnY;
    }
}

And this is my result

{
"map": "cabinMap",
"SpawnX": -7,
"SpawnY": 417
}

As you can see from the output file I am missing 2 values.
float time and boolean firstSpawn are missing from the file. I've worked for hours trying to find out why. I have no clue why it omitted part of the code... If anyone knows why that would be very helpful to me.


texts: How do I fix missing anti-aliasing in the Unity scene view and game?

texts:
Both the editor and the game seem to lack anti-aliasing even though quality is set to Ultra.
I chose the "3D" project template when I created the project, so I am using the build-in render pipeline.


texts: What are the differences between random encounters and permanent mobile enemies?

texts:
Random Encounter:

A player has a 10% chance to encounter an enemy. while moving through a 5x5 grid.

Permanent Mobile Enemies:

There is one enemy that constantly moves through the 5x5 grid and only encounters the player when they land on the same grid. Also, both the enemy and the player cannot see each other until they meet.

Obviously, the random encounter will give better performance, but are there any benefits through implementing the second option?


texts: What interface should be responsible for specifying the initial position of a game object?

texts:
I'm making a simple Pong clone game and have been having an issue deciding on how my classes should handle the initial placement of an object.

For instance, my Ball class's constructor is:

Ball (std::string imageName, float screenWidth, float screenHeight)

The constructor then automatically centers the ball in the middle of the screen, since it knows the ball's width and height the dimensions the image it loads, and the screen width and height by the arguments it is passed.

I would rather be able to place the ball manually, and just take the exact x and y locations in the constructor:

Ball (std::string imageName, float x, float y)

But that would require the calling function to already know the ball's width and height in order to center the ball and when it creates a ball it'd have to write something like:

Ball ball("ball.png", ((SCREEN_WIDTH / 2) - (BALL_WIDTH / 2)),
((SCREEN_HEIGHT / 2) - (BALL_HEIGHT / 2)))

I know this may be personal preference, but I'm trying to figure out which way is generally accepted.

A similar issue occurs with my Paddle class. Its constructor argument list looks like this:

Paddle (std::string imageName, float screenWidth, float screenHeight, int player)

Since I set the location inside of the constructor, it's forced me to have a player flag so I know if the paddle is supposed to line up with the left or right hand side of the screen. If I took the exact x and y location in the constructor's argument list, I could figure out which player is which internally using math.

I'm thinking that if the calling function kept consts of all of their objects' widths and heights they could use those in all of their objects' constructors in order to manually set their starting position... but is this the best way to do this?

EDIT:

Now I'm thinking that it would be realistic to expect the calling function to know the center x and center y that it wants the object at, and the object itself can use those x and y coordinates to center itself using its own width and height.

I'm starting to think this may have been a silly question since it really depends on the type of game you're making and how you're using the specific classes. I appreciate any input!


texts: Kinect joint coordinates and XNA animation

texts:
I have written a program to record the x,y,z coordinated of the Hand joint and I want to animate my models 2D or 3D according to these coordinates. . .However the output of the x,y,z coordinates are fluctuating from -0 to 1 but not more than that..

So i assume I will need to multiply them back with the screen width and height, however it still doesnt seem to animate according to the original x,y,z points

Any transformations I might be missing out?

        protected override void Update(GameTime gameTime)
        {

            position += spriteSpeed * (float)gameTime.ElapsedGameTime.TotalSeconds;

            //// TODO: Add your update logic here
            using (StreamReader r = new StreamReader(f))
            {
                string line;
                Viewport view = graphics.GraphicsDevice.Viewport;
                int maxWidth = view.Width;
                int maxHeight = view.Height;

            //    int i = 0;
                while ((line = r.ReadLine()) != null)
                {

                    string[] temp = line.Split(',');

                int x = (int) Math.Floor((float.Parse(temp[0]) * 0.5f) + 0.5f) maxWidth);
              int y = (int) Math.Floor((float.Parse(temp[1]) * -0.5f) + 0.5f) * maxHeight);

                    motion.Add(new Point(x, y));
            //        Console.WriteLine(temp[0] + "," + temp[1] + "," + motion[i].X+ "," + motion[i].Y);
            //        i++;

                }

            }

//            foreach (Point s in motion)
            {

                position.X = motion[i].X;
                position.Y = motion[i].Y;

            }

  //

            i++;

            a_butterfly_up.Update(gameTime);

            a_butterfly_side.Update(gameTime);

            G_vidPlayer.Play(mossV);

            base.Update(gameTime);
        }


texts:
Alright, so I've got hold of some simple physics mechanics, and am currently trying to implement bouncing. Based on the first answer of this question, I've developed the following algorithm:

    Vector2 velocity;

    float gravity;
    float elasticity;

    Hitbox dummy;

    // ---

    void bounce() {
        dummy.MoveY(velocity.Y);
        velocity.Y += gravity;

        if (dummy.ThereWasContact.South) velocity.Y *= -elasticity;
    }

Gravity can be any value, and Elasticity is always between 0.0f and 1.0f. Velocity.Y's initial value can also be anything.

Weight factors aside, which would determine a minimal rebound force for the object to be able to leave the ground again and (probably) aren't related to the problem, this is apparently fallacious.

What happens here is somewhat like this:

If I drop an object from a height of 128 units, for example, 0u marking ground height, with a gravity of 1u and elasticity of 0.9, the object would bounce once, reach a maximum height of ~126u from the rebound, and from then on keep alternating on maximum heights between this and ~122u.

This example is based on one of my own experiments, in which I drop an object from a height of 64 pixels and there is a floor at 192 pixels. The maximum height will keep going from ~66 pixels to ~70.

What am I missing? Does weight after all do more than I think? If I need to explain something better or details appear to be missing, let me know.


texts:
I have about 2+ years of experience in computer gaming development and I just started writing my own shaders to help me utilize performance. I have this problem that I'm trying to work around but after several tries nothing seems to work.

Basically, I have a plane that's made of 16641 vertices - thats 32768 triangles and I know that is pretty much. The plain has a texture on it with some colors. Now, what I am trying to do is placing units on that plane. Where they stand, the vertex under them will have a certain color but all other vertexes on the plain will have the color white. The idea is to discard and don't draw vertexes that aren't white.

Now in the shader, I tried two things.

1 - In the vertex input I check if the vertex, called o, had the o.color.b value != 0. If so it was given the alpha value of 0 and would not be seen when rendering.

2 - In the vertex output, I checked the same thing ( if(i.color.b !=0)
    discard;) and discarded the fragment so it would not be rendered.
    That way I thought Unity should not count these triangles and thus
    wouldn't waste performance.

Now when I run my game and open the stats, with the plane active I have
85.8k triangles and only 28 draw calls. With the plane un-active I have 20.2k triangles and 26 draw calls (Note : there are some units, interface, skies etc around that counts up to 26 draw calls, thus the plane is just 2 draw calls).

I thought this solution would be clever to save draw calls (developing for mobile games) by treating this plane and the colors under the units as one instead of making them all a separate gameobject. Turns out, I'm way over budget on the triangles. Does anyone know if this is possible and if so, give a good answer or explenation?

Here is the following shader.

Shader "Custom/Ottar_VertexBasic" {
Properties {
    _MainTex ("Particle Texture", 2D) = "white" {}
    _Transparency("Transparency", Range(0,1)) = 1
}

SubShader {
    Tags { "Queue" = "Transparent" }
    Blend SrcAlpha OneMinusSrcAlpha
    AlphaTest Greater .01
    ColorMask RGB
    Lighting Off
    ZWrite Off
    //Fog { Color (0,0,0,0) }
    Pass {
        CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag
            #pragma multi_compile_builtin
            #pragma fragmentoption ARB_precision_hint_fastest
            #include "UnityCG.cginc"

            uniform float4  _MainTex_ST;
            float _Transparency;
            //VertexInput
            struct vI {
                float4 vertex : POSITION;
                float4 texcoord : TEXCOORD0;
                float4 color : COLOR;
            };

            uniform sampler2D _MainTex;
            //VertexOutput
            struct vO {
                float4 pos : SV_POSITION;
                float2  uv;
                float4 color;
            };

            vO vert (vI v) {
                vO o;
                o.pos = mul (UNITY_MATRIX_MVP, v.vertex);
                o.uv = TRANSFORM_TEX(v.texcoord, _MainTex);
                float4 viewPos = mul(UNITY_MATRIX_MV, v.vertex);
                o.color = float4(v.color.rgb, v.color.a*1);
                //if(o.color.b != 0) o.color.a = 0;
                //else o.color.a = 1;
                return o;
            }

            float4 frag (vO i) : COLOR {

                if(i.color.b !=0) discard;
                else
                {
                half4 texcol = tex2D( _MainTex, i.uv );
                return texcol*i.color*_Transparency;
                }
            }
        ENDCG
    }
}
Fallback "Particles/Alpha Blended"
}


texts: Culling And Optimization in a 2D Orthographic Game

texts:
I'm currently developing a 2D top-down space themed RTS game. I'm building the space procedurally from a seed. At the end of generation of all space objects, if i don't apply any optimizations I end up with following result (all space objects are visible by camera):

There are stars, planets, satellites as Sprite Renderers in the scene. And orbits of stars and planets as Line Renderers. Planets move around stars, satellites move around planets orbitally. Line Renderers of orbits are controlled and updated dynamically by a script to snap belonging object as it moves around parent orbit.

When i apply following logic to each renderer:

        if (MinVisibleDistance > mainCamSize || mainCamSize > MaxVisibleDistance)
        {
            if (renderer.enabled)
            {
                renderer.enabled = false;
            }
        }
        else
        {
            if (!renderer.enabled)
            {
                renderer.enabled = true;
            }
        }

The results are much more happier (again, all space is visible by camera):

You can see a huge amount of saving in tris and verts count. But the problem with this logic is, even though the object is out of camera view, it gets enabled when camera zooms in. I think the "occlusion culling" option of Unity camera handles this problem, but I'm not sure if it has a performance impact either.

The question is; do this optimizations worth efforts? Or do they make performance even worse by if-else checks every frame and enabling-disabling components?

And are there other optimization ideas you can suggest?

Thanks!


texts:
I'm trying to implement a basic scene graph in DirectX using C++. I am using a left child-right sibling binary tree to do this.
I'm having trouble updating each node's world transformation relative to its parent (and its parent's parent etc.). I'm struggling to get it to work recursively, though I can get it to  work like this:

for(int i = 0; i < NUM_OBJECTS; i++)
{
    // Initialize to identity matrix.
    D3DXMatrixIdentity(&mObject[i].toWorldXForm);

    int k = i;
    while( k != -1 )
    {
        mObject[i].toWorldXForm *= mObject[k].toParentXForm;
        k = mObject[k].parent;
    }
}

toWorldXForm is the object's world transform and toParentXForm is the object's transform relative to the parent. I want to do this using a method within my object class (the code above is in my main class).
This is what I've tried but it doesn't work (only works with nodes 1 generation away from the root)

if (this->sibling != NULL)
    this->sibling->update(toParentXForm);
D3DXMatrixIdentity(&toWorldXForm);
this->toWorldXForm *= this->toParentXForm;
this->toWorldXForm *= toParentXForm;
toParentXForm *= this->toParentXForm;
if (this->child != NULL)
    this->child->update(toParentXForm);

Sorry if I've not been clear, please tell me if there's anything else you need to know. I've no doubt it's merely a silly mistake on my part, hopefully an outside view will be able to spot the problem.


texts: Calculating the angular direction from velocity

texts:
I'm trying to calculate the angular direction of a projectile, knowing it's X and Y velocity I can find the magnitude of its movement, but I'm having a hard time wrapping my mind around getting the angular direction (in radians) that it is moving...

I assume there is a tan or a sin involved, but I'm a bit clueless otherwise...


texts: How can I support a background more complex than a flat color?

texts:
I'm a beginner at making 2D games. Up until now, I always created my games with a black background, or a fixed color. This is because my sprites always have a black (or a solid color) background, and I have to set the background of the game black so the sprites won't be moving around with a black box surrounding them.

Now I want to be able to set the background of the game to an image or texture.

What do I need to do in order to achieve that? Is it possible to design sprites without a background in the first place? Currently if I need a sprite of a guy standing, I would draw the guy on a black rectangle. Is it possible to set the rectangle to be transparent instead of black?


texts:
I'm try to implement client-server communication base on UNET.
The problem i got now is send custom message to server, but the Client.Send always show error without my understanding.
So what i'm wrong? I jus try to implement from scratch, not inherit from NetworkManager.
Here is the code:

using UnityEngine;
using System.Collections;
using UnityEngine.Networking;

public class ZMessageTransfer : NetworkBehaviour
{
    private static ZMessageTransfer instance;
    public static ZMessageTransfer Instance { get { return instance; } }
    NetworkClient m_Client;
    public class MessageType
    {
        public static short Login = 1001;
    };
    public class LoginMessage : MessageBase
    {
        public string username;
        public string password;
    };
    void Awake ()
    {
        instance = this;
    }
    public void SendLoginMessage(string username, string password)
    {
        LoginMessage loginMsg = new LoginMessage();
        loginMsg.username = username;
        loginMsg.password = password;
        m_Client.Send(MessageType.Login,loginMsg);
    }
}

Server:

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

public class ZMatchServer : NetworkBehaviour
{
    public int listenPort;
    public int maxConnection;
    public bool enableNAT;

    public Text currentPlayer;
    public Text currentLog;

    private int onlinePlayer;

    void Start ()
    {
        Network.InitializeSecurity();
        Network.InitializeServer(maxConnection,listenPort,enableNAT);
        NetworkServer.RegisterHandler(ZMessageTransfer.MessageType.Login,OnPlayerLogin);
    }

    void OnPlayerLogin(NetworkMessage netMsg)
    {
        var loginMsg = netMsg.ReadMessage<ZMessageTransfer.LoginMessage>();
        string username = loginMsg.username;
        string password = loginMsg.password;
        currentLog.text = "Player send login " + username + " " + password;
    }

    void OnServerInitialized()
    {
        Debug.Log("Server Initialize completed! ");
        currentLog.text = "Server Initialize completed! ";
    }

    void OnPlayerConnected(NetworkPlayer player)
    {
        onlinePlayer += 1;
        currentPlayer.text = "Current player online : " + onlinePlayer.ToString();
        currentLog.text = "Player connected";
        Debug.Log("Player connected " );
    }

    void OnPlayerDisconnected(NetworkPlayer player)
    {
        onlinePlayer -= 1;
        currentPlayer.text = "Current player online : " + onlinePlayer.ToString();
        currentLog.text = "Player disconnected";
    }
}

Client:

using UnityEngine;
using System.Net;
using System.Collections;
using UnityEngine.Networking;
using UnityEngine.Networking.Types;

public class ZNetworkConnection : NetworkBehaviour
{
    [SerializeField]private string serverURL;
    [SerializeField]private string serverIP;
    [SerializeField]private int serverPort;

    NetworkClient m_Client;

    private static ZNetworkConnection instance;

    public static ZNetworkConnection Instance { get { return instance; } }

    void Awake()
    {
        instance = this;
    }

    void Start ()
    {
        ConnectToServer();
    }
    protected void ConnectToServer()
    {
        Network.Connect(serverIP,serverPort);
    }

    public void LoginToServer(string username,string password)
    {
        ZMessageTransfer.Instance.SendLoginMessage(username,password);
    }

    protected void OnConnectedToServer()
    {
        Debug.Log("Connected to server complete ");
    }
}


texts: Optimize a render call to draw out several semi-transparent sprites

texts:
I'm writing a 2D side-scrolling style game in C++ and openGL. In this game I have several cloud sprites which are rendered across the top of the screen. They rotate and scale and such so they're not static. I'm wondering if there is any way that I can optimize this, because currently every time one of these sprites is rendered, GL has to perform blending between everything already rendered (like the background, etc) and these sprites.

I'm thinking something along the lines of rendering ONLY the clouds together all at once, and then performing a single call where the final result is rendered and blended into the main scene. Not sure how to even go about that or if it will even result in a performance gain. Any suggestions would be greatly appreciated!

Just for clarity, here is what a final render looks like. The clouds are formed by several smaller sprites being populated close together around certain points.


texts:
i want to draw/graph an equation(like sinusoidal signal or any parametric equation) in UE4. I don't know if that is possible. I looked for it but found almost nothing. here is what i found most related and wanted to achieve
https://oliverm-h.blogspot.com/2014/12/ue4-material-graphing-functions.html

the problem is i can't understand how he did it.

Anyone have the idea or any kind of help please?

thanks in advance!!!


texts: Libgdx/Box2D PolygonShape has no position... well, what now?

texts:
As my prototype works perfectly fine I want to advance to more fun areas of the project and add a more complex player-character body.

So for Box2D I figured I'd need multiple fixtures, like one for the legs, one for the torso and one for the head.

Each of these fixtures will get a different sprite/texture that should be swappable dynamically if the player puts on some armour or changes cloths etc.

Until now the player-character consisted of a Box2D Body with just one single fixture.
I added the sprite like this:

   body.setUserData(this.sprite);

I rendered it like this:

 // Draw-method
  if(body.getUserData() != null && body.getUserData() instanceof Sprite) {
      Sprite sprite = (Sprite) body.getUserData();
      sprite.setPosition(body.getPosition().x - sprite.getWidth() / 2, body.getPosition().y - sprite.getHeight() / 2);
      sprite.setRotation(body.getAngle() * MathUtils.radiansToDegrees);
      sprite.draw(spriteBatch);
  }

Now that I want to have multiple sprites for different "regions" of the body I figured it's better to add them to the fixture itself. For now I just wanted to reproduce what I already had, so just the one sprite I have to the one fixture I have right now instead of the body.

I do this like that:

Fixture fixture = body.createFixture(fixtureDef);

My problem arises when trying to render this.

for(Fixture fixture : body.getFixtureList())
{
    if(fixture.getUserData() != null && fixture.getUserData() instanceof Sprite)
    {
        Sprite sprite = (Sprite) fixture.getUserData();
        //sprite.setPosition(fixture.getShape().getPosition() ... // Not gonna work, because PolygonShape has no position! :(
        sprite.draw(spriteBatch);
    }
}

As you can read in the comment, the fixture for now has a rectangular shape which is made like:

shape = new PolygonShape();
shape.setAsBox(widthInMeters / 2, heightInMeters / 2);

The problem is, that a PolygonShape has not position :/ Now when I render this, the sprite is not being drawn at the fixtures position and currently I really have no idea how to fix that.

I'd highly appreciate any help you can give me! Thanks in advance and have a wonderful day! :)


texts: How to make a game where match duration is determined only by skill disparity between the best player and the second best player?

texts:
I want to create a real-time multiplayer game (with a variable number of players, potentially 2-20+, per match) where the match duration is determined only by how much better the best player is compared to the second best player. Thus, 2 properties are required:

Game duration is independent of the number of players. Racing games have this property in that the time it takes for a match to end (which is how long it takes the best player to finish) is independent of how many players are playing. However they don't have the 2nd property.
Game duration is inversely proportional to the skill disparity between the best and second best players - we want close games to last longer than complete stomps. I'm not aware of any game where there is such a strong correlation between match duration and skill disparity that one could say it's the rule. I mean, in Chess, if one is really bad, one could be mated in a few moves, and if two players are close in skill, then games might last really long, but this is not certain. In any case, these games tend to not have the first property.

How might one design a game that has both properties?


texts: So i am trying to scrap together something for vr in which the locomotion is about the player holding the direction where he wants to go to(basically planning what he is going to do)while holding down the button a ray is beeing drawn and when the player lets go the character moves until he reaches the end of the ray i tried looking up something but couldnt find anything regarding something like this


texts:
I want to move car on each game play run with same speed. At present I was getting each time different velocity. I want to fix that.

Here is game play area on which I was moving car:

At present I was moving car in infinite motion without any kind of control. When it collide with wall, it will its direction based on collision calculation.

Here is my source code that I was using to move car:

void Start ()
 {
     direction = new Vector2 (Random.Range (-1f, 1f), Random.Range (-1f, 1f));
 }

 void FixedUpdate ()
 {

     float angle = Mathf.Atan2 (direction.y, direction.x) * Mathf.Rad2Deg;
     float targetRot = Mathf.LerpAngle (myRigidbody.rotation, (angle - 90f), 0.1f);
     myRigidbody.MoveRotation (targetRot);

     myRigidbody.velocity = direction * speed;
//        myRigidbody.MovePosition (myRigidbody.position + direction * Time.deltaTime * speed);

     Debug.Log("vel mag: " + myRigidbody.velocity.magnitude);
 }

 void OnCollisionEnter2D (Collision2D other)
 {
     ContactPoint2D contact;
     contact = other.contacts [0];

//        direction = 2 * (Vector3.Dot(direction, Vector3.Normalize(contact.normal))) * Vector3.Normalize(contact.normal) - direction; //Following formula  v' = 2 * (v . n) * n - v

//        direction *= -1;// Dont know why I had to multiply by -1 but it's inversed otherwisae
     Vector2 reflectedVelocity = Vector2.Reflect(direction, contact.normal);
     direction = reflectedVelocity;
 }

At present on each run of car, I was getting different velocity that I have checked via debug statement. So my target is to move car with same speed always.


texts:
When i want to load texture i can either call
CreateTexture2D without passing pointer to texture content passing Default usage and call UpdateSubResource

or

CreateTexture2D with pointer to texture content passing Immutable or Default as usage.

In first case texture is uploaded to GPU, in seconds case it is also backed to RAM. IIRC it is a so called Managed Pool that help with device loss, but i have hand-made mechanism to handle device loss, i don't want DX to consume pretty big amount of RAM for nothing.

I would be easy to stick with 1st option, but if i call UpdateSubResource from BG thread it sometimes crashes (because it uses ImmediateContext that is used on render thread).

Is there any way to tell DX11 not to copy textures to RAM on CreateTexture2D?


texts: What is the meaning of this "MuxOMX ctor" log in LibGDX?

texts:
I'm developing a game in Java for Android using LibGDX with Android Studio. I'm using the AssetsManager class and I've noticed weird log when finishLoading() is finished:

10-17 22:15:17.108 31943-32282/com.gadarts.parashoot.android I/OMXClient: MuxOMX ctor
10-17 22:15:17.146 31943-32285/com.gadarts.parashoot.android I/OMXClient: MuxOMX ctor
10-17 22:15:17.182 31943-32291/com.gadarts.parashoot.android I/OMXClient: MuxOMX ctor
10-17 22:15:17.231 31943-32296/com.gadarts.parashoot.android I/OMXClient: MuxOMX ctor
10-17 22:15:17.284 31943-32299/com.gadarts.parashoot.android I/OMXClient: MuxOMX ctor
10-17 22:15:17.330 31943-32302/com.gadarts.parashoot.android I/OMXClient: MuxOMX ctor
10-17 22:15:17.385 31943-32309/com.gadarts.parashoot.android I/OMXClient: MuxOMX ctor
10-17 22:15:17.425 31943-32312/com.gadarts.parashoot.android I/OMXClient: MuxOMX ctor
10-17 22:15:17.462 31943-32315/com.gadarts.parashoot.android I/OMXClient: MuxOMX ctor
10-17 22:15:17.499 31943-32318/com.gadarts.parashoot.android I/OMXClient: MuxOMX ctor
10-17 22:15:17.546 31943-32321/com.gadarts.parashoot.android I/OMXClient: MuxOMX ctor
10-17 22:15:17.607 31943-32324/com.gadarts.parashoot.android I/OMXClient: MuxOMX ctor
10-17 22:15:17.654 31943-32327/com.gadarts.parashoot.android I/OMXClient: MuxOMX ctor
    10-17 22:15:17.698 31943-32330/com.gadarts.parashoot.android I/OMXClient: MuxOMX ctor
    10-17 22:15:17.740 31943-32334/com.gadarts.parashoot.android I/OMXClient: MuxOMX ctor
    10-17 22:15:17.782 31943-32339/com.gadarts.parashoot.android I/OMXClient: MuxOMX ctor
    10-17 22:15:17.822 31943-32343/com.gadarts.parashoot.android I/OMXClient: MuxOMX ctor
    10-17 22:15:17.864 31943-32346/com.gadarts.parashoot.android I/OMXClient: MuxOMX ctor
    10-17 22:15:17.911 31943-32353/com.gadarts.parashoot.android I/OMXClient: MuxOMX ctor
    10-17 22:15:17.953 31943-32356/com.gadarts.parashoot.android I/OMXClient: MuxOMX ctor
    10-17 22:15:17.997 31943-32359/com.gadarts.parashoot.android I/OMXClient: MuxOMX ctor
    10-17 22:15:18.043 31943-32362/com.gadarts.parashoot.android I/OMXClient: MuxOMX ctor
    10-17 22:15:18.087 31943-32365/com.gadarts.parashoot.android I/OMXClient: MuxOMX ctor
    10-17 22:15:18.139 31943-32368/com.gadarts.parashoot.android I/OMXClient: MuxOMX ctor
...

Does anybody have any idea what it means? I've searched everywhere and couldn't find anything relevant.
It doesn't make any problem, it just blows my Android Monitor with these logs.

Thanks in advance!


texts: How can I implement revolute (hinge) joints in a 2d physics system?

texts:
Further to my previous question on fixed joints, I am now going toe-to-toe with hinge joints in 2D physics. Though the answer to the previous question was excellent, I have come across a few problems in extending it to hinge joints.

My approach was to extend that given here by implementing the following algorithm:

Find the 'target' point for both hinge points by taking the midpoint between them (I actually use mass to give a ratio here but assume the bodies are of equal mass -- in my simulation they all are). The target point is labelled T in the diagram below.
For body a, find the angle between the hinge point A and the target point T. This is done by transforming T from global space to local  space, then taking the difference of Atan2(y, x) for each point - this should return the angle between them.
The body a is then rotated by a matrix created from this angle, so that A  and T now lie along the same vector. a is then translated by T-A; now A should be at T.
Repeat steps 2 and 3 for body b.

The algorithm seems logical to me, but I have found that there is some kind of stability issue whereby the bodies will stay constrained for a short time, then as the angle between the two bodies becomes slightly more acute (in either direction), they will both shoot off at high velocity. The number of constraint iterations is not the issue as far as I can tell - the same problems occur at 1 iteration as at 10.

Pseudocode to my algorithm given below:

// EntityA and EntityB are the two objects
// HingeA and HingeB are represented as vectors relative to their local transforms
Transform tA = EntityA.Transform;
Transform tB = EntityB.Transform;

Vector2 delta = tA.LocalToGlobal(HingeA) - tB.LocalToGlobal(HingeB);

// Locate the target in global space by finding the midpoint of the delta vector A-B
// then translating it by B
Vector2 Target = (delta * 0.5) + tB.LocalToGlobal(HingeB);

// Locate target in Entity A's local space
Vector2 TargetA = tA.GlobalToLocal(Target);

// Avoid undefined behaviour for Atan2
if (TargetA != Vector2.Zero && HingeA != Vector2.Zero)
{
   // Get the angular difference between A and T
   float angleA = Math.Atan2(TargetA.Y, TargetA.X) - Math.Atan2(HingeA.Y, HingeA.X);
   tA.Angle += angleA;
}

// Re-convert the target to local co-ordinates and translate EntityA towards it
tA.Pos += tA.GlobalToLocal(Target) - HingeA;

// Repeat for entity B...

Am I on the right track with this algorithm? Is there some minor detail I have missed that is aggravating the simulation?


texts: Providing texture coordinates and using indexed drawing at the same time

texts:
Please consider the following vertex structure

struct vertex {
    vec3 posL, normalL;
};

Using this vertex layout, we can provide the vertex data in an interleaved way, i.e. (posL,normalL),(posL',normalL'),...
This works pretty fine in combination with indexed drawing via glDrawElements().

However, if we add texture coordinates to our vertex structure, i.e. consider

struct vertex
{
    vec3 posL, normalL;
    vec2 tex;
};

things get more complicated. Since one and the same vertex (meaning it's position) may participate in a variety of different faces with varying texture coordinates, I wondered how one would provide such vertex data to the vertex buffer.

One solution would be to quit storing the data interleaved and provide it a linear way, i.e. (posL,posL',...),(normalL,normalL',...),(tex,tex',...) where each tuple has the same length. Doing so, we would hold related things together (i.e. the k-th element of each tuple forms exactly one input the vertex shader sees).

But we would push much more data to the pipeline than necessary. So, what's the "ideal" solution to this problem? If one suggests to use different buffers, how does the vertex shader know, that texture coordinate tex at position i in Buffer 2 corresponds to the tuple (posL,normalL) at position j in Buffer 1?


texts: Can I legally remove the default Unity splash screen by removing it from the APK?

texts:
While using Unity I export an Android game as an APK. When the APK is run, the first thing that is displayed is the Unity splash screen. I worked out that I could replaced that image by opening the APK like a zip file, looking for the splash screen image  (App.apk/assests/bin/Data/splash.png) and replacing it with any image I wanted.

Is it legal to publish Unity-powered Android game apps with modified splash screens like this? I remember that some games on PS3, 360 and Wii have been created with Unity but don't display a Unity splash screen when run on their respective consoles.


texts: I'm making a game, and I'm adding a screenshots feature. Currently I save screenshot files to <Home Directory>/Pictures/MyGame/. However, I'm not sure if these files will be accessible on Mobile. On Mobile, I want to save them to the gallery. What's the best way to save screenshots in my game? I am not using a game engine, so using any cross-platform helper functions is completely out of the question. I only have access to built-in libraries like Cocoa on MacOS.


texts: Please help, I am developing a 2D game for a school project and I want to drag the apple to the think box then when it collides, the apple will go back to the original position then it will add 1 point to the score. I'm just new to Unity. So please help


texts: Simplest way to render image over top of another with another image used as mask in OpenGL?

texts:
The effect I'm looking for is to have a single large background image that is always visible (at full alpha) and then show a second image (what I call a light map or specular map) that is partially shown over the top based on a third image (which is effectively a mask).

The effect is similar to this effect except instead of simply darkening or lightening the background image using the third image it needs to mask the second without effecting the first at all.

The third image is the only one that moves therefore hard baking the third images alpha into the second image isn't an option.

If my explanation isn't clear I'll provide visual examples when I have more time.

I'd prefer not to go down a shader route as I haven't taught myself this area yet so unless I have too I'd rather try to achieve this with simple alpha blending.
Happy to use a shader approach.

Cheers.

Additional

These third images are obviously light sources being cast onto the first image showing the specular information from the second image to simulate the light 'shining' off the objects in the first image. The solution I implement will need to allow two light sources to potentially overlap so my current thoughts are that the alpha values of the two images will need to be combined (Added?) to produce a final image which masks the second image?

Don't worry about things like coloured lights. For this technique the lights are all considered white.


texts:
I'm doing a little demo with scene kit and i want to simulate the rotation of a ball on a table. How can i achieve this?
This is the scene that i prepared:


texts: Do higher-level 'Pure AI' concepts (such as Neural-Nets or Genetic Algos) ever get implemented successfully in commercial games?

texts:
Although graphics is my main area of focus, I've been dabbling with Game AI concepts for quite some time now; from simple A* path-finding to intricate Perceptrons..

My question is this; Does anyone have any examples of successful (or perhaps more interestingly, failed) implementations of some higher-level AI concepts in large-scale commercial titles?

By higher-level, I mean methods of simulating intelligence that are usually found in Pure AI.. For example..

Neural Networks
Genetic Algorithms
Decision Theory

I understand that as well as a financial budget, developers also have a budget of memory usage (with AI often taking a back seat). Many of these methods are costly to implement and provide limited returns.. I am just intrigued to find out if anyone knows where or when any of these (or any other high-level concepts that I've forgot to mention) have been deployed in any well-known games :)

I also know that in this industry, trade-secrets are a fact of life ;) Aside from the AAA titles, if you have any of your own success-stories (or disasters) it would be nice to hear them! :D


texts: My game works on the emulator and the PSVita, but crashes on Android

texts:
I made a game on PSM, ported from a previous iOS/Android game. I test it on the emulator and PSVita and runs fine. However, as I test it on a PlayStation Certified Android device, it crashes on load. I'm getting a FileLoadException on the following line:

shaderProgram = new ShaderProgram("/Application/shaders/Render.cgx");

This is my vertex shader:

void main( float4 in spritePosition  : POSITION,
           float2 in textureCoords : TEXCOORD0,
           float4 out gl_Position: POSITION,
           float2 out textureVarying: TEXCOORD0,
           float4 out colorVarying : COLOR0,
           uniform float4x4 projectionMatrix,
           uniform float4 color)
{
    gl_Position = mul(spritePosition, projectionMatrix);
    textureVarying = textureCoords;

    colorVarying = color;
}

and my fragment shader:

void main( float4 in colorVarying : COLOR0,
           float2 in textureVarying: TEXCOORD0,
           float4 out gl_FragColor: COLOR,
           uniform sampler2D spriteTexture: TEXUNIT0)
{
    float4 colorPremultiplied = float4(colorVarying.xyz * colorVarying.w, colorVarying.w);
    gl_FragColor = tex2D(spriteTexture, textureVarying) * colorPremultiplied;
}

What could be causing this problem?


texts: How to return reference from BlueprintImplementableEvent?

texts:
I've got a C++ component and I want to have function which will be implemented in Blueprint like this:

UFUNCTION(BlueprintImplementableEvent)
Stats& GetStats();

But this doesn't compile, I get the following error:

  overload function differs only by return type from

and Unreal generates function inside .gen.cpp looking like this:

Stats Component::GetStats()
{
// ...
}

Stats is USTRUCT


texts: Control diamond square algorithm to generate islands/pangea

texts:
I generated a height map with the diamond square algorithm. The thing is i do not manage to create islands, this is, restrict the height other than water level range to a certain value in the center of the map.

I manualy seeded a circle in the middle of the map but the rest of the map still receives heights over the water level.

I dont fully understand the Perlin noise algorithm so i'd like to work with my current implementation of the diamond square algorithm which took me 3 days to interpret and code in PHP. :P

UPDATE:

I'm trying to get a gradient and its working (it's late and have to refine it, i'll try tomorrow). I tried to work with gradients but silly me, I had been clamping the affected values to a radius, giving me a circle when generating the map.

The seeding option is NOT working. I may get some bigger landmass, but may be located in any sector in the map, not even close to the center.

Please have in mind that the DSA generates the middle value averaging it's corners, so its not possible to seed the middle of a square.

a     b
   f
c     d

f = (a+b+c+d) / 4 + random(-value,value)

Perhaps that's why seeding it's not working.


texts: How to prevent one account from unlocking products on other devices using Apple StoreKit?

texts:
We are currently wrapping up a free-to-play game on iOS in which you can purchase non-consumable products. We have been discussing this case internally and are not quite sure what the best practices are as this is our first title.

For example, if a user downloads our app, and makes some purchases. These can be restored should the app ever be deleted and reinstalled as long as the user uses the same Apple ID. What is to stop him from making a fake Apple account, purchasing items and then posting this account on the web allowing everyone to get the items for free?

That is obviously a worst case situation. But a smaller case would be a user unlocking items for his friends. We do not want this to be an always online game but have considered doing a check on startup if there is internet available. If the currently logged in account doesn't own the products do we lock them again? Probably not because people may simply sign into the device with different Game Center logins at which point we don't want to constantly lock and unlock items.

At some point we will be adding multiplayer at which point we can definately do a check with the currently logged in account. This is because A, they will be online when attempting multiplayer, and B, they will want to use their own account for multiplayer. Unfortunately we aren't quite ready for this yet.

Has anyone tackled this issue. Are we overthinking here?


texts: Comparing analog stick movements to predefined flick shapes

texts:
I want to create a control scheme similar to the EA Skate games, where flicking the right analog stick in various ways makes the character do various tricks:

I record the user input over a set amount of time or until the user moves the analog stick back to its resting position. The recording is a List of Vector2 Coordinates.

Depending on how fast the user flicks the analogue stick, I sometimes get a shorter (15) or longer (45) list of points.

Now I want to compare these lists of points to predefined shapes like the ones in the screenshot, to match which action the player intended to take.

My idea was to use some metric to compare the similarity of the recording to lists of arrays, however, I don't which metric I might use. I found the Hausdorff-Metric and it seems applicable, but I don't know how to implement it.
It might also be an overkill for the problem, so I wanted to ask, how other people would solve the problem.


texts: How can I "capture" the section of my sprite sheet that I want to draw in Java?

texts:
I'm working on a puzzle game, I've implemented a sprite class that uses an array of images and cycle through the array to draw each frame as required.
This works fine!

Here's the original code:

    String number;
    Image sprite;
    ArrayList <ImageIcon> spriteAnimation = new ArrayList();
    int _imageCount = 0;
    int _animationStart = 0;

   public Sprite(String spriteType, int totalFrames){

        for(int x =1; x <= totalFrames; x++){
          spriteAnimation.add(new ImageIcon("Images/" + spriteType + "/" + spriteType + x + ".png"));
          System.out.println("Added " + spriteType + x + ".png to the ArrayList");

        }

    }

    public void updateSprite(){

        sprite = spriteAnimation.get(_imageCount).getImage();

        System.out.println("image count is " + _imageCount);

        if(_imageCount < spriteAnimation.size()-1){

           _imageCount += 1;

       }else{

           _imageCount = _animationStart;

       }

    }

    public Image getSprite(){

      return sprite;

      }
}

However, after researching the difference between using the method above and using a single sprite sheet (there must be a good reason to use a sprite sheet I thought, and I was right) I've decided to use a single sprite sheet to represent all sprites in my game.

While I fully understand the principle of using the sprite sheet, I cannot get my head around actually drawing the selected part of the sprite sheet.
I thought there might be a constructor in the ImageIcon or Image classes that would allow me to do something like pass in the size of the image to be drawn, the x and y co-ordinates to start at and the original sprite sheet as arguments - but apparently not.
I'm obviously looking in the wrong place.

I would be very grateful if someone could advise me on how to do this in Java.


texts: Game engine with good Lua entity creation/management

texts:
I'm looking for an engine that constructs it's entities using Lua or other scripting language. This is in order to find inspiration and do it in my own engine as well.

I know that CryEngine does use Lua to make their entities, but I wanted to know if there are some other alternatives that I can look up.

Thanks!


texts: Pathfinding: grid based map of irregular numbered tiles to mark connections

texts:
Given this map:

The floor tiles are separated from the rest (it's a map made in Tiled in separate layers) and as you can see, the id numbers are not in sequence.

How I would go about making connections from node to node so later the pathfinder can find a path?

The best approach I can think of is to iterate over all tiles (not just the floor ones) and that way the id's can be in sequence, but I want to find a way around this method because there's has to a way that I can't think of right now.


texts:
I've recently encountered a strange problem with my program and I can't seem to fix it. When I try to apply a shader to my SpriteBatch it doesn't change. I've debugged this problem like so:

if (test) {
    System.out.println("Batch shader: " + stage.getBatch().getShader());
    System.out.println("Default shader: " + Assets.getDefaultShader());
    System.out.println("Default batch: " + Assets.SPRITE_BATCH);
    System.out.println("Stage batch: " + stage.getBatch());
}

stage.getBatch().setShader(null);
if (test)
    System.out.println("Batch shader: " + stage.getBatch().getShader()); //Should print null
stage.act();
if (test)
    System.out.println("Batch shader: " + stage.getBatch().getShader());
stage.draw();
if (test)
    System.out.println("Batch shader: " + stage.getBatch().getShader());
test = false;

All of those shaders print the exact same thing, and the batches are also the same (the batches are supposed to be the same). Any ideas why?


texts:
My 2D game has a second camera on the scene that renders an upside down image of the scene and distorts it, giving the effect of water reflection. I render this camera first, and on top of it I render the main camera.

This is working correctly as expected, however, I want to improve it's performance by performing this process in small sections of the scene instead of the whole screen. I created a trigger to detect which items should be turned upside down and rendered.

How can I turn these items and distort them as I did with the whole scene, but only to the GameObjects detected inside the trigger?

Note: I can't assign them to a layer since the layer is already in use.


texts:
I've been trying to understand voxel rendering and have been looking at dual contouring (DC).

So far I understand this much:

Run a density function for a set of grid points (i.e noise function)
Find which edges in the gird contain changes between end-points
From these edges create intersection points (i.e vectors)

Now this is where I'm stuck, next would be to generate normals, but how? When looking at this topic this image normally crops up.

Doing research indicates that the normals would be generated from an isosurface. Is it correct to think that I go from noise to isosurface to normals? If so how would I accomplish each step?

To my understanding, the next step would be the following from the DC paper;

  For each edge that exhibits a sign change, generate a quad connecting the minimizing vertices of the four cubes containing the edge.

Is this quote represented by the above image?

Finally the next step would be to run the QEF with the intersecting points and normals and this would generate my vertex data. Is this correct?


texts: How do I create a 'disable minimap' skill for a StarCraft 2 mod?

texts: I would like to make a "disable minimap" type of skill, which when used will make an area of the minimap black (such that you can't see enemies or allies on the map). How can I accomplish this?