texts: Simple 3D collision detection for general polyhedra

texts:
I have correctly set up a SAT system. I now need to determine a simple, fast, and general purpose collision detection mechanism to identify the collision points. These points will then be used to determine the constraints for Catto's algorithm.

Unfortunately there seems to be a huge set of candidate algorithms, hence my confusion.

My first take would be, given that SAT tells me the candidate triangle-vertex or triangle-triangle for the collision, to perform the following:
- if SAT results in a T-V collision, we are done; collision is at V
- if SAT results in a T-T collision, then the collision points are found by intersecting the vertices of triangle1 with triangle2 and the edges of triangle1 with triangle2

Am I missing something big?


texts: How can I use StringTokenizer instead of array?

texts:
I'm currently redeveloping an OBJ & MTL importer for my game engine. At the moment, I'm focusing on increasing how quickly I can parse large OBJ files.

For now, I can parse about 1.2M vertices, uvs and normals in around 4-6 seconds. Which is awesome, considering the file that I'm parsing, couldn't be parsed originally.

Anyways, on with my question; I want to be able to make the following method use a StringTokenizer instead of String array. The reason is because using String.split is slow and I want to parse the file relatively fast.

private OBJIndex parseIndex(String token)
{
    String[] tokens = token.split("/");

    OBJIndex result = new OBJIndex();
    result.setVertexIndex(Integer.parseInt(tokens[0]) - 1);

    if(tokens.length > 1)
    {
        if(!tokens[1].isEmpty())
        {
            hasUVs = true;
            result.setUvIndex(Integer.parseInt(tokens[1]) - 1);
        }

        if(tokens.length > 2)
        {
            hasNormals = true;
            result.setNormalIndex(Integer.parseInt(tokens[2]) - 1);
        }
    }

    return result;
}

How would I go about doing this?


texts: RGBA values not coming as intended | LibGDX

texts:
As it states, my RGBA values aren't coming out the way I want it to be.
My RBGBA values are
    As it states, I am trying to create a orange tinted color on my game.

221, 189, 98, 0.7

I am using a ShapRenderer called tint, and here is the code:

ShapRenderer tint = new ShapRenderer();
tint.begin(ShapeType.Fill);
tint.setColor(221, 189, 98, 0.4f);
tint.rect(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
tint.end();

I had tried this out in CSS, and it came out with the correct color. But with LibGDX, the game screen is plain white. The opacity (rgb 'A' value) does not have any affect on the tint color.


texts:
I am experiencing a problem with collision detection, an efficiency problem. Right now I want to make it so that my player square stops traveling in the direction of collision into the static object. I followed what a guy did in a tutorial when he checked this type of collision but it's long and hard to understand let alone read. Is there an easier way to tackle this issue?

sf::RectangleShape player;
player.setSize(sf::Vector2f(50, 50));
player.setFillColor(sf::Color::Cyan);
player.setPosition(width / 2, height / 2);

sf::RectangleShape object;
object.setSize(sf::Vector2f(100, 100));
object.setFillColor(sf::Color::Green);
object.setPosition((width / 2) - 200, (height / 2) - 120);

sf::Vector2f velocity(0, 0);
float gravity = .1;

bool jumping = true;

sf::Event event;
while (window.isOpen())
{
    while (window.pollEvent(event))
    {
        if (event.type == sf::Event::Closed)
            window.close();

        if (event.type == sf::Event::KeyPressed)
        {
            if (event.key.code == sf::Keyboard::Space)
            {
                if (jumping == false)
                {
                    velocity.y = -3.5;
                    jumping = true;
                }
            }
            else if (event.key.code == sf::Keyboard::Right)
            {
                velocity.x = 3;
            }
            else if (event.key.code == sf::Keyboard::Left)
            {
                velocity.x = -3;
            }
        }
    }

    //Move the player
    player.move(velocity);

    //Gravity

    if (player.getPosition().y < height / 2)
    {
        velocity.y += gravity;
    }
    else if (player.getPosition().y >= height / 2)
    {
        player.setPosition(player.getPosition().x, height / 2);
        jumping = false;
    }

    //Check collision with object
    sf::FloatRect player_boundingBox = player.getGlobalBounds();

    if (player_boundingBox.intersects(object.getGlobalBounds()) && player.getPosition().y + 50 < object.getPosition().y + 5 && player.getPosition().y + 50 > object.getPosition().y && player.getPosition().y < object.getPosition().y)
    {
        player.setPosition(player.getPosition().x, object.getPosition().y - 50);
    }
    else if (player_boundingBox.intersects(object.getGlobalBounds()) && player.getPosition().x > object.getPosition().x + 90 && player.getPosition().x < object.getPosition().x + 99)
    {
        player.setPosition(object.getPosition().x + 100, player.getPosition().y);
        velocity.x = 0;
    }
    else if (player_boundingBox.intersects(object.getGlobalBounds()) && player.getPosition().x + 50 < object.getPosition().x + 10 && player.getPosition().x + 50 > object.getPosition().x)
    {
        player.setPosition(object.getPosition().x - 50, player.getPosition().y);
        velocity.x = 0;
    }
    else if (player_boundingBox.intersects(object.getGlobalBounds()) && player.getPosition().y > object.getPosition().y + 97 && player.getPosition().y < object.getPosition().y + 99)
    {
        player.setPosition(player.getPosition().x, object.getPosition().y + 100);
        velocity.y = 0;
    }

    window.clear(sf::Color::White); //Clear

    window.draw(player);
    window.draw(object);

    window.display(); //Display
}


texts:
Does CharacterController benefit from adding lerp?

as in this script.

mouse = Input.GetAxis("Mouse X");
current = Mathf.Lerp(current, mouse, Time.deltaTime * 10);
transform.Rotate(0, current * 600 * Time.deltaTime, 0);

I was using,

transform.Rotate(0, mouse * 18, 0);

But read into the idea of lerp and wrote that.


texts:
A useful list of AI middleware.  Please provide URL, free/open-source or licenced, and brief description of abilites.

Format:

*Package* (License)
Link

Pros

Cons


texts: Why do we need a fourth coordinate to divide by z?

texts:
I read the response here:

What does the graphics card do with the fourth element of a vector as the final position?

  "The fourth component is a trick to keep track of perspective
  projection. When you do a perspective projection, you want to divide
  by z: x' = x/z, y' = y/z, but this isn't an operation that can be
  implemented by a 3x3 matrix operating on a vector of x, y, z. The
  trick that has become standard for doing this is to append a fourth
  coordinate, w, and declare that x, y, z will always be divided by w
  after all transformations are applied and before rasterization. "

but I didn't understand why couldn't we divide by z using a 3x3 matrix?

can't we just multiply by

1/z 0 0
0 1/z 0
0 0 1/z

to get [x/z y/z 1]

?


texts: How to animate a destruction of a model?

texts:
I have a model (see image) and I am trying to animate a destruction.

But it doesn't seem possible, since XNA is using only bones to animate.
So my question is:

Which workflow should I use, to animate 4 independent objects (being one big model), which lie on top of each other?

Regarding this model:


texts: How can I apply a shader to images in a map in XNA?

texts: Basically, what I'm trying to do is apply a shader to my background image and only the background image. The problem is: the background is actually made up of tiles that are picked out of a list of images. The background code loads and draws the tiles according to a map (an int[,].) I've been reading up on using RenderTarget2d, but I haven't found anything that suggests I'd be able to use specific images (let alone images set up according to a map.) So here's my question: is there a way to render my backgrounds to a texture so I can apply a shader or is there another way for me to apply a shader that I might want to try?


texts: How to increase or decrease the speed of a gameObject after solving a puzzle?

texts:
I am new to unity development and I am trying to make a script where the game player needs to solve puzzles to keep an object moving. How can I make the player increase/decrease this velocity after solving a challenge? Thanks in advance.

Edit 1

I just started with this code to control a Sphere using the arrows:

public class PlayerController : MonoBehaviour {

public float speed;

private Rigidbody rb;

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

void FixedUpdate ()
{
    float moveHorizontal = Input.GetAxis ("Horizontal");
    float moveVertical = Input.GetAxis ("Vertical");

    Vector3 movement = new Vector3 (moveHorizontal, 0.0f, moveVertical);

    rb.AddForce (movement * speed);
}

I am thinking to try a method like velocityIncrease that will act after a condition statement like isPuzzleSolved. My intention is to handle the Sphere after getting some points during the puzzle. It will keeps the ball rolling until it reach its goal. My screen will be divided on a field where the ball stays and on the bottom of the screen I need to put an area for the puzzle solving. Thanks to reply.


texts: Is this a good way to "get rid of the sprite shakes" for my sprites that "target" other sprites? (XNA)

texts:
I'm relatively new to XNA, but very proficient with C#. I want to know if this is the best way to solve the sprite shaking problem. I had a sprite class that can target a place/other sprite on the map and follow it.

Here's my update method:

public override void Update(GameTime gameTime)
    {
        //move this rectangle closer to the target
        float EntitySpeed = 100f; //this is actually a property
        Vector2 velocity = new Vector2();
        if (_target.GetX() < this.GetX())
            velocity += new Vector2(-1, 0) * EntitySpeed;
        if (_target.GetX() > this.GetX())
            velocity += new Vector2(1, 0) * EntitySpeed;
        if (_target.GetY() < this.GetY())
            velocity += new Vector2(0, -1) * EntitySpeed;
        if (_target.GetY() > this.GetY())
            velocity += new Vector2(0, 1) * EntitySpeed;

        //a guy on pluralsight said it's best to update velocity taking a time into consideration to account for faster/slower computer speeds
        var movement = (velocity * (float)gameTime.ElapsedGameTime.TotalSeconds);
        _position += movement; //position is a Vector2

        //is the code below a good solution to get the sprite to stop shaking?
        //if we're "close" to the target sprite, then set the position exactly
        Vector2 vectorDiff = this._position - new Vector2(_target.GetX(), _target.GetY());

        bool xReached = Math.Abs(vectorDiff.X) <= Math.Abs(movement.X);
        bool yReached = Math.Abs(vectorDiff.Y) <= Math.Abs(movement.Y);

        if (xReached)
            _position.X = _target.GetX();
        if (yReached)
            _position.Y = _target.GetY();

    }


texts: Why aren't my 2D primitives visible using a custom effect?

texts:
I'm working with Monogame and rendering a triangle using the following code.

vertices = new []
{
    new VertexPositionColor(new Vector3(100, 200, 0), Color.White),
    new VertexPositionColor(new Vector3(200, 100, 0), Color.White),
    new VertexPositionColor(new Vector3(300, 200, 0), Color.White),
};

graphicsDevice.DrawUserPrimitives(PrimitiveType.TriangleList, vertices, 0, 1);

Ordinarily I'd apply a BasicEffect before the draw call, but this time I'm using a custom effect. For testing, I wrote the following shader code to return solid green for each pixel within the triangle.

struct VertexShaderInput
{
    float4 Position : POSITION;
    float4 Color : COLOR;
};

struct VertexShaderOutput
{
    float4 Position : POSITION;
    float4 Color : COLOR;
};

VertexShaderOutput VertexShaderFunction(VertexShaderInput input)
{
    VertexShaderOutput output;
    output.Color = input.Color;
    output.Position = input.Position;

    return output;
}

float4 PixelShaderFunction(VertexShaderOutput input) : COLOR
{
    return float4(0, 1, 0, 1);
}

technique Technique0
{
    pass Pass0
    {
        VertexShader = compile vs_4_0_level_9_1 VertexShaderFunction();
        PixelShader = compile ps_4_0_level_9_1 PixelShaderFunction();
    }
};

The problem is that, although the shader compiles successfully, nothing shows up.

Why is my triangle invisible using this shader?

Based on my understanding of vertex and pixel shaders, the above HLSL code should work correctly. In the vertex shader, since (for the moment) I'm working in strictly 2D without a camera, no transformations need to be done on the vertices (i.e. they're already in screen space). From there, the pixel shader simply returns solid green for each pixel. I've also ruled out potential backface culling issues by swapping the order of vertices, and I've tried using different semantics on my HLSL structure variables. No luck.

Shaders still feel uncomfortable to me, but I feel my logic is correct based on what I've read. If that's the case, there must be some weird quirk I'm not aware of in having these HLSL shaders work at all, apart from the logic. What am I missing? Is there a better way to debug these problems short of changing random variables and hoping for the best?


texts:
I want to limit the creation of objects acording to the stage width.

My method is the following:

for (var i:int = 0; i<7; i++){

If I put something like this, it won't work

for (var i:int = 0; i<(stage.width); i++){

What I'm doing wrong?

Full code:

    [SWF(width = 350, height = 600, frameRate = 60)]
import com.actionsnippet.qbox.*;
var sim:QuickBox2D = new QuickBox2D(this);
sim.createStageWalls();
// make a heavy circle
sim.addCircle({x:3, y:3, radius:0.4, density:1});
// create a few platforms

// make 26 dominoes
for (var i:int = 0; i<7; i++){
//End
     sim.addCircle({x:1 + i * 1.5, y:18, radius:0.1, density:0});
     sim.addCircle({x:2 + i * 1.5, y:17, radius:0.1, density:0});
     sim.addCircle({x:1 + i * 1.5, y:16, radius:0.1, density:0});
     sim.addCircle({x:2 + i * 1.5, y:15, radius:0.1, density:0});

//Mid end

      sim.addCircle({x:0 + i * 2, y:14, radius:0.1, density:0});
      sim.addCircle({x:0 + i * 2, y:13, radius:0.1, density:0});
      sim.addCircle({x:0 + i * 2, y:12, radius:0.1, density:0});
      sim.addCircle({x:0 + i * 2, y:11, radius:0.1, density:0});
      sim.addCircle({x:0 + i * 2, y:10, radius:0.1, density:0});

}
sim.start();
sim.mouseDrag();


texts:
I'm developing a little 2D game using OpenGL 4.x and I've also coded a very simple light system which does not take care of shadows.
The main concept behind this light system is the frambuffer multiplicative blending. I basically have two framebuffers, one for the normal scene render and the other one for ambient light and the scene light sources. Then, I blend those two framebuffers and I get my final result (which is pretty good, to be honest).

In this model I have 3 different shader programs:

One for rendering the normal scene (with texturing and other normal features)
One for rendering lights, which compute light halos and other light effects
One for blending the two framebuffers together

Now, in my main application loop I have to switch between those three shader programs in order to complete a full rendering cycle. I'm also planning to add more shaders to render different light effects and particles.
At the moment I'm in the design phase of my game, so I'm not able to test out the performance of this approach and I have no previous experience with it.
And for the same reason I'd like to start with the best approach possibile for this situation.

So my question is: considering your experience, is switching between several shader programs at each frame something good or is it a bad behaviour in a 2D enviroment ? Is using fewer shader programs but with more if statement and more unused uniform variables a better solution?


texts: How do I inline images between text in a Table?

texts:
I have a Table and a Label with wrapped text.
I want to display some images in-line with the text. For example:

  This is an image -IMAGE_HERE-, and now some more text showing, yet, another image -IMAGE_HERE-.

I tried using one Label containing all the text and spaces for the images, then draw the sprites. However, I can't get the locations I should draw the sprite in to fill those spaces. I could hard-code the values, but they'll vary per device. I also tried adding multiple labels with images between, but that didn't work out either.

Is there a way of fixing this, say by calculating words' widths? Is it possible to have text with inline images in a Table?

if you are wondering why I'm using a Table: The Label text should fit on screen regardless of device resolution. I've found a Table helps with this: I just set bounds and size and it works.


texts: Fade a texture effect as it nears the end of a cylinder mesh

texts:
In my game I have a laser beam that travels for about 15m, but abruptly stops due to the mesh the texture is attached to. How can I setup my shader graph so that the end of the texture fades away? I can't find anything similar to this anywhere online, and have tried multiple things (gradient/colors with lerp attached to alpha) but just can't figure it out as I'm too new to the whole shader graph thing. Anything helps, thank you.
Note: The texture is 'animated' and scrolls along the path of the beam using the shader graph


texts: How does making of games using game engines happen?

texts:
I am a complete beginner to game programming. I have decided to give a try on UDK game engine. I have some simple doubts. I searched Google for the answers but couldn't get my doubts cleared.

This is what I have understood about a game engine:
    They are used to reduce our workload by doing the jobs which are common in games. They abstract the complex level and give us a more easier layer to work with. So when using a game engine we can concentrate on our game logic and the engine will do those complex but common tasks.
    I understand that game engines are built over APIs like OpenGL.

Now the doubt comes:
How do we make OUR game from a game engine?
Does every game engine provide a API through which we can interact with it and get our game from it?

I thought of analogy. This may not be a real analogy. Suppose we are building a house. The engine provides as a skeleton of a house in which the common works like foundations and walls which are common to all houses are given. Now we want to put a window of our choice into the house skeleton. We interact Through the API and find the position or hole where we can put our window which was made externally. Does this analogy make sense???
Is UnrealScript The language used to use the API provided by UDK so that our "Window" can be inserted to the "House"?


texts:
I am trying to use Unity's shader graph to create this old tv effect:

I thought about using a noise node, and somehow randomize the noise's seed.

Can anyone help me?


texts:
I'm learning DirectX12 and I'm trying to create a simple application that clears the screen with a solid color, but I'm stuck in Direct3D initialization. I can't create the swap chain and the DXGI factory returns a nullptr. This is my initialization code:

bool Game::InitializeD3D()
{
ID3D12Debug *debug;
D3D12GetDebugInterface(IID_PPV_ARGS(&debug));
debug->EnableDebugLayer();

// hardware result returned by functions
HRESULT hr;

// create device
hr = D3D12CreateDevice(nullptr, D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&mDevice));
if (FAILED(hr))
    MessageBox(0, L"device creation failed", L"error", MB_OK);

// create fence
mDevice->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&mFence));

// query descriptor size
mRTVDescriptorSize = mDevice->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV);
mDSVDescriptorSize = mDevice->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_DSV);
mCBVSRVDescriptorSize = mDevice->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV);

// check for 4X MSAA quality level support
D3D12_FEATURE_DATA_MULTISAMPLE_QUALITY_LEVELS MSAAQuality;
MSAAQuality.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
MSAAQuality.Flags = D3D12_MULTISAMPLE_QUALITY_LEVELS_FLAG_NONE;
MSAAQuality.NumQualityLevels = 0;
MSAAQuality.SampleCount = 4;
mDevice->CheckFeatureSupport(D3D12_FEATURE_MULTISAMPLE_QUALITY_LEVELS, &MSAAQuality, sizeof MSAAQuality);
mMSAAQualityLevels = MSAAQuality.NumQualityLevels;

// create command queue
D3D12_COMMAND_QUEUE_DESC commandQueueDesc = {};
commandQueueDesc.Type = D3D12_COMMAND_LIST_TYPE_DIRECT;
commandQueueDesc.Flags = D3D12_COMMAND_QUEUE_FLAG_NONE;
hr = mDevice->CreateCommandQueue(&commandQueueDesc, IID_PPV_ARGS(&mCommandQueue));
if (FAILED(hr))
    MessageBox(0, L"command queue creation failed", L"Error", MB_OK);

// create command allocator
mDevice->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&mCommandAllocator));

// create main command list
mDevice->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, mCommandAllocator, nullptr, IID_PPV_ARGS(&mCommandList));
static_cast<ID3D12GraphicsCommandList*>(mCommandList)->Close();

// create the swap chain
DXGI_MODE_DESC mode = {};
mode.Width = mWindowWidth;
mode.Height = mWindowHeight;
mode.Format = mBackBufferFormat;
mode.RefreshRate.Numerator = 60;  // 60 Hz refresh rate
mode.RefreshRate.Denominator = 1;
mode.Scaling = DXGI_MODE_SCALING_UNSPECIFIED;
mode.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED;
DXGI_SWAP_CHAIN_DESC swapChainDesc = {};
swapChainDesc.BufferCount = bufferCount; // double buffering
swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
swapChainDesc.BufferDesc = mode;
swapChainDesc.OutputWindow = mWindow;
swapChainDesc.SampleDesc.Count = 4; // 4X MSAA
swapChainDesc.SampleDesc.Quality = mMSAAQualityLevels - 1;
swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_FLIP_DISCARD;
swapChainDesc.Windowed = true;
swapChainDesc.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH;

hr = CreateDXGIFactory1(IID_PPV_ARGS(&mFactory));
if (FAILED(hr))
    MessageBox(0, L"factory creation failed", L"Error", MB_OK);

hr = mFactory->CreateSwapChain(mCommandQueue, &swapChainDesc, &mSwapChain);
if (FAILED(hr))
    MessageBox(0, L"swap chain creation failed", L"Error", MB_OK);

// more init code
......

My main window is created and the message box appears saying that the swap chain creation failed and Visual Studio raises an access violation exception.
What am I doing wrong?


texts:
I downloaded and installed Unity3D Personal edition on my Windows 10 computer and first time I launched it I couldn't help but notice that text looks really bad across all UI elements (buttons, dropdowns, preferences, etc) except system menus, as if anti-aliasing is turned off everywhere.

I couldn't find any settings related to this in Preferences. Is it GUI font customizable in Unity?


texts: How can I increase the tileset limit in RPG Maker VX?

texts:
In RPG Maker VX, the default setup allows you to have five tilesets for the map layout.
Is there a way I can increase this limit?

I know it's possible to make "fake" tiles by using events overlaid on the real tiles to show different images. However, this is a huge hassle to setup, and isn't a very clean way of creating the game; I'm hoping there is another way.


texts: In AGK2 Basic, how would I attach a camera to the player charater?

texts:
I've started making a game in AppGameKit and I'm using Tier 1/AGK2 Basic. I'm trying to make a sort of endless runner. I've made it so that the player stays still and the rest of the world moves around them to create the illusion that the player is what is running forward. I then use a global variable to control all movement relative to the player.

There must be a better way to do this, though. Like if I were to attach a camera to my player character. How would I do something like that?


texts: What are the advantages of putting cheat codes into a game?

texts:
Some games have cheat codes in them, but I'm not sure I want to add some to mine because I fear they'll ruin the game by making it too easy to beat.

What would be the advantages of putting cheat codes into my game?


texts:
I have a sprite sheet that contains a character walk cycle, and I have made a player class that allows the player to move and cycle through the walk animation, however the animation only works whilst walking to the right. I use the arrow keys to move up, down, left and right, meaning when I press any key, my player moves in the correct direction, but only performs the animation of walking to the right.

The current animation that works, has been called like this in the LoadContent() function:

spritesheet = Content.Load<Texture2D>("sprites2");

player = new Player(spritesheet, new Rectangle(0, 96, 32, 48),
new Vector2(100, 100), 4);

This does its job, as it calls each 4 sprites to complete the walking animation to the right, and new Rectangle(0,96,32,48) is the location cut out from the sprite sheet. However I need (for example) new Rectangle(30, 101, 65, 52) to be used also, which will correctly animate my character when the left arrow key has been pressed.

My question is, how would I get another location of the sprite sheet loaded, and then actually work when I press the correct key?

This is a very difficult question to ask and I very much apologize if it was difficult to understand. Accepting all edits to my question, and thank you in advanced.


texts: Adding underwater shadow to 2D top down boat

texts:
I have a boat/hovercraft sprite in my game. It's topdown 2D view, but it's actually a 3D scene, for better lighting and other effects.
I want to add a buoyancy effect, so that the hovercraft floats with the waves and has a little margin for going under water, like a real boat. So when idle or when going off a ramp, when landing in the water it will kinda "bounce" a bit under and then back up.
But the problem is: the water and boat sprites are on top of each other (because it's 2D). See this picture:

So it can not go underwater, because then the water will be on top. But I still want those edges of the vehicle to be a bit darker as it floats. I already have an effect that changes the Y value to make it float up and down. But now the edges have to become a bit darker to show they go underwater.

I kinda have this idea to add a 3D capsule and make it move up and down through the sprite to simulate this:

So as the boat and the capsule go down with each wave, it could mask the sprite, and the visible part (marked with black lines in the image below) could be made darker. To simulate the "under water" effect. Later I will also add foam and stuff, but the first problem is the underwater part. So how could I mask my sprite inside this capsule, and more importantly, make the "outsides" (so the parts of the sprite not touching the capsule darker? Any help would be greatly appreciated! :)


texts: Are there any methods for generating rivers on-demand with Perlin/Simplex noise?

texts:
I'm aware of many methods for procedurally generating rivers, but they require an entire heightmap beforehand in order to work. For instance, they may require to find a high position on the map and find a path to the ocean.

But when working with on-demand / on-the-fly procedural generation (generating the map around the player as he moves), those requirements are unfeasible. For instance, Minecraft doesn't have "true rivers":

  the river does not in fact have a start and end point, it is actually just dividing the two biomes, this means that it uses the distance between the point and the edge of the biome to determine how deep the water should be, with some variance of course.

This mod seems to solve the issue, but how? Probably it takes advantage of the fact that entire chunks are generated and thus is not entirely on-demand per position.

So, the question is: how can I generate rivers procedurally on-demand? More preciselly, I want a function f(x, y) which tells me whether there is a river at (x,y) or not (and its flow direction). It seems pretty unsolvable for me, but maybe people have come with some solution.


texts: Can someone explain to me how setting shader parameters aren't a bottleneck?

texts: I am trying to understand this.  So I have a bunch of models that need to be rendered.  Each model most likely has various "sub meshes" with their own diffuse, specular, etc textures.  So for each of these models I have to loop through set the diffuse, specular, etc and then a draw call.  Now lets say I do this a couple times for each model, and I have 100 models in a scene.  Since my C++ code that sets these per model parameters is called by the CPU, doesn't it have to bus all that data to the GPU a ridiculous amount of times.  Even if it doesn't and the GPU is caching, wouldn't the CPU still need to make several inquires to make sure the correct resources are cached?  I am asking because I have a, single, high res model I am rendering and once textures are applied I drop from 1000 FPS to 70.  This model has about 20 different textures, and isn't something that will be used in a game, solely using it to stress test and locate bottlenecks. Thanks!


texts: Moving one object from one point to another with acceleration

texts:
How would someone implement moving an object from one point in 2D space to another using these formulae to update objects:

m_position.setX/Y( m_position.X/Y() + m_velocity.X/Y() * dt + 0.5 * m_acc * pow(dt,2);
m_velocity.setX/Y(m_velocity.X/Y() + m_acc * dt);

I'm trying to make a pong clone and I'm having some trouble programming the AI paddle to go to the y coordinate where the ball will hit. (the y coord is predicted in a function).

Currently I have it so that it applies an acceleration of 1 until half the distance then an acceleration of -1 after it, but naturally it is overshooting by a lot, then trying to go back, etc.


texts: How can I reflect a point with respect to the plane?

texts:
How can I reflect a point with respect to a plane?

Example:

I have three points (0,0,2), (4,0,0) and (0,8,0). And I have a point (x,y,z). From these, I want derive a composite transformation matrix. How can I do that?


texts: How can I remove a sprite from the screen using pygame?

texts:
I am having trouble with removing sprites on my screen using pygame.

I am killing my sprite with sword.kill which is removing it from an all_sprites group, so it should disappear right?

Here is where i blit my images:

def draw(self):
        for sprite in self.all_sprites:
            self.screen.blit(sprite.image, self.camera.apply(sprite))
        pg.display.update()

Here is my sword class:

class Sword(pg.sprite.Sprite):
    def __init__(self, game, x, y, entity):
        self.groups = game.all_sprites
        pg.sprite.Sprite.__init__(self, self.groups)
        self.game = game
        self.image = self.game.sword
        #self.image = pg.transform.scale(self.image, (TILESIZE, TILESIZE))
        self.image.set_colorkey(WHITE)
        self.rect = self.image.get_rect()
        self.x = x
        self.y = y
        self.rect.x = x
        self.rect.y = y
        if entity.direction == 'down':
            self.image = pg.transform.rotate(self.image, -90)

        def update(self):
            self.kill()

And here is where I create my sword object:

def get_keys(self):
        self.vx, self.vy = 0, 0
        keys = pg.key.get_pressed()
        if keys[pg.K_LEFT] or keys[pg.K_a]:
            self.game.walk_sound.play(-1)
            now = pg.time.get_ticks()
            self.vx = -200
            self.direction = 'left'
            if now - self.last_update > self.frame_rate:
               self.last_update = now
               try:
                    self.game.player_img = self.game.walkleft[self.frame]
                    self.frame += 1
               except IndexError:
                    self.frame = 0
            self.swing = False
        elif keys[pg.K_RIGHT] or keys[pg.K_d]:
            self.game.walk_sound.play(-1)
            now = pg.time.get_ticks()
            self.vx = 200
            self.direction = 'right'
            if now - self.last_update > self.frame_rate:
               self.last_update = now
               try:
                    self.game.player_img = self.game.walkright[self.frame]
                    self.frame += 1
               except IndexError:
                    self.frame = 0
            self.swing = False
        elif keys[pg.K_UP] or keys[pg.K_w]:
            self.game.walk_sound.play(-1)
            now = pg.time.get_ticks()
            self.vy = -200
            self.direction = 'up'
            if now - self.last_update > self.frame_rate:
               self.last_update = now
               try:
                    self.game.player_img = self.game.walkup[self.frame]
                    self.frame += 1
               except IndexError:
                    self.frame = 0
            self.swing = False
        elif keys[pg.K_DOWN] or keys[pg.K_s]:

            self.game.walk_sound.play(-1)
            now = pg.time.get_ticks()
            self.direction = 'down'
            self.vy = 200
            if now - self.last_update > self.frame_rate:
               self.last_update = now
               try:
                    self.game.player_img = self.game.walkdown[self.frame]
                    self.frame += 1
               except IndexError:
                    self.frame = 0
            self.swing = False
        elif keys[pg.K_SPACE]:
            self.attack = True
            if self.direction == 'down':
                print(self.rect.centery)
                self.sword = Sword(self.game, self.rect.centerx-7, self.rect.bottom, self)
        elif self.vx != 0 and self.vy != 0:
            self.vx *= 0.7071
            self.vy *= 0.7071
            self.swing = False
        elif keys[pg.K_t]:
            self.x = 1 * TILESIZE
            self.y = 1 * TILESIZE
            self.swing = False
        elif self.attack and not keys[pg.K_SPACE]:
            self.sword.update()
            self.attack = False

Any help would be appreciated. Thanks!


texts: Fit entire screeen whn Aspect Ratio Change Unity

texts:
i'll try to explain what i have...
my "field" camera with this script (used to keep the aspetct)
using UnityEngine;

[RequireComponent(typeof(Camera))]
public class CameraCrop : MonoBehaviour {
// Set this to your target aspect ratio, eg. (16, 9) or (4, 3).
public Vector2 targetAspect = new Vector2(16, 9);
Camera _camera;

void Start () {
    _camera = GetComponent<Camera>();
    UpdateCrop();
}

// Call this method if your window size or target aspect change.
public void UpdateCrop() {
    // Determine ratios of screen/window & target, respectively.
    float screenRatio = Screen.width / (float)Screen.height;
    float targetRatio = targetAspect.x / targetAspect.y;

    if(Mathf.Approximately(screenRatio, targetRatio)) {
        // Screen or window is the target aspect ratio: use the whole area.
        _camera.rect = new Rect(0, 0, 1, 1);
    }
    else if(screenRatio > targetRatio) {
        // Screen or window is wider than the target: pillarbox.
        float normalizedWidth = targetRatio / screenRatio;
        float barThickness = (1f - normalizedWidth)/2f;
        _camera.rect = new Rect(barThickness, 0, normalizedWidth, 1);
    }
    else {
        // Screen or window is narrower than the target: letterbox.
        float normalizedHeight = screenRatio / targetRatio;
        float barThickness = (1f - normalizedHeight) / 2f;
        _camera.rect = new Rect(0, barThickness, 1, normalizedHeight);
    }
}

}
and one more camera inside my canvas used to who 3d character on UI and a background image ( used to show a screenshot got from the field camera) so what i have on my ui is 3d model with a background spriterenderer with a screenshot texture got from "field" camera ( using rendertexture )
on cap1 is what i have on my "field" camera then i take a screenshot and on cap2 is what i have after i get a screenshot with the rendertexture then convert it to a texture2d and create a new sprite from that texture ( to a sprite render inside the canvas camera)
so as you can see the screenshot doesn't fit the entire screen, without the above script it does fit perfectly.
this is what i do to resize it
    void ResizeSpriteToScreen()
{
    SpriteRenderer sr = sprite.GetComponent<SpriteRenderer>();

    sprite.transform.position = _myCamera.transform.position + Vector3.forward * sr.transform.position.z;

    sprite.transform.localScale = new Vector3(1, 1, 1);
    Vector3 lossyScale = sprite.transform.lossyScale;

    float width = sr.sprite.bounds.size.x;
    float height = sr.sprite.bounds.size.y;

    float worldScreenHeight = _myCamera.orthographicSize * 2f;
    float worldScreenWidth = worldScreenHeight / Screen.height * Screen.width;

    Vector3 xWidth = sprite.transform.localScale;
    xWidth.x = worldScreenWidth / width;
    sprite.transform.localScale = xWidth;
    //transform.localScale.x = worldScreenWidth / width;
    Vector3 yHeight = sprite.transform.localScale;
    yHeight.y = worldScreenHeight / height;
    sprite.transform.localScale = yHeight;

    Vector3 newLocalScale = new Vector3(transform.localScale.x / lossyScale.x,
        sprite.transform.localScale.y / lossyScale.y,
        sprite.transform.localScale.z / lossyScale.z
    );

    sprite.transform.localScale = newLocalScale;
}


texts: How to iterate through members of lists of members of lists within members of previous lists?

texts:
I'm sorry for the clumsy title, and for what will be the continuation of further clumsiness in my question - I'm not even sure how to properly ask this, so please allow me to illustrate:

I'm writing a game using XNA and C#.

I have 'nodes' in 2d space, and I'm trying to create a network of nodes representing traverse-able world-space.

The nodes themselves store a list of their 'neighbors', and an associated dictionary that refer to how an AI might travel from one node to a node's neighbor, either by walking, or jumping.

I'm trying to find a way that I may iterate from the list of one node's neighbors, to its neighbor's neighbors, to its neighbor's neighbor's neighbors, etc. etc. etc., to test each for contiguous neighboring connections based on whether or not they are all reachable to each other by 'Walk' (so I can find whole walkable platform segments).


texts: What is the best method to use to write and handle multiple levels?

texts:
I have a level class that does all of the updating and drawing and everything pertaining to the level.  My question is, what would be the best approach to creating different levels?  Should I just write them all in this single class which just chooses what to load and do depending on the level, or should I write each level in its own class that inherits from a base level class?

My code handles switching levels through the game's state manager...

void Game::change(GAMESTATE changeTo) {
  state = changeTo;
  load(state);
}

void Game::load(GAMESTATE loadState) {
  while(!currentState.empty()) {
    delete currentState.back();
    currentState.pop_back();
  }
  if(state == TITLE) {
    currentState.push_back(new Title());
  }
  else if(state == LEVEL) {
    currentState.push_back(new Level(&levelNumber));
  }
  else if(state == CUTSCENE) {
    currentState.push_back(new Cutscene());
  }
  else if(state == GAMEOVER) {
    currentState.push_back(new GameOver());
  }
}

[edit] For this question, let's assume I want to hard code the levels and don't want to use external files.


texts:
I'm about to pick up computer graphics once again for an university project. For a previous project I used a library called FTGL that didn't leave me quite satisfied as it felt kind of heavy (I tried lots of rendering techniques, text rendering didn't scale very well).

My question is, is there a good and efficient library for this? If not, what would be the way to implement fast but nice looking text? Some intended uses are:

Floating object/character labels
Dialogues
Menus
HUD

EDIT: Preferably it could also load fonts


texts: PBR Metalness Implementation: specColor at Value 1?

texts:
I am doing a BRDF supporting the metalness/roughness workflow.
I know that in cases of Metalness = 1.0 the reflectance value is taken from the albedo map - so is the specular color to tint the highlights.

My question is if the specular color is taken at the same value that it is in the albedo or is it set to 1.0 first and then used ?

Example:

A Pixel in my Albedo Map has a  Hue/Sat/Value of 0.5/0.5/0.5

With metalness = 1 the reflectance is 0.5.

Is specColor

a) 0.5/0.5/0.5
b) 0.5/0.5/1.0 (to not dim the specular) ?

Thanks,
Jens


texts: What does the "random element" do in Cellular Automata

texts:
I'm reading this post on TutsPlus regarding procedural level generation using cellular automata. My question arises in this code snippet:

float chanceToStartAlive = 0.45f;

public boolean[][] initialiseMap(boolean[][] map){
    for(int x=0; x<width; x++){
        for(int y=0; y<height; y++){
            if(random() < chanceToStartAlive){
                map[x][y] = true;
            }
        }
    }
    return map;
}

In the first line, the author declares a float that represents 45%. This makes sense. However, the role of this is unclear to me. In this line:

if(random() < chanceToStartAlive)

A random number is being generated, and being tested if it's less than 0.45f. Since it is an inequality, this expression can either return true or false correct?

How exactly is this percentage affecting this loop?

Thank you!


texts: Optimising a bool spread on a 2D Grid/List

texts:
I'm trying to work out a more efficient way of spreading a bool flag across a 2D tilemap, as the way I currently have it setup works, but has to run far too many times to work properly.  This isn't a massive performance problem as the code doesn't run every tick, but it's still annoying as there must be a better way!  Hopefully somebody on here can help...

At present, the game code grabs a map XML file and deserialises it into a List of "mapsquares" (simple little class that holds all the info about that square in memory, so it can be modified).  This works great for most of what I want to do, but is causing an issue with "power spreading".

Each square that contains a building uses a powered/notpowered bool, with the idea that power spreads from the station along power lines to other buildings.  If it's connected to the grid, it's powered.

However, trying to get this working properly is proving messy, I've already followed the advice on here and generated neighbouring tile co-ordinates for every square when first loading the map file, this is used for exploration, but I thought it would also do power spreading.

It kinda works:

public void RegeneratePower()
    {
        MapSquare msnsq = new MapSquare(0, Vector2.Zero);
        MapSquare msssq = new MapSquare(0, Vector2.Zero);
        MapSquare msesq = new MapSquare(0, Vector2.Zero);
        MapSquare mswsq = new MapSquare(0, Vector2.Zero);

        foreach (MapSquare ms in mapSquares)
        {
            if (ms.HasBuilding)
            {
                Vector2 msn = ms.North;
                Vector2 mss = ms.South;
                Vector2 mse = ms.East;
                Vector2 msw = ms.West;

                foreach (MapSquare msa in mapSquares)
                {
                    if (msa.Location == ms.North) msnsq = msa;
                    if (msa.Location == ms.South) msssq = msa;
                    if (msa.Location == ms.East) msesq = msa;
                    if (msa.Location == ms.West) mswsq = msa;
                }

                if (msnsq.HasPower || msssq.HasPower || msesq.HasPower || mswsq.HasPower) ms.HasPower = true;

            }
        }
    }

However, it has to be run multiple times to actually spread the power more than 1 square at a time - theoretically I might have to run it as many times as the length or height of the map to ensure it covers everything :(.  I thought about using the .Reverse() command to change the List order, or using a different kind of construct instead of a list.  What would be the best way of doing this?

Thanks.


texts: Unreal Engine Niagara Write to Texture or Data Structure

texts:
In the Niagara system, is there any way to write to a texture? I want to write the position of each particle into a texture. So the 2d grayscale texture has its intensity as the number of particles in the pixel.

Or, is there any data structure that I can use to store the particle positions? Something like 2d or 3d array?


texts: How to design a damage formula in an RPG which keeps weapons with different attack speeds balanced?

texts:
I'm making a mobile rpg game, an infinite one where there is a loot system like Diablo 3. Weapons have attack and speed, armor pieces have a resistance value (not percentage).

The formula I'm using is:

float realDamage = SkillDmg * BaseDamage / ( BaseDamage + Defense )

The results are good, the damage gets bigger if the defense gets lower and it doesn't exponentially go up because of the division between ( BaseDamage + Defense ).

Lets say I have a sword with 1.0 attack speed that deals 50 damage. Thats 50 dps, and I have a dagger that I want it to attack faster, but of course deal less damage, to maintain the dps the logic says that if the daggers attack speed is doubled, the damage needs to be halfed (2.0 speed with 25 dmg ). But using the formula above you'll see that the actual real damage DPS is lower than the sword.

Iv'e solved this by making the dagger not do 25 damage but a bit more, doing some calculations I can make the real dps be the same to balance things. In this case the dagger at 2.0 speed would need to deal 32 damage to be the same real damage dps as the sword.

However, I want to display the DPS number on weapons. If I just display the daggers DPS as 32 dmg * 2 attackspeed it's going to be 64 dps, compared to the sword 50 dps, one will clearly say that the dagger is better, but of course it's not.

Possible solutions? Change the initial damage formula? If so to which one? Lets assume I don't change the formula, is there any solution? I really don't like having to trick the dagger to deal more damage than half to make it even...

I'd really wish I'd know the damage formula for diablo 3. I know that diablo 3 weapons DPS it's simply base damage * attack speed.

Edit:

Lets assume defense = 50 and normal attack (skillDmg = baseDmg)

Sword 1.0 attack speed dealing 50 dmg -> real damage hit=  50 * 50 / ( 50 + 50 ) = **25 dmg** = 25 dps

Dagger 2.0 attack speed dealing 32 dmg -> real damage hit = 32 * 32 / ( 32 + 50 ) = **12.5 dmg** = 25 dps

Sword item, lets display the actual sword dps, 50 * 1.0 = **50 dps**
Dagger item, lets display the dagger dps, 32 * 2.0 = **64 dps** (SHOULD BE THE SAME)


texts:
When I run my program I keep getting: MissingComponentException: There is no 'TextMesh' attached to the "Can" game object, but a script is trying to access it.Even though I have attached it as you can see:

In the script I am trying to edit the text of the Text Mesh like this¨:

private int count;
public TextMesh countText;

// Use this for initialization
void Start () {

    count = 0;
    counterText = gameObject.GetComponent<TextMesh>();
    counterText.text = "Count: " + count.ToString();

}

What I want is to count the cans that have been shot, so what I do next is:

  void OnCollisionEnter(Collider other)
{
    if (other.gameObject.CompareTag("Can"))
    {
        other.gameObject.SetActive(false);
        count = count + 1;
        counterText.text = "Count: " + count.ToString();
    }
}


texts: Game Maker 8.0 - Can I simulate any collision event within the step event of an object including the "other" reference?

texts:
Let's say I have two objects. One is "obj_wall" and the other is "obj_player". For the sake of argument, let us assume that I cannot just add a collision event to obj_wall (I truly cannot due to limitations embedded within the nature of the project itself).

Is there a function or block that allows one to write a collision event within obj_wall's step event? I know there are various collision detection functions, but what I need is one that acts identically to the collision event and allows me to access the "other" property. If this is not possible, are there any suitable alternatives (such as a function that detects collision and returns the instance_id of an object colliding the wall)?

My primary issue here is that I want to be able to use collision in one instance of an object without having to have the collision event added. I'd prefer it to be as close as possible to the collision event so as to avoid unnecessary extra checks.


texts: Copy location/rotation information in Unity

texts:
I place a cube in my level (scaled along one axis) and start doing something else.

Then I place another cube, but want to copy and paste the location and rotation data from the first cube onto this new one.

So far I'm doing that by copying & pasting 6 numbers one by one. Is there a faster way to clone the location/rotation of an object (eg. with a single key press)?


texts: Moving pac-man in maze game using objective c

texts:
I am trying to develop maze game using objective-c, I want to allow moving the pac-man using swipe method, the user can swipe his fingers on the iPhone to indicate where he want PAC-MAN to go but I'm stuck on moving pac_man.
I used UIPanGesture but it can't indicate the collision of ghosts?

Please see the bellow code:

- (IBAction)pacmanmovement:(UIPanGestureRecognizer *)sender {
    CGPoint netTranslation;
    CGPoint translatedPoint = [(UIPanGestureRecognizer*)sender translationInView:self.pacman];

    sender.view.transform = CGAffineTransformMakeTranslation(
        netTranslation.x +  translatedPoint.x,
        netTranslation.y += translatedPoint.y);

    if ([(UIPanGestureRecognizer*)sender state] == UIGestureRecognizerStateEnded) {
        netTranslation.x += translatedPoint.x;
        netTranslation.y += translatedPoint.y;
    }

    [self collisionWithGhosts];
}

- (void)collisionWithGhosts {

    CALayer *ghostLayer1 = [self.ghost1.layer presentationLayer];
    CALayer *ghostLayer2 = [self.ghost2.layer presentationLayer];
    CALayer *ghostLayer3 = [self.ghost3.layer presentationLayer];
    CALayer *ghostLayer4 = [self.ghost4.layer presentationLayer];

    if (CGRectIntersectsRect(self.pacman.frame, ghostLayer1.frame)
        || CGRectIntersectsRect(self.pacman.frame, ghostLayer2.frame)
        || CGRectIntersectsRect(self.pacman.frame, ghostLayer3.frame)
        || CGRectIntersectsRect(self.pacman.frame, ghostLayer4.frame) ) {

        self.currentPoint  = CGPointMake(0, 144);
    }

Any help?


texts: Need efficient way to keep enemy from getting hit multiple times by same source

texts:
My game's a simple 2D one, but this probably applies to many types of scenarios.

Suppose my player has a sword, or a gun that shoots a projectile that can pass through and hit multiple enemies.

While the sword is swinging, there is a duration where I am checking for the sword making contact with any enemy on every frame.  But once an enemy is hit by that sword, I don't want him to continue getting hit over and over as the sword follows through. (I do want the sword to continue checking whether it is hitting other enemies.)

I've thought of a couple different approaches (below), but they don't seem like good ones to me. I'm looking for a way that doesn't force cross-referencing (I don't want the enemy to have to send a message back to the sword/projectile). And I'd like to avoid generating/resetting multiple array lists with every attack.

Each time the sword swings it generates a unique id (maybe by just incrementing a global static long). Every enemy keeps a list of id's of swipes or projectiles that have already hit them, so the enemy knows not to get hurt by something multiple times. Downside is that every enemy may have a big list to compare to. So projectiles and sword swipes would have to broadcast their end-of-life to all enemies and cause a search and remove on every enemy's array list. Seems kind of slow.
Each sword swipe or projectile keeps its own list of enemies that it has already hit so it knows not to apply damage. Downsides: Have to generate a new list (probably pull from a pool and clear one) every time a sword is swung or a projectile shot. Also, this breaks down modularity, because now the sword has to send a message to the enemy, and the enemy has to send a message back to the sword. Seems to me that two-way streets like this are a great way to create very difficult-to-find bugs.


texts:
I create a C # script in which I declare a transformation:
public Transform Origin;

When I put this script on an object of the hierarchy, in the Inspector a field Origin appears at the level of the script in which I have to drag and drop a transformation of a GameObject or a GameObject.

How does the Origin transformation deal with the GameObject transformation to move in this field?

Thank you for your help


texts: AndEngine Making Chase Camera Follow Player

texts:
I am playing around with the AndEngine Race Game example.  I am trying to make the camera follow the car as the player moves around.  The Tile Map is larger than the player's screen but the camera does not follow the car when it moves.

Here's my code:

this.mScene = new Scene();
//this.mScene.setBackground(new Background(0, 0, 0));

/** Tiled Map Test **/
try {
    final TMXLoader tmxLoader = new TMXLoader(this.getAssets(), this.mEngine.getTextureManager(), TextureOptions.BILINEAR_PREMULTIPLYALPHA,
            this.getVertexBufferObjectManager(), new ITMXTilePropertiesListener() {
        @Override
        public void onTMXTileWithPropertiesCreated(final TMXTiledMap pTMXTiledMap, final TMXLayer pTMXLayer, final TMXTile pTMXTile,
                final TMXProperties<TMXTileProperty> pTMXTileProperties) {
            /* We are going to count the tiles that have the property "box=true" or "boxBool=true" set. */
            if(pTMXTileProperties.containsTMXProperty("box", "true")) {
                SpeedsterGameActivity.this.numBoxes++;
            }
        }
    });
    // Load the TMX file into an Object
    this.mTMXTiledMap = tmxLoader.loadFromAsset("tmx/level3.tmx");
            this.runOnUiThread(new Runnable() {
        @Override
        public void run() {
            Toast.makeText( SpeedsterGameActivity.this, "Box count in this TMXTiledMap: " + SpeedsterGameActivity.this.numBoxes, Toast.LENGTH_LONG).show();
        }
    });
} catch (final TMXLoadException e) {
    Debug.e(e);
}

// Get the first TMX Layer and add it to the scene
final TMXLayer tmxLayer = this.mTMXTiledMap.getTMXLayers().get(0);
this.mScene.attachChild(tmxLayer);
        /* Make the camera not exceed the bounds of the TMXEntity. */
this.mBoundChaseCamera.setBounds(0, 0, tmxLayer.getHeight(), tmxLayer.getWidth());
this.mBoundChaseCamera.setBoundsEnabled(true);

/* Debugging stuff */
Debug.i( "Game Info", "Height & Width: " + tmxLayer.getHeight() + " x " + tmxLayer.getWidth() );

int[] maxTextureSize = new int[1];
GLES20.glGetIntegerv( GLES20.GL_MAX_TEXTURE_SIZE, maxTextureSize, 0);
Debug.i("Game Info", "Max texture size = " + maxTextureSize[0]);
/**********/
        /* Calculate the coordinates for the face, so its centered on the camera. */        final float centerX = (CAMERA_WIDTH - this.mVehiclesTextureRegion.getWidth()) / 2;
final float centerY = (CAMERA_HEIGHT - this.mVehiclesTextureRegion.getHeight()) / 2;
        /* Create the sprite and add it to the scene. */
final AnimatedSprite player = new AnimatedSprite(centerX, centerY, this.mVehiclesTextureRegion, this.getVertexBufferObjectManager());
this.mBoundChaseCamera.setChaseEntity(player);
/********************/

this.mPhysicsWorld = new FixedStepPhysicsWorld(30, new Vector2(0, 0), false, 8, 1);


texts: What are the parameters for btHingeConstraint::setLimit?

texts:
What does each parameter in btHingeConstraint::setLimit do to the hinge constraint?

void btHingeConstraint::setLimit    (   btScalar    low,
        btScalar    high,
        btScalar    _softness = 0.9f,
        btScalar    _biasFactor = 0.3f,
        btScalar    _relaxationFactor = 1.0f
    )


texts: Calculating the rotational force of a 2D sprite

texts:
I am wondering if someone has an elegant way of calculating the following scenario.

I have an object of (n) number of squares, random shapes, but we will pretend they are all rectangles.

We are dealing with no gravity, so consider the object in space, from a top down perspective.  I am applying a force to the object at a specific square (as illustrated below).

How do I calculate the rotational angle, based on the force being applied, at the location being applied.  If applied in the center square, it would go straight.  How should it behave the further I move from the center?  How do I calculate the rotational velocity?


texts: How can I make player move on array of GameObjects in Unity?

texts:
I am making a board game where the players hit a dice and move on an array of GameObjects according to the number they got.

So I declared a Gameobject array and added to it all the objects I need.

The problem is that when the player moves, he is going immediately to the target.

What I want is to make the player move through the Gameobject array, object by object, till it reaches the target(which is defined according to the dice number).

Here is what I am trying (using C#):

for(int i=0;i<spaces.Length;i++)
{
    transform.position = Vector3.MoveTowards(transform.position,
    spaces[currentPosition+diceResult].transform.position,Time.deltaTime / smooth );
}

spaces is the name of GameObject[] array.

currentPosition is the position of player before hitting the dice.

diceResult is the number he got in the dice.

EDIT :

I solved it!

Here is how it worked:

 if (index < spaces.Length)
 {
       transform.position = Vector3.MoveTowards(transform.position,
       spaces[index].transform.position, Time.deltaTime *smooth);

       //If we've reached the destination, move to the next one
       if (transform.position == spaces[index].transform.position)
            index++;
 }


texts: What program generates character sprite sheets like this?

texts:
I see template sprites like this a lot but cant find what program creates them.

To clarify I am looking for the program or generator that is creating the characters not laying them out. I've seen the same character as fat, skinny, and short which makes me think its just being generated by a program for reference.


texts: How do I set the size of a single 'unit' in my game?

texts:
I'm currently trying to remake/port an old game created on Unreal Engine 2.5 to my own engine, and I have access to its physics data. It's using a scale of 80 units per meter, or 1 unit = 1.25cm.
The walk speed value for example is 5, and physics is simulated at 60 FPS, so the walking speed I need to implement would be 3.75 meters per second.
But I don't exactly know what the size of a game engine's "unit" actually means. I of course want my own engine (I'm using C++, OpenGL, and GLM) to use this same scale, but I'm not sure how to go about that. I'd assume this affects not only physics/movement code, but the scale of models and maps I load in as well, so it's important to make sure it's the same as in the original game.
How would I implement this? What parts of a game does the size of a 'unit' affect and how? Just the physics and movement calculations, or the graphics side as well (matrices, clipping space, FOV, etc.)?
(I'm not sure if I'm overthinking things)


texts:
People have asked questions on fast pixel manipulation, but I'm looking to read the RGB color values of each pixel.

I've heard of SDL_RenderReadPixels but in the docs it says:

  WARNING: This is a very slow operation, and should not be used frequently.

Is there an SDL2 function that returns an array of all the pixels of a texture or an SDL2 routine that I can use to loop over each pixel?


texts: I need to replace the sprite at runtime Unity 2d

texts:
I need a help, I have some code in Unity that should replace the player's sprite at runtime. But this code does not make it correctly, it does't make the change. Could you help me? Thanks

using UnityEngine;
using System.Collections;

public class PlayerBehavior : MonoBehaviour {

  public enum Skins
  {
    normal,
    verde
  }

  private Skins skinAtual;

  private Rigidbody2D player;
  public float height;
  private Transform posicao;
  public float jumpForce = 10f;
  private AudioSource audio;
  public DeathMenu deathMenu;
  private float initialX;
  public float goBackSpeed = 10f;
  Object[] BGMusics;
  //private SpriteRenderer sprite;

  public SpriteRenderer[] sprites;

  public Sprite skinVerde, skinNormal;

  void Start () {

    //skinAtual = Skins.normal;
    skinAtual = Skins.verde;
    //sprite = GetComponent<SpriteRenderer> ();
    player = GetComponent<Rigidbody2D> ();
    BGMusics = Resources.LoadAll ("Music/BG");
    initialX = transform.position.x;

    //skinVerde = Resources.Load<Sprite> ("Sprites/BOYrECORTADOvERDE");
    skinVerde = Resources.Load<Sprite> ("Sprites/PersonagemFatiado_verde");
    skinNormal = Resources.Load<Sprite> ("Sprites/PersonagemFatiado");

  }

  private void UpdateSkin(Sprite novaSprite)
  {
    foreach (var item in sprites) {
      item.sprite = novaSprite;
    }
  }

  void Update ()
  {

    switch (skinAtual) {

    case Skins.normal:
      UpdateSkin (skinNormal);
      break;
    case Skins.verde:
      UpdateSkin (skinVerde);
      break;
    default:
      break;
    }

    if (Input.GetKeyDown (KeyCode.Escape))
      Pause.INSTANCE.Pausing ();

    if (Pause.isPaused)
      return;

    if (Application.isEditor)
      inputComputer ();
    else if(Application.isMobilePlatform)
      inputMobile ();

    FixePosition ();
  }

  void FixePosition()
  {
    if (transform.position.x <= initialX) return;

    var newPX = Mathf.Lerp (transform.position.x, initialX, Time.deltaTime * goBackSpeed);
    transform.position = new Vector3 (newPX, transform.position.y);

  }

  private void inputMobile(){
    if(Input.GetMouseButtonDown(0))
      playerJump ();
  }

  private void inputComputer(){

    if(Input.GetKeyDown(KeyCode.Space))
      playerJump ();
  }

  private void playerJump(){
    if (player.transform.position.y <= -8.93000f )
    {
      player.AddForce (new Vector2 (0, height * jumpForce), ForceMode2D.Impulse);
      MusicManager.INSTANCE.JumpSound ();
    }
  }

  void PlayRandom(){
    int i = Random.Range(0, BGMusics.Length); // index sortido
    AudioClip m = (AudioClip) BGMusics[i]; // uma referencia ao audioclip sortido
    GetComponent<AudioSource>().PlayOneShot(m); // tocamos esse audioclip
  }

  void Reset(){
    GetComponent<AudioSource>().playOnAwake = false; // aqui tira o play on awake do audio source
  }

  // CONFIGURANDO OS TRIGGERS E SUAS ACOES
  void OnTriggerEnter2D(Collider2D col)
  {
    if(col.gameObject.CompareTag("Heart"))
    {
      Score.INSTANCE.AddPoints ();
      col.gameObject.SetActive (false);
      Handheld.Vibrate ();
      //TOCAR
      PlayRandom ();

    }
    else
    {
      if (col.gameObject.tag == "Doctor")
      {
        MusicManager.INSTANCE.DeathSong ();
        player.gameObject.SetActive (false);
        Handheld.Vibrate ();
        ToggleEndMenu();
      }
    }

  }

  void ToggleEndMenu()
  {
    deathMenu.ToggleEndMenu (Score.INSTANCE.GetScore ()); //Send to DeathMenu the Score value
  }
}


texts: Problem getting in adjust the image in drawable canvas

texts:
I am working on the game which i develop on android and i am just stuck on adjust the images. I want the spinning ball image in center where i targeted the red color on the given image and the both bottom left and right player images on yellow mark on the given images.

Here is the some code i used for dice and the player :-

Dice :-

dice.get(0).setPosition((gWidth + dice.get(0).getWidth()) / 300,
                    (gHeight + dice.get(0).getHeight()))

Player 1 and player 2 :-

male = BitmapFactory.decodeResource(getResources(), R.drawable.male);
    canvas.drawBitmap(male, 0, canvas.getHeight() - male.getHeight(), null);
    female = BitmapFactory.decodeResource(getResources(), R.drawable.female);
    canvas.drawBitmap(female, canvas.getWidth() - female.getWidth(), canvas.getHeight() - female.getHeight(), paint);


texts: Can I make my sprite design very similar to Pokémon's sprite design?

texts:
I'm making a 2d RPG and I'm having trouble designing a sprite, so I downloaded an image of Pokémon Leaf Green's player sprite and copied how it looked. I didn't copy it completely, only how it looks. Here's the image:

Can I get sued for this? the gameplay and mechanics are far from Pokémon's mechanics, the only problem is the sprite of the characters. Can I get into trouble because the character sprite looks too much like Pokémon's character?


texts:
I want to make game more realistic, for that I need a city. So, I decided to take New York City, as it can be seen through Google Maps with Street View, 3d view and much more and will help me a lot to make realistic game.

So, my simple question is: Can I use the whole New York City in my game and publish it commercially?


texts: How can I increase framerate, when drawing tiles to a HTML canvas?

texts:
I am using the HTML 5 canvas to make a simple platformer game. I am currently drawing the tiles using a for loop that runs through a list of tiles and checks if they will be drawn to the screen.

for (var i = 0; i < tiles.length; i++) {
    if (tiles[i].x + scale > pos.x - (canvas.width / 2)
            && tiles[i].x < (pos.x + scale) + (canvas.width)) {
        canvas.drawImage(tiles[i].x - pos.x, tiles[i].y - pos.y, scale, scale,
                "img/Tiles/" + tiles[i].Tile + ".png")
    }
}

I am also using this custom library to draw the image to the screen:

this.drawImage = function(x, y, width, height, src, alpha) {
    if (alpha) {
        ctx.globalAlpha = alpha
    }

    if (document.getElementById(src) == undefined) {
        document.head.innerHTML
                += ''
    }

    var img = document.getElementById(src)
    ctx.drawImage(img, x, y, width, height);
    ctx.globalAlpha = 1.0
    document.getElementById(src).outerHTML = ""
}

When I run the for loop, the frame rate of the game seems to drop. Is there an alternate option to going through every element of the array that I'm not aware of?


texts: How to check in single event if two objects are clicked at the same time in libGDX?

texts:
I am newbie to libGDX and I have written two functions for touchdown,

    LockerKeyHalfImage.addListener(new InputListener() {
        public boolean touchDown (InputEvent event, float x, float y, int pointer, int button) {
            System.out.println("clickrd Locker>>>>>>>>");
              return false;
        }
        });

    MasterKeyHalfImage.addListener(new InputListener() {
        public boolean touchDown (InputEvent event, float x, float y, int pointer, int button) {
            System.out.println("clickrd Master>>>>>>>>");
              return false;
        }
});

My problem is to check if these two images are clicked at the same time (multi-touch detection). I tried to use the following lines without success:

 InputMultiplexer im = new InputMultiplexer();
      //  GestureDetector gd = new GestureDetector(ui);
         //   im.addProcessor(gd);
            im.addProcessor(ui);
            Gdx.input.setInputProcessor(im);

Can anyone point me in the right direction?


texts: Simple switch to instanced draws causes consistent, but incorrect, results

texts:
I have dumbed the following code down to "stupid simple" for DirectX and still cannot get any cooperation:

g_d3dContext->OMSetRenderTargets(1, g_renderTargetWorld->ColorRenderTargetView.GetAddressOf(), g_depthStencilView.Get());
g_d3dContext->OMSetDepthStencilState(g_States->DepthNone(), 0);
g_d3dContext->OMSetBlendState(g_States->AlphaBlend(), NULL, 0xffffffff);
g_d3dContext->IASetVertexBuffers(0, 2, m_segments->GetLineVertexBuffers(), s_strides, s_offsets);
g_d3dContext->IASetIndexBuffer(m_segments->GetLineIndexBuffer(), DXGI_FORMAT_R16_UINT, 0);
g_d3dContext->IASetInputLayout(s_IL_Polyline.Get());
g_d3dContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_LINELIST_ADJ);
g_d3dContext->VSSetShader(g_World_Polyline_VS_Segment.Get(), NULL, 0);
g_d3dContext->GSSetShader(g_World_Polyline_GS_Segment.Get(), NULL, 0);
g_d3dContext->PSSetShader(g_World_Polyline_PS_Segment.Get(), NULL, 0);
g_d3dContext->RSSetState(g_States->CullNone());
//g_d3dContext->DrawIndexed(4 * m_segments->LineCount, 0, 0);
g_d3dContext->DrawIndexedInstanced(4, m_segments->LineCount, 0, 0, 0);
g_d3dContext->GSSetShader(nullptr, NULL, 0);

-The DrawIndexed call draws all segments
-The DrawIndexedInstanced call draws only the first segment

Creating a second instance of this class, DrawIndexedInstanced draws only the first segment of each compound line. Although it is correctly created, filled, and set, I am not even using the per-instance data yet. Manually manipulating the StartIndexOffset parameter causes different, only-one, line segments to be drawn.

PIX is worthless, as usual, but, at least, allowed me to inspect the buffer contents. All of the data is correct and in-place but I cannot get the "gosh-darn" thing to work. After 18 hours of searching and getting nowhere, I'm livid, giving up, and going to bed.

Please help me explain why (4*2) != 4[0:1]

Edit:
This, stupidly, works:

for (char i = 0; i < m_segments->LineCount; i++)
{
    g_d3dContext->DrawIndexedInstanced(4, 1, i * 4, 0, i * 4);
}

So, now: (4[0] + 4[1]) == (4*2) != 4[0:1]

Verifying, again, that the data is all where it needs to be.. Stumped. It's got to be something so obvious, that it's not. I feel like I'm already over-kill on setting every possible state parameter there is and if I comment any one line, it would switch from doesn't work to shouldn't work and I can't debug it.


texts: Unity Checkpoint System that remembers NPC interactions + Environment changes?

texts:
I have already implemented a checkpoint system that respawns the player at the last checkpoint they cross through. Now imagine this:

NPC A interacts with NPC B
NPC B walks over to a nearby car
A bird flies over the car and takes a dump
Player dies tragically (lol)
Player respawns at the last checkpoint X

Given that checkpoint X is achieved after watching all these NPC interactions, how can I fast forward/skip these interactions when respawning the player? The build I have right now respawned at the correct location but of course, the NPC interactions happen again even though they were supposed to end before reaching that last checkpoint (if that makes any sense  )

I understand that this can be achieved by saving all the last known locations of the NPCs, flags that indicate whether the bird took a dump (true/false). For example, this seems quite tedious for a game like Uncharted/GTA where a lot of interactions happen at the same time.

My initial thought was to somehow fast forward the entire game to a point where all these interactions are done and dusted. That way, I can safely respawn the player knowing that they don’t see something they’ve already seen.

Sorry for the detailed post  Any tips on how this can be accomplished?


texts: Implementing multithreaded loading screens

texts:
Ok, I have fairly little multi-threading experience, but i have done a similar thing before without issue...but this has me stumped.

This is in C++, Directx9 Visual Studio...

My game basically runs in one thread, apart from loading screens. When I want to load a new game, I fire up a new thread which goes through and does all of the simulation and asset loading stuff. Meanwhile, the original (base) thread displays an animated loading screen.
Once the loading is finished, the loading thread sets a flag in tjhe loading screen saying it's done, and during the loading screens Draw() it spots the flag, ends the 'loading' thread, and starts the main game.

All of this works perfectly, in debug and release.

Except fullscreen...

For some reason, if I run the game in fullscreen mode, it goes wrong. The game hangs at the end of loading, and it looks like the flag in the loading screen is never getting set. if I force a debug break into the base thread, it seems to always be inside the D3D flip().

I can't see what I'm doing wrong. The loading thread does zero rendering. It creates some directx assets but never uses them. The flag I'm using to communicate between threads is a simple int, and it's read/write should thus be atomic.
I've done a very similar thing in my previous games with no problems, but this has me stumped. Should I really be using CriticalSections etc for something this simple?
Help!


texts:
I am running the build Unity executable in ubuntu 18.04 and it may take a while to load the asset. When I wait, I always receive a window telling me "You can choose to wait for a while to let it continue or force the application to completely exit." For a while, Unity will run and it looks like works well.
My question is, what is the impact of this? Why does ubuntu send the message? How to deal with it?


texts: How does one do alpha transparency testing in XNA 4.0?

texts:
I've read a lot of tutorials, but it just doesn't seem to work. Here's the code as suggested by a tutorial, using the built-in AlphaTestEffect class:

Matrix projection = Matrix.CreateOrthographicOffCenter(0, GraphicsDevice.Viewport.Width, GraphicsDevice.Viewport.Height, 0, 0, 1);
Matrix halfPixelOffset = Matrix.CreateTranslation(-0.5f, -0.5f, 0);
alphaTest = new AlphaTestEffect(GraphicsDevice);
alphaTest.VertexColorEnabled = true;
alphaTest.DiffuseColor = Color.White.ToVector3();
alphaTest.AlphaFunction = CompareFunction.Greater;
alphaTest.ReferenceAlpha = 128;
alphaTest.World = Matrix.Identity;
alphaTest.View = Matrix.Identity;
alphaTest.Projection = halfPixelOffset * projection;

Then this object is just passed in to the SpriteBatch.Begin method. The result: Nothing appears on the screen, whereas the exact same code that doesn't pass in the alphaTest object renders correctly.

Note that this is the case even with CompareFunction.Always! (I tried CompareFunction.Never too in case I misunderstand the comparison order).

I am following this tutorial, but I've also seen that same code elsewhere. The tutorial has a downloadable file for XNA 4.0 to demonstrate it. I downloaded and tried it, and - It doesn't work. No craters show up. So what the heck is going on?


texts:
I have been trying to find a fairly cross-compatible way to stream a framebuffer from my game to a single client. The client will be on the local network and I want to have the stream be as low latency as possible. I was thinking some form of h264 and UDP but I am not finding a good solution.

Anyone have good advice on creating a stream server as part of my game?


texts: Exposing type definitions to modders in Unity

texts:
Note that this question is not about modding assets/data and not about security, I plan to rely on community trust.
I don't know much about DLL's and I was wondering how I can provide interface and attribute definitions for modders.
For Kerbal Space Program modders only have to reference the Assembly-CSharp.dll, UnityEngine.dll and UnityEngine.CoreModule.dll files of a games build, to create and compile their own DLLs.

Are there certain things I have to do, to mimic this behavior, or does this work out of the box?
Are there gotchas to this approach?
Will a mods DLL, that was compiled using an older version of Assembly-CSharp.dll, break if the Assembly-CSharp.dll is updated, even though no types relevant to the mod changed?
Will modders be able to use Visual Studios debugging features for their DLLs?
Is there a better approach to provide type definitions?

My question is related to this question. But I would argue that that question is kind of broad, while mine is about one specific aspect.

Might not be needed for the question, but here are the two levels of modding that I would like to support for my game:
1. Easier modding
I want to compile .cs files of modders that implement special interfaces like IAbility, IItem, etc. I will use Roslyn or cs-sript to do so.
2. More advanced modding
I also want to load .dll's that modders compiled, allowing them to register their own Types in the games DI-Framework, mark methods/classes with attributes like CallMethodOnLevelLoad and use Harmony.


texts: Image of the room appearing incorrectly for no apparent reason

texts:
In the game, when I call the room (room_Corrida) from the room of the selection menu, it was for that to appear:

It turns out this is how the room appears:

The effect is as if it had a white rectangle the same size as the room, with less than 100% opacity.
When I start the room immediately (I put it first), it appears normally. The room also appears normally when I have the room called directly after the start menu. It only appears wrongly when I call it after the game selection menu.
Code that makes the room appear wrong (from the selection menu):
if(mouse_x>=1601 && mouse_x<=1917 && mouse_y>=762 && mouse_y<=1077){
    room_goto(room_Corrida);
}

Code that makes the room appear correctly (from the home menu):
if(mouse_x>=room_width/7*1 && mouse_x<=room_width/7*2-1 && mouse_y>=room_height/10*1 && mouse_y<=room_height/10*2-1){
    room_goto(room_Corrida);
}


texts:
I'm familiar with various methods of triangulation (eg Delaunay), but since I have hundreds of thousands of regularly spaced points that may need to be revisited like this on each physics frame, I'm hoping that there's a more efficient way to do this.

What I need to do is, given a series of points like this:

locate the triangles and perimeter. While I haven't show it in this image, it should be possible to form holes in the mesh where there are points missing inside the blue perimeter shown below. Still, I do need to find all the interior perimeters.

or, if it would be faster

My current plan is to use Delaunay triangulation to build the mesh, not merging the triangles at all, and then starting from an arbitrary point, select points which meet criteria for being an edge (being a member of less than 5 triangles?). Is there a more efficient way to do this?


texts:
I read this: How to design a replay system But it don't really answer my question.

My game is built with the client "view" of the game as a separate program from the server "model" and "controller". (a bit like a mmo, or any multiplayer game built this way).
The server side is always the "truth" of the game, it only accept action requests as input from the clients and output events and "current state" messages.

The game model and rules are fully deterministic with a fixed "tick" update cycle, so on the server side I can record both the events sent to the client views, and the action requests. Both are associated to specific cycle number.

The question is: in this case, to setup a replay system, should I use the input, or user action requests (as suggested in there) or the events?

It looks to me that both would give exactly the same output. The only differences I can see are:

Events gives the real output while action requests have to be processed to give events.
Action requests might be far less data to record.

Are there other things to consider?


texts: How to create a reliable Installation Package for Windows in seconds?

texts:
I am looking a reliable way to create an Installation Package for a Unity 3D Video Game.

I have just tried NSIS (Nullsoft Scriptable Install System)
But the default user interface (of the final result) appear too much old.

If you have a better method (based on script) please give an advice!


texts: Trouble With Quaternions and orbital camera:

texts:
UPDATED:
I have been trying to implement a Orbital Camera of sorts in a engine I am currently doing in Unity3D, the issue being I can't seem to do the correct rotation no matter what.

This is what it is needed:

Rotate on Y and X axis via the mouse, but the Y and X axis are not Vector.up or Vector.right
they are given by the current Slope of  the Target I am orbiting around.

I don't get how I can make it idependent of the character rotation, but at the same time dependent

This sorta works, but some loops have issues,  check the video below for a taste of whats wrong

var forward = Vector3.forward; //Vector3.Cross(ViewTarget.transform.up, transform.right);
        //Apply the rotation
        var rot = Quaternion.AngleAxis(CurrentHorizontalLook, ViewTarget.transform.up);
        var rot2 = Quaternion.AngleAxis(CurrentVerticalLook, transform.right) ;
        Debug.DrawRay(ViewTarget.transform.position, Vector3.right * 5, Color.yellow, 0, false);
        Debug.DrawRay(ViewTarget.transform.position, ViewTarget.transform.up * 5, Color.blue, 0, false);
        var offset = forward * 5;
        transform.rotation =  rot * rot2;
        transform.position = ViewTarget.transform.position + EyeHeight + transform.rotation*-offset;
        transform.LookAt(ViewTarget.transform.position, ViewTarget.transform.up);

EDIT : Maybe this image will help.

Black is the Up Vector, Red is the rotation on X Axis, Green is rotation on Y Axis.
The trick here is it being idependent of the right and forward of the Target object , only the Up vector used to align the camera.

Edit: I have "something" that is somewhat related to what I want, but still missing one thing.

I got the camera to rotate correctly on the target Y axis, but it doesn't align to the ground plane at all.

Convention :
Y = UP
Z =  Forward
X = Right

var rot = Quaternion.AngleAxis(CurrentHorizontalLook, ViewTarget.transform.up);
        transform.rotation = rot ;
        var rot2 = Quaternion.AngleAxis(CurrentVerticalLook, transform.right) ;

  transform.rotation =  rot * rot2;

    var offset = forward * 5;

This is what I have , the issue now being that if the character is on a 90 degree wall the camera should be moving around the character on the same plane as the wall, but in my case it looks in a top down manner. If instead of WorldForward I used TargetForward it moves in the correct plane, but then when the character changes direction  the camera shifts too.

I think a better explanation of what I want is this : I want the camera to rotate on the X,Z Plane of the character, and I want to be able to tilt it up or down in the Y,Z Plane.
If you check the video I posted when Sonic goes in loop I want the camera to do sorta the same thing.

Youtube Showing current Camera issue


texts: How would a sprite spawn more sprites under themself every second?

texts: I am making a snake game and am having trouble to make the snake go longer, at the moment when I run the program, I just have the snake head eating apples. But I want the snake head(30x30) to spawn body parts(20x20) under himself every second. After I can do that, the snake head has to draw 4 body parts and the computer must "delete" the oldest body part before a new one spawns. It is a 2d game, and the snake can curve instead of 90 degree turns. I hope you will all understand.


texts:
How Can i Create Text in Unity3D?
I Use "3D Text" But Its Always on Top Of Everything!
Can You Suggest Anything?
I creating a 2D Game So its not Necessarily a 3D Text..

Edit: Because I Building a 2D Game My Scene is Full of Planes in Front of Camera And I want My Text to be Over One of the Planes and when plane is moving My Text appears behind it.
But When I Use "3D Text" Its Always In Front of Everything.

Sorry for My Bad English...


texts: How to control an Unity character with mouse clicks?

texts:
I am trying to make a 2D RPG game in Unity with an isometric tile setup.

Using Unity/C#, how do I code the character's upward, right, left, down and diagonal animations and movements using mouse button as the controls (much like Red Alert 2). Normally, this can easily be done using keyboard inputs, however, what I am trying to do is control the character by clicking the mouse. For example, if I click in a diagonal location from the character, the character should follow the mouse and also do the diagonal animation.


texts:
What is the best way to create a camera for a 2D platformer using swing, and I want to create a camera that moves instead of moving the background. This is because I'm going to have objects rotated by a transformer and need the camera to stay on the object whilst also allowing zooming and rotation.
Any help would be appreciated.


texts: Does Unity's Microphone functionality support stereo input?

texts:
The documentation for the Microphone class in Unity does not indicate whether Unity supports stereo recording. Does Unity support recording stereo audio from a compatible microphone? It looks like several people have asked this on Unity's Q&A website, but no one has ever answered.

I understand that most microphones are mono and gaming headsets never have stereo microphones, but stereo microphones do exist. It's just not clear whether Unity supports stereo input.


texts:
I use libgdx and I draw some text with BitmapFont, it works, but on some devices with Android 5.1 game draw only numbers and punctuation symbols, without any text.

I tried two ways:

1) Font Generator:

    mFontGenerator = new FreeTypeFontGenerator(Gdx.files.internal(fontName));
    mFontParameter = new FreeTypeFontGenerator.FreeTypeFontParameter();
    mFontParameter.characters = Font.FONT_CHARS;
    mFontParameter.size = mSizePixels;
    mFontParameter.color = mTextColor;
    mFontParameter.borderWidth = mBorderWidth;
    mFontParameter.borderColor = mBorderColor;
    mBitmapFont = mFontGenerator.generateFont(mFontParameter);
    mBitmapFont.setUseIntegerPositions(false);
    mBitmapFont.getData().setScale(mTextScale);
    mFontGenerator.dispose();

2) Font, created in Hiero:

    mBitmapFont = new BitmapFont(Gdx.files.internal(fontName));
    mBitmapFont.setUseIntegerPositions(false);
    mBitmapFont.getData().setScale(mTextScale);
    mBitmapFont.setColor(mTextColor);

Draw code is the same for both ways:

@Override
public void draw(SpriteBatch spriteBatch) {
    mBitmapFont.draw(spriteBatch, mText, mPositionX, mPositionY);
}

Both ways works on tablet with Android 7.1.1 and even on phone with Android 2.3.5, but on two devices with Android 5.1 I can see just numbers, no letters.

Thanks for any help!


texts: Unity Mobile project, button problem "CrossPlatformInputManager.GetButton" not working

texts:
Good afternoon, I have a problem with an input in my code:
Before testing it on mobile I tried on PC and the code to make my player sprint was like this:

        var sprintPressed = Input.GetKey(KeyCode.LeftShift);
        var targetSpeed = maxSpeed;
        if (attacking) {
            targetSpeed *= attackMoveSpeedMultiplier;
        }
        else if (sprintPressed) {

            targetSpeed *= sprintMultiplier;
        }

And everything was working fine. My player increases the movement speed as soon as I press "Left Shift" button.
Then I changed the code to make it work with a mobile button:

        var sprintPressed = CrossPlatformInputManager.GetButton("Sprint");
        var targetSpeed = maxSpeed;
        if (attacking) {
            targetSpeed *= attackMoveSpeedMultiplier;
        }
        else if (sprintPressed) {
            Debug.Log(sprintPressed ? sprintMultiplier : 1);//just to see if it take a button
            targetSpeed *= sprintMultiplier;
        }

I also make a change for a controller so instead, to press WASD I use a screen joystick. That's work fine.  But when I press a button to make a sprint, nothing happens. I insert a debug log line and when I press a button it just return 1 single value (sprintMultiplier) and not 1 per frame as it should be because this function is in the Fixed Update.
I check in Google and I found this tutorial https://www.youtube.com/watch?v=nGYObojmkO4&t=851s&list=PLXVRS21ln3JIbFLPwf9bdH3thHmmYRJGi&index=16
Pretty much what I did but in his video, it's working. In my project doesn't.
Can someone help me, please?
Many thanks beforehand


texts: How to get Pixel Coordinates of certain colors in a Texture?

texts:
I have a relatively big Texture, and I try to find a certain color pixels pattern:
eg. White, Black, White, Green .
They are lying next to each other,

If I use Texture2d.Getpixels() on every pixel every frame its possible, but way too slow.

Is there a "real good" way to do this? For example a shader way?

The "big idea" is to make a game which is "remote-playable".
For example through Twitch or of a streamed youtube video.
The user should not be connected to the server in any way, Instead he is sending messages or not.

For this I have to find a health bar. This health bar has the left-upper corner in black-> white -> black -> green pixels lying next to each other.

In the shader I CAN find these colors, but I dont really know the coordinates.
Also I think there "should" be a solution with a  ... compute shader?
I dont really want to render new stuff. Just check pixel colors.
I just want to know where these pixel colors are.

I imagined something like this:

If PixelColorIsWhite(x,y)
{
If PixelColorIsBlack(x+1,y)
{
If PixelColorIsWhite(x+2,y)
{
If PixelColorIsGreen(x+3,y)
{
return x+20,y+100 //because the player is 20 pixels right and 100 pixels below
}}}}

In a shader i guess i can access the current coordinate, but I cant access the other pixels. Its paralell processing... right?
So its impossible to access the "entire thing" in one go , right?

I think it must work somehow with... getting the big "chunk" of texture data, a very long array of pixels, giving it to a compute shader, and letting the CS find it.

I hope I could clarify the problem now :)

_-----------------------------------

Update:

I found out it (at least) should work with a compute shader.

I feel like im so close to the solution, yet im getting errors. :-(

So...

This is my C# Code:

public ComputeShader shader;
public Material thisMat;

public RenderTexture ScreenTex;

public int x;
public int y;

public const string INPUTTEX = "InputTexture";

private void Update()
{
    RunShader();
}

public void RunShader()
{
    RenderTexture tex = new RenderTexture(1024, 786, 24);
    tex.enableRandomWrite = true;
    tex.Create();

    shader.SetTexture(0, INPUTTEX, ScreenTex);
    shader.SetFloat("_ScreenWidth", Camera.main.pixelWidth);
    shader.SetFloat("_ScreenHeight", Camera.main.pixelHeight);

    int[] data = new int[2];
    ComputeBuffer buffer = new ComputeBuffer(data.Length, sizeof(int)*2);
    buffer.SetData(data);
    shader.SetBuffer(0, "readWriteIntBuffer", buffer);

    thisMat.mainTexture = tex;
    int kernelHandle = shader.FindKernel("CSMain");

    shader.SetTexture(kernelHandle, "Result", tex);
    shader.Dispatch(kernelHandle, 1024 / 8, 786 / 8, 1);

    buffer.GetData(data);

    x = data[0];
    y = data[1];
    buffer.Release();}

And this is my ComputeShader Code:

    -------------------
    #pragma kernel CSMain

RWTexture2D<float4> Result;

RWStructuredBuffer<int> readWriteIntBuffer;
Texture2D<float4> InputTexture;
float _ScreenWidth;
float _ScreenHeight;

[numthreads(8, 8, 1)]
void CSMain(uint3 id : SV_DispatchThreadID)
{
    if (id.x >= (uint)(_ScreenWidth*_ScreenHeight))
    {
        return;
    }

    int y = id.x / int(_ScreenWidth);
    int x = id.x % int(_ScreenWidth);
    readWriteIntBuffer[0] = 999; //some debug-testnumbers that show me that there were no colors found
    readWriteIntBuffer[1] = 998;

    if (InputTexture[float2(x,y)].r == 1.0f && InputTexture[float2(x, y)].g == 0.0f && InputTexture[float2(x, y)].b == 0.0f)
{
    float2 coordinates = float2((float)id.x / (float)_ScreenWidth, (float)id.y / (float)_ScreenHeight);

    readWriteIntBuffer[0] = coordinates.x;
    readWriteIntBuffer[1] = coordinates.y;

}
}

This Computeshader checks if a single pixel in a texture is red and writs it in a buffer. The buffer gets read by C# with getdata.
-- it seems we're almost getting there!
But "something" seems to be wrong, since I dont seem to get the colors i want.
But the compute shader seems to work, since i also get the triange-pattern in my material.


texts: Which open source licenses can address these concerns for an open source game engine?

texts:
I am on a team that is looking to open source an engine we are building.  It's intended as an engine for Online RPG style games.  We're writing it to work on both desktops and android platforms.

I've been over to the OSI http://opensource.org/licenses/category to check out the most common licenses. However, this will be my first time going into an open source project and I wanted to know if the community had some insight into which licenses might be best suited.

Key licensing concerns:

Removing or limiting our liability (most already seem to cover this, but stating for completeness).
We want other developers to be able to take part or all of our project and use it in their own projects with proper accreditation to our project.
Licensing should not hinder someone's ability to quickly use the engine. They should be able to download a release and start using it without needing to wait on licensing issues.
Game content (gfx, sound, etc.) that is not part of the engine should be allowed to be licensed separately. If someone is using our engine, they can retain full copy right of their content, including engine generated data.
Our primary goal is exposure, which is why we're going open source to
start with.  Both for the project and for the individuals developing it.  Are there any licenses that can require accreditation visible to players? Update: As per comments, I mean this to be a requirement for either a splash screen or placement in the credits. Not a constantly visible logo.

While I'd put our primary goal as exposure, for licensing the accreditation is less of a concern.

From what I've read through (and have been able to understand) it doesn't seem like any of the licenses cover anything that is produced by the licensed software.  Are there any that state this specifically, or does simply not mentioning it leave it open for other licensing?

Are there any other concerns that we should consider?

Has anyone had any issues using any of these licenses?


texts: Proper way to calculate x and y components of two 2D vectors

texts:
I'm having some issues on resolving this with the current set of Vector2 methods. Could you help me to define a universal solution? The idea is to move a spaceship to another point using only relative to (A) lateral and forward movements.

Given two points A(1,-1) and B(2,-3):
- A has a known angle with the y axis: alpha
- How to calculate the x-dist and y-dist relative distances in order to move A to B?


texts: Picking a 2D Box Collider with the mouse in Unity

texts:
I have a scene with a bunch of 2D doors that have 2d Box Colliders (no trigger) on them and that live on a Canvas.  I would like to be able to click on them with the mouse, but have had no luck.

Following this earlier topic: (2D) Detect mouse click on object with no script attached , I did the following:

    if (Input.GetMouseButtonDown(0))
    {
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        RaycastHit2D hit = Physics2D.Raycast (ray.origin, ray.direction, Mathf.Infinity);
        if (hit)
        {
            Debug.Log(hit.collider.gameObject.name);
        }
    }

However, (hit) is always null.  I have no RigidBody2D objects in my scene, because I only need mouse selection, not any interaction between objects.

In the inspector I the green box collider but clicking within it in the scene (not the inspector, obviously) runs the MouseButtonDown() code but still no Raycast hit.

What else could I be missing?

To reduce this to its simplest, you can do the following:

Create a new 2D scene with a canvas
Add two 100x100 Images to the Canvas
Add a Boxcolllider2D to each image
Now what script is required to detect mouse clicks within them?


texts: I was just wondering about the horizontal movement of a pong ball? What is the general algorithm used with this? The ball in my pong game just moves vertically and I don't know about the algorithms used for horizontal movement.


texts: How to port animation from one skeleton to another?

texts:
While I need to do this in a Blender3D modeler script, the math should be similar for other modelers or realtime engines.

Blender3D specific terminology:
Armature = skeleton
EditBone = rest pose bone (stores the rest pose matrix)
PoseBone = can store a different pose (animation matrix) for each frame of your animation

I need to share animations (Blender Actions) between Armatures which have EditBones with same names and which have the same positions, but can have different (rest pose) angles and scales. Plus the Armatures might have different bone hierarchy (bone parenting/ no bone parenting).

Why I need this:
I've made an importer/exporter for a 3d format for a game. The format doesn't store enough info to connect/parent the bones, which makes posing/animating character models in a 3d modeller nearly impossible (original model files for the 3d modeler don't exist, this is for modding).
As there are only 2 character skeleton types in the game, I decided to optionally allow to generate the bone from a hardcoded data in the model importer and undo that in the exporter. This allows to easily pose the model for checking weights, easily create weights, makes it easier for Blender to generate automatic weights and of course makes animating possible.

This worked perfectly: the importer optionally generated the Armature itself and the exporter removed those changes, so the exported model works with existing animations in the game.
But now I'm writing an importer and exporter for the game's animation format and here come the problems of:

Trying to make original animations work in Blender with my "custom" (modified) Armature
Trying to make animations created by using the "custom" (modified) Armature work with the original models in the game (and Blender).

Constraints or bone snapping inside Blender won't work as they don't care that the bones have different angles in the rest pose, they will still face the same direction.

It seems I just need to get the "difference" between the EditBone matrices of all EditBones for the two Armatures somehow and apply that difference to PoseBone matrices of all PoseBones, for all frames of my animation. I need to know how to get that difference and how to apply it.

BTW, PoseBone matrices are relative to rest pose, they are by default

[1.000000, 0.000000, 0.000000, 0.000000](matrix [row 0])
[0.000000, 1.000000, 0.000000, 0.000000](matrix [row 1])
[0.000000, 0.000000, 1.000000, 0.000000](matrix [row 2])
[0.000000, 0.000000, 0.000000, 1.000000](matrix [row 3])

So the question is: How to get the difference between two bone (EditBone) matrices to apply that difference to the animation matrices (PoseBone matrices)?

Please be easy on the matrix math.