texts: How to reduce the size occupied by my video animations?

texts:
I have a mobile game but my build size is currently 4gb. Furthermore, it crashes on open and I suspect it has something to do with the huge build size.

In my project are 10 animations made of a series of images, each one using around 250-300 images. Each one is quite large as the animation takes up most of the screen so they are high resolution. What can I do to reduce the build size?

I have tried converting it into a video file and using the raw image component to display it as a movie texture, however, it seems unity doesn't support videos with alpha channels, and the alpha channel is critical to my animation.

I thought about combining them into a single image, but lets be real, if each image is more than 1080p, then combining 250 - 300 images into a single file will be massive.

So what can I do to reduce the size of the animations?


texts: 3D/perspective Top down shooter bullet issues

texts:
I'm developing a top-down shooter with multiple levels (ground for ground units, middle level for buildings, top level for air unity).

The problem is the collision. Though I can make the collider box of a bullet be long enough to reach the ground (and collide with it), the real issue is optical.

When the bullet is fired from a aircraft and collides with some object on the ground (building, ground unit) it will be optically offset due to the perspective camera, because it looks like the shot "by-passed" the target as seen below

Is there any way to make the bullets collide perspectively correct? I'm using Unity3d Engine and it offers only simple colliders (box, sphere, cylinder, mesh and wheel), though I don't think a cone-formed collider would solve this issue.

I'd need a (cheap) way to check if it's overlapping a destructible object? I thought of casting a ray from the camera through the bullet and if it hits something destructible, trigger an action, but that's quite punctual and maybe to performance heavy on certain number of bullets


texts: Why is custom memory management needed for assets?

texts:
Pretty much all resources relating to game programming, especially 3D open-world games, talk about how you have to constantly be unloading and reloading assets to and from disk, system memory, and video memory.  I can understand this on consoles, as they have very simple memory management schemes that cannot deal with any potential overflow.

However, on the PC, the situation is very different.  There is virtual memory provided by the OS for system memory and the graphics driver handles swapping back and forth from the CPU to the GPU.  So why is it that it's not sufficient to load everything at once and only have to deal with prefetching and possibly making sure that there is no blocking while a required asset is being swapped?

This is not to say that everything is being allocated naively using something like malloc.  Everything will be kept contiguous and cache-coherent.  It's arguably easier to make your memory access efficient if you don't have to worry about paging in and out manually anyways...

UPDATE:

After reading a bit into asynchronous buffer transfers, I get the idea that the way the graphics driver can automatically page memory in and out is suboptimal.  Does this also hold true for CPU resources; i.e., is it better to always manually manage when a given resource is to be loaded and unloaded even in the presence of virtual memory?


texts: In HLSL pixel shader , why is SV_POSITION different to other semantics?

texts:
In my HLSL pixel shader, SV_POSITION seems to have different values to any other semantic I use. I don't understand why this is. Can you please explain it?

For example, I am using a triangle with the following coordinates:

(0.0f, 0.5f)
(0.5f, -0.5f)
(-0.5f, -0.5f)

The w and z values are 0 and 1, respectively.

This is the pixel shader.

struct VS_IN
{
    float4 pos : POSITION;
};

struct PS_IN
{
    float4 pos : SV_POSITION;
    float4 k : LOLIMASEMANTIC;
};

PS_IN VS( VS_IN input )
{
    PS_IN output = (PS_IN)0;
    output.pos = input.pos;
    output.k = input.pos;
    return output;
}

float4 PS( PS_IN input ) : SV_Target
{
    // screenshot 1
    return input.pos;

    // screenshot 2
    return input.k;
}

technique10 Render
{
    pass P0
    {
        SetGeometryShader( 0 );
        SetVertexShader( CompileShader( vs_4_0, VS() ) );
        SetPixelShader( CompileShader( ps_4_0, PS() ) );
    }
}

When I use the first statement (result is first screenshot), the one that uses the SV_POSITION semantic, the result is completely unexpected and is yellow, whereas using any other semantic will produce the expected result. Why is this?


texts: Deserialize only some fields from a JSON file

texts:
I'm trying to parse a very large JSON string in Unity. I do not need all the fields and I can't create a class with all the members.
It appears that all examples I have found, including the official docs, always deserialize and map every field to class members, which I cannot do for my application.
I tried creating a class that is similar to the JSON string, meaning that it has some members of the target JSON, just not all of them. But it's not working as desired: all members of my class are always undefined after deserializing.
Here's part of the string:
{
    "Robots":[{"CanReset":false,
    "CycleTime":123.875,
    "Info":null,
    "LevelInfo":null,
    "Name":"FTF_10033",
    "State":0,"
    ...
    }, ...
}

So I tried creating these classes:
[Serializable]
public class jsonData
{
    public Robot[] robots;
}

[Serializable]
public class Robot
{
    public string Name = "Unknown AGV";
}

And printing the results:
var jsonString = www.downloadHandler.text;
jsonData jsonData_ = JsonUtility.FromJson<jsonData>(jsonString);
Debug.Log("Json data: " + jsonData_);
Debug.Log("Robots: " + jsonData_.robots);

jsonData_ prints Json data: jsonData_, and jsonData_.robots prints nothing (just Robots:).
Is there any way to parse just these particular fields out of the JSON string?
I would be content with something like jsonString["robots"][0]["name"] or something.


texts: ScriptableObjects lose references/stored objects upon build/restarting the Unity Editor?

texts:
I'm working on implementing room prefabs for my 2D procedural map generation algorithm.

Basically I made a tool which parses a scene's

monsters, items, etc into an ObjectContainer prefab,
and into a ScriptableObject containing the tilemap's TileDatas, EntryTiles, and the ObjectContainerPrefab.

It works well, but my problem occurs when I try to build the game, or just restart the editor.

The TileData array will be empty.

And thus for example the EntryTiles' TileData reference will be null.

Here 's how I use them:

[MenuItem("Custom Tools/Parse room prefab from scene")]
private static void ParseRoomPrefabFromScene()
{
    var tilemap = GameObject.Find("Tilemap").GetComponent<Tilemap>();
    RoomPrefab roomPrefab = ScriptableObject.CreateInstance<RoomPrefab>();
    ParseTilemap(roomPrefab, tilemap);
    ParseObjects(roomPrefab, tilemap);
    ParseEntryTiles(roomPrefab, tilemap);
    AssetDatabase.CreateAsset(roomPrefab, "xyz.asset");
    AssetDatabase.SaveAssets();
}

// How I setup my scriptable object, i.e. in ParseTilemap:
var tileDatas = new List<TileData>();
...
    var tileData = new TileData(coordinates, unityTile, isWall);
    tileDatas.Add(tileData);
...
roomPrefab.tileDatas = tileDatas.ToArray();

Here are the classes:

public class RoomPrefab : ScriptableObject
{
    public TileData[] tileDatas;
    public EntryTile[] entryTiles;
    public ObjectContainerPrefab ObjectContainerPrefab;
}

[Serializable]
public class TileData
{
    public TileBase UnityTile
    {
        get;
        private set;
    }

    public Vector2Int Coordinates
    {
        get;
        set;
    }

    public bool IsWall
    {
        get;
        private set;
    }

    public TileData(Vector2Int coordinates, TileBase unityTile, bool isWall)
    {
        Coordinates = coordinates;
        UnityTile = unityTile;
        IsWall = isWall;
    }
...

[Serializable]
public class EntryTile
{
    public TileData TileData
    {
        get;
        private set;
    }

    public Vector2Int LeaveDirection
    {
        get;
        private set;
    }

    public EntryTile(TileData tileData, Vector2Int leaveDirection)
    {
        TileData = tileData;
        LeaveDirection = leaveDirection;
    }
...

[Serializable]
public class ObjectContainerPrefab
{
    public Vector2Int Coordinates
    {
        get;
        private set;
    }

    public float Rotation
    {
        get;
        private set;
    }

    public GameObject Prefab
    {
        get;
        private set;
    }

    public ObjectContainerPrefab(Vector2Int coordinates, float rotation, GameObject prefab)
    {
        Coordinates = coordinates;
        Rotation = rotation;
        Prefab = prefab;
    }
}

UPDATE: here is a freshly parsed scriptable object. In the Editor everything is fine, while in its file its tileDatas array is already empty. Why?

%YAML 1.1
%TAG !u! tag:unity3d.com,2011:
--- !u!114 &11400000
MonoBehaviour:
  m_ObjectHideFlags: 0
  m_CorrespondingSourceObject: {fileID: 0}
  m_PrefabInstance: {fileID: 0}
  m_PrefabAsset: {fileID: 0}
  m_GameObject: {fileID: 0}
  m_Enabled: 1
  m_EditorHideFlags: 0
  m_Script: {fileID: 11500000, guid: 30263215ad3a45a479bb2dd6409fb0a9, type: 3}
  m_Name: TestRoom
  m_EditorClassIdentifier:
  tileDatas: []
  entryTiles:
  - DebugCube: {fileID: 0}
  - DebugCube: {fileID: 0}


texts: Why is my spritesheet displaying all messed up in game?

texts:
I'm having an issue I don't quite understand, where my spritesheet is looping strangely and not showing the full sprite I want, even though I feel like I'm specifying it correctly. My code is in phaser.js.

Example: https://imgur.com/a/xJ95Qbj

My code for it is as follows:

this.load.spritesheet('dude', 'assets/bunny.png', { frameWidth: 32 , frameHeight: 42 });

    this.anims.create({
        key: 'left',
        frames: this.anims.generateFrameNumbers('dude', {start: 56, end: 64}),
        frameRate: 5,
        repeat: -1
    });

    this.anims.create({
        key: 'turn',
        frames: [{key: 'dude', frame: 4}],
        frameRate: 20
    });

    this.anims.create({
        key: 'right',
        frames: this.anims.generateFrameNumbers('dude', {start: 40, end: 48}),
        frameRate: 5,
        repeat: -1
    });

Look fine on the 'turn' frame, but not so fine on movement. For reference, here's the spritesheet I'm attempting to use: https://imgur.com/Rzi5i7Z


texts: Textures loading too large on smaller monitors

texts:
I have an XNA game, and when i run the game the textures load all good on my computer and on my tv and they're all bring drawn in the right position. But on my laptop, which screen is smaller then both my othe computers monitor and my tv screen, all the textures are being drawn way to large. Example: i have a background which is just grass, and a stone path, and the image size is 1920x1080. It loads fine and is centered on my other computer and TV, but on my laptop, its drawn way too big and where the center should be is in about the bottom right corner of the laptop screen. Is it possible to edit the code to make it resize better on smaller screens, or is it just my laptop and my laptop's screen size is messed up. I believe that my laptop is in the 16:9 aspect ratio.

Update 1

I have noticed that the textures load fine when the window is not in full screen, but in full screen the textures have problems. How should i change this Draw Method to fix this problem, and draw this in the right spot in a full screen 1920x1080 window?

spriteBatch.Draw(backgroundTexture, Vector.Zero, Color.White);

(keep in mind the backgroundTexture is 1920x1080)


texts: Position GameObject sprite where I tap on the screen

texts:
I can't do one of the simplest things. When the player taps the screen, I want to put my sprite in that place.

public class Controller : MonoBehaviour {

    public GameObject ball;  // A GameObject with a SpriteRenderer

    void Start () {

    }

    void Update () {
        if (Input.GetMouseButtonDown(0)) {
            ball.transform.position = Input.mousePosition;
        }
    }

}

Well, this doesn't work. When I tap the screen, the sprite appears further up and right. This is how the scene looks:

Where the sprite is by default at (0,0).

Aha, the problem seems quite obvious: if I touch the screen at (0,0) (the bottom-left), the sprite would appear at (0,0) - but as you can see, "(0,0)" is the center of the screen rather than the bottom-left, thus appearing further to the top and right as described above.

The solution seems pretty clear: the position of the sprite should be Input.mousePosition - new Vector3(Screen.width/2, Screen.height/2, 0) to make up for this offset! So:

ball.transform.position = Input.mousePosition - new Vector3(Screen.width/2, Screen.height/2, 0);

... It didn't quite work. Look, if I tap on the top-left of my screen, I get this:

If I tap on the bottom-right:

And if I tap on the center, it works correctly. But that's the only scenario.

How can correctly put my sprite wherever I tap on the screen?


texts:
I want to create a flat universe, where at first the whole universe is blank.

That would be represented by a parallax scrolling nebula background image.

What I want to do is represent the planets as disc shaped objects in the universe.
They can be of various sizes.

The inside of the discs will consist of a landmass, then outside that will be a body of water and after that air.

what would be the best way to go about creating those tiles procedurally as for example the air would consist of various gases and the land of various minerals and resources.

My first thought is to create texture images and then stamp out the circles out of those textures, but problem is that those textures would have to wrap horizontal and vertically. Is there a fully procedural way of doing this?


texts: Formula for calculating time difference regardless of speed

texts:
See the following situation:

The first car has a speed of 10 pixels per second and completes one lap in a circuit in 84 seconds.
I want the second car to complete this same lap in the circuit, but in 85 seconds (1 second slower than the first car).
For this I find that I need to slow down this second car by 0.118. Making it stay at the speed of 9.882 pixels per second.

So far no problem.

Now using the third car with speed 5 pixels per second, the third car completes the lap in 167 seconds (same circuit).
The speed of the fourth car is equal to the speed of third car minus 0.118 (5 - 0.118), but fourth car is not 1 second slower than third car, but 4 seconds (approximately).

Obviously the lap time is not just about the speed value. It is neither linear nor percentage.

Otherwise the third car would complete the lap in the circuit twice as long as the first car.

I would like to know how to do so that I can handle the lap time regardless of the speed of the car.

That is, the car could have 100, 80, 55... and yet I can make the car 1 tenth slower, whatever its speed.

EDIT 1

In the examples below, car speeds will be defined by the following line of code:

velocity=10.118-(car*0.118);

The lap time detection in the example below was done as follows:

distance=point_distance(obj_car.x,obj_car.y,obj_finish.x,obj_finish.y);

lapTime=(obj_finish.timer+distance/10)/3.395;

The lap time detection in the example below was done as follows:

distance=point_distance(obj_car.x,obj_car.y,obj_finish.x,obj_finish.y);

lapTime=obj_finish.timer+distance/10;

The lap time detection in the example below was done as follows:

lapTime=obj_finish.timer;

This is a famous circuit of Australia, I made many other from the most varied parts of the world. So it would need a general rule.

As you can see in all the examples, even though the differences between car speeds are the same, the time difference is still growing.

This is because the slower the car is, the greater its percentage loss in speed.

Even excluding all modifiers:

3.395 - This number is used to convert the finish line counter value to the real time of one lap of the circuit.
distance/10 - This value is used so that in cases of very small differences, if the cars arrive at the same step of the game, it will have different times.

Link to a question I also asked, which will help to understand this increase in distance:

https://forum.yoyogames.com/index.php?threads/how-to-make-a-more-accurate-lap-time-get_timer-limitation.69526/#post-414136


texts: Is it necessary to wait for rendering thread to terminate in surfaceDestroyed(...)

texts:
I just wrote a simple Android app that uses SurfaceHolder.Callback interface to communicate the state of the SurfaceView. In the Callback.surfaceDestroyed() method i just informed the rendering thread to terminate and returned, like so:

    public void surfaceDestroyed(SurfaceHolder holder) {
    renderingThread.requestStop();
    }

I did this because in the Android documentation SurfaceHolder.lockCanvas() it states that   a null will be returned when the surface is not available. And also that the SurfaceHolder holds a lock internally until SufraceHolder.unloackCanvasAndPost() is called, which prevents calls to SurfaceHolder.Callback methods.

So to me it seems that it's not necessary to wait for the rendering thread to finish. However all examples I've seen wait for the thread to finish, usually something like:

    public void surfaceDestroyed(SurfaceHolder holder) {
       boolean retry = true;
       rederingThread.setRunning(false);
       while (retry) {
          try {
            thread.join();
            retry = false;
          } catch (InterruptedException e) {
        }
     }
  }

Is this really necessary? My application runs without problems.


texts:
So I sort of understand the math behind projecting 3d points onto a 2d plane. It's just some simple dividing and multiplication of distances. However I can't seem to wrap my head around projecting lines from 3d space onto a 2d plane.

Demonstration:

Just to make this a little more simple, I'm going to be talking in terms of 2d projection onto a 1d line, because it's the same concept for 3d to 2d. So my issue is that if I want to project the line AB onto the viewing window which has a set focal length, I can just project both of the points of the line (A and B) onto the perspective line, and then draw the line between those two on the viewing window. However the difficulty comes when trying to project the line CD onto the line. The second point (D) of the line is behind the viewing window, and therefore cannot be projected onto the line. So how would one go about drawing line CD in the perspective window?


texts: Where would I update a graphical representation of a b2Body in Box2D's solver?

texts:
Hey i'm trying to make a class called BodyRep Which is supposed to use SFML too sync a graphical representation and Box2D Bodies orientation/location.

To do this i plan to ovveride some Box2D function so that it does it's original steps, plus one extra: to update the graphical representaions orientation based on the new Body orientation.

However I found this is not as easy as it seems as my class must be a descendent of another class that does the actual updates to the bodies in the World, so it CAN ovveride the function. On top of that, I know there is a ton of itterating in Box2D's solver, and i don't want my graphical reps. being updated if they don't have to yet....

So... What CLASS should I Descend from and what FUNCTION should I ovveride?

if you have any other ideas on how i could accomplish my goal of
syncronization between SFML and Box2D bodies, feel free to suggest
them! =)


texts: Problem with animating in Android, using batcher.draw in LibGDX

texts:
I am having a problem with the last part of the GameRenderer class. I call batcher.draw() and receive this error:

  The method draw(Texture, float, float, float, float) in the type SpriteBatch is not applicable for the arguments (Object, float, float, float, float)

This only happens when I try to draw animation; images work fine. How do I fix this?

This is my GameRenderer class, which throws the error.

public class GameRenderer {
    private SpriteBatch batcher = new SpriteBatch();

    public void render(float runTime) {
        // Begin SpriteBatch
        batcher.begin();
        // The bird needs transparency.
        batcher.enableBlending();

        // Draw bird at its coordinates. Retrieve the Animation object from
        // AssetLoader
        // Pass in the runTime variable to get the current frame.
        batcher.draw(AssetLoader.birdAnimation.getKeyFrame(runTime),
                x, y, width, height);

        // End SpriteBatch
        batcher.end();
    }
}

Just in case, here is my AssetLoader class:

public class AssetLoader {
    public static Animation birdAnimation;

    public static void load() {
        Texture texture = new Texture(Gdx.files.internal("data/texture.png"));
        texture.setFilter(TextureFilter.Nearest, TextureFilter.Nearest);

        TextureRegion birdDown = new TextureRegion(texture, 136, 0, 17, 12);
        birdDown.flip(false, true);

        TextureRegion bird = new TextureRegion(texture, 153, 0, 17, 12);
        bird.flip(false, true);

        TextureRegion birdUp = new TextureRegion(texture, 170, 0, 17, 12);
        birdUp.flip(false, true);

        TextureRegion[] birds = { birdDown, bird, birdUp };
        birdAnimation = new Animation(0.06f, birds);
        birdAnimation.setPlayMode(Animation.PlayMode.LOOP_PINGPONG);
    }
}

The class  where i call AssetLoader.load()

public class ZBGame extends Game {
    @Override
    public void create() {
        AssetLoader.load();
        /* Other stuff */
    }
}


texts: What would be a good way to implement Zelda like attack?

texts:
I'm looking for ways to implement "attack" like Gameboy Zelda used.

A method I came up with is:

Create a rectangle near a player based on the direction the player is facing when every time attack button is pressed.
If the rectangle intersects with enemy(rectangle shape) then, damage the enemy and push it back.

Just like the following image shows.

Any suggestions would be appreciated.


texts: Is there a universal method to send key or mouse input to any application from C#?

texts:
I need method or group of them to send signals to any application (browsers, games, et cetera) about mouse movement or key input.

I can easly retrieve an IntPtr to any process, but I don't know what library or function I must use next.

I know only about SendMessage/PostMessage functions from user32.dll, but these functions can send messages only to applications with standard message loops and it doesn't work with DirectX applications. And I've noticed that something like this:

PostMessage(pFoundWindow, WM_KEYDOWN, (IntPtr)VK_RIGHT, (IntPtr)0);
Thread.Sleep(150);
PostMessage(pFoundWindow, WM_KEYUP, (IntPtr)VK_RIGHT, (IntPtr)0);

sends messages slower than DirectInput in and does not allow player to send, for example, left arrow and space, even in threads.


texts: Common game controls/ User interface libraries or source code?

texts:
Sorry for the ackward title, but i don't know what to call it exactly. I'm looking for code or libraries that allow easy creation of commonly used user input devices, and code/libs that make gaming controls easy to set up (i'm using SFML and Box2D at the moment)

I don't want to re-invent things like buttons, arrows being placed wherever the mouse is located, and more game specific items such as "controls settings" or even being able to drag objects around with the mouse.

More specifically i want source code for interfaces that....

Makes Buttons and Textboxes easy to create
allows mouse input to press buttons or drag objects in games
has "Focuses" (like a textbox being able to gain focus and be typed in)
Is compatable with SFML/Box2D

and code for common game mechanics/controls that....

Allows easy setup of controls for a game
Makes events like clicking and holding on an object easy to setup, as so objects can be dragged around afterward

Are there any simple libraries or resources out there that i can use to avoid spending much of my time coding these now standard input devices/tecniques?


texts: Unity 2d...Bullet Intantiate on left....but instantiate on right but not showing in game mode

texts:
I created the gameobject player and add script to it:
[SerializeField] float _xSpeed = 10f;
    [SerializeField] float _jumpForce = 10f;

    private Rigidbody2D _rb;
    private float _movement;
    private float _extraJumps;
    private bool _isFacingRight;

    void Start()
    {
        _rb = GetComponent<Rigidbody2D>();
    }

    void Update()
    {
        _movement = Input.GetAxisRaw("Horizontal");
    }

    void FixedUpdate()
    {
        _rb.velocity = new Vector2(_movement * _xSpeed ,_rb.velocity.y);
        {
            if(_isFacingRight == true && _movement > 0.1f)
            {
                Flip();
            }
            else if(_isFacingRight == false && _movement < -0.1f)
            {
                Flip();
            }
        }

        if(Input.GetKeyDown(KeyCode.Space))
        {
            _rb.velocity = new Vector2(_rb.velocity.x,_jumpForce * Time.deltaTime);
        }
    }

    void Flip()
    {
        _isFacingRight = !_isFacingRight;
        transform.Rotate(0,180f,0);
    }
}

Then I created and empty gamobject firePoint and make the child of the player, then I add a bulletPrefab to instantiate at firePoint and created a script
Intstantiate(bulletPrefab,firepoint.position,firePoint.rotation);

And under bulletfrefab I wrote the movement script for it:
if(Input.GetButtonDow("fire1"))
 rb.velocity = transform.right * speed;

Now when firing ... the bulletPrefabs are instantiated and showing in the left side and right side in the scene scene panel but in game panel the bulletPrefab is showing in only left side and invisible on the right side.


texts: Problem with ID3D11DeviceContext::CopyResource method - How to properly read a texture CPU-side?

texts:
I am trying to make a full copy from a render target texture to a staging one but it seems my data length ends up being only 4 in length instead of 921600 (1280 * 720).

Here is my textures initializaion code :

// Setup the step count texture description.
D3D11_TEXTURE2D_DESC stepCountTextureDesc;
ZeroMemory(&stepCountTextureDesc, sizeof(stepCountTextureDesc));
stepCountTextureDesc.Width = g_clientWidth;
stepCountTextureDesc.Height = g_clientHeight;
stepCountTextureDesc.MipLevels = 1;
stepCountTextureDesc.ArraySize = 1;
stepCountTextureDesc.Format = DXGI_FORMAT_R32_UINT;
stepCountTextureDesc.SampleDesc.Count = 1;
stepCountTextureDesc.Usage = D3D11_USAGE_DEFAULT;
stepCountTextureDesc.BindFlags = D3D11_BIND_RENDER_TARGET;
stepCountTextureDesc.CPUAccessFlags = 0;
stepCountTextureDesc.MiscFlags = 0;

// Create the step count texture
hr = g_d3dDevice->CreateTexture2D(&stepCountTextureDesc, NULL, &g_StepCountTexture);
if (FAILED(hr)) return false;

// Setup the description of the render target views.
D3D11_RENDER_TARGET_VIEW_DESC stepCountRenderTargetViewDesc;
stepCountRenderTargetViewDesc.Format = stepCountTextureDesc.Format;
stepCountRenderTargetViewDesc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2D;
stepCountRenderTargetViewDesc.Texture2D.MipSlice = 0;

// Create the render target view.
hr = g_d3dDevice->CreateRenderTargetView(g_StepCountTexture, &stepCountRenderTargetViewDesc, &g_StepCountRenderTargetView);
if (FAILED(hr)) return false;

// Setup the step count staging texture description.
D3D11_TEXTURE2D_DESC stepCountStagingTextureDesc;
ZeroMemory(&stepCountStagingTextureDesc, sizeof(stepCountTextureDesc));
stepCountStagingTextureDesc.Width = g_clientWidth;
stepCountStagingTextureDesc.Height = g_clientHeight;
stepCountStagingTextureDesc.MipLevels = 1;
stepCountStagingTextureDesc.ArraySize = 1;
stepCountStagingTextureDesc.Format = DXGI_FORMAT_R32_UINT;
stepCountStagingTextureDesc.SampleDesc.Count = 1;
stepCountStagingTextureDesc.Usage = D3D11_USAGE_STAGING;
stepCountStagingTextureDesc.BindFlags = 0;
stepCountStagingTextureDesc.CPUAccessFlags = D3D11_CPU_ACCESS_READ;
stepCountStagingTextureDesc.MiscFlags = 0;

// Create the step count staging texture
hr = g_d3dDevice->CreateTexture2D(&stepCountStagingTextureDesc, NULL, &g_StepCountTextureStaging);
if (FAILED(hr)) return false;

Then the copy performed on each frame :

g_d3dDeviceContext->CopyResource(g_StepCountTextureStaging, g_StepCountTexture);
D3D11_MAPPED_SUBRESOURCE msr;
HRESULT hr = g_d3dDeviceContext->Map(g_StepCountTextureStaging, 0, D3D11_MAP_READ, 0, &msr);
if (FAILED(hr)) return;
g_StepCount = countSteps((BYTE*)msr.pData);
g_d3dDeviceContext->Unmap(g_StepCountTextureStaging, 0);

And the countSteps function :

unsigned int countSteps(BYTE* data) {
    return sizeof(data) / sizeof(data[0]); // -> 4 !?
}

The idea of the countSteps function is to iterate each texture pixel and add their unsigned int value together. The expected result would be above 1m, for now I get 17 sometimes 18 :)

How do I actually read my whole texture ?


texts: Why does Unity Eventsystem lag on first touch?

texts:
Hi I am making a very simple simple platformer game for android devices. I am using Unity's event system for player movement. The problem is when I touched the button first time there is a lag (hiccup) after then everything is ok. I have profiled my game there is a spike in EventSystem Update method.

here is the simplified code,

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

[RequireComponent (typeof(Rigidbody2D)) ]
[RequireComponent (typeof(BoxCollider2D)) ]
public class PlayerController : MonoBehaviour {

public float movementSpeed = 5f;
public float jumpForce = 5f;
public float distanceToGround = 0.2f;
public LayerMask staticCollider;
public playerState state;

private Rigidbody2D rBody;
public Transform leftmost;
public Transform rightmost;

Collider2D[] platforms = new Collider2D[2];
public int hrInput = 0;

// Use this for initialization
void Start ( ) {
    rBody = GetComponent<Rigidbody2D> ();

}

//FixedUpdate is framerate independent, and therefore completely unrelated to your framerate

void FixedUpdate ()
{
    state.grounded = isGrounded ();

    if (hrInput > 0) {
        MOVE_RIGHT ();
    }
    else if (hrInput < 0) {
        MOVE_LEFT ();
    } else {
        STOP_MOVE ();

    }

}

public bool isGrounded(){
    print ("ground");
    if (Physics2D.OverlapAreaNonAlloc (leftmost.position, rightmost.position, platforms, staticCollider) > 0) {
        return true;
    } else
        return false;
}

public void setHrInput (int h ) {
//    print (h);

    hrInput = h;
}

public void JUMP(){
    if(state.grounded){
        state.onAir = true;
      //  rBody.AddForce(Vector2.up * jumpForce, ForceMode2D.Impulse);
        rBody.velocity = Vector2.up * jumpForce;
    }
}

public void MOVE_LEFT(){
    rBody.velocity = new Vector2 (-1 * movementSpeed * Time.deltaTime, rBody.velocity.y);
}

public void MOVE_RIGHT(){
    rBody.velocity = new Vector2(1 * movementSpeed*Time.deltaTime, rBody.velocity.y);
}

public void STOP_MOVE(){
    rBody.velocity = new Vector2(0,rBody.velocity.y);
    }

} // end

Here is the profiler Image.

Please help me to fix this issue.


texts: how should I implement the Minimax Algorithm to a XCOM like turn-based game? I mean I should use score to each action like, move to cover, shoot, fall back etc. Or even is it possible to do that kind of game with Minimax algorithm?


texts: 2D AABB vs AABB Sweep : How to calculate hit normal?

texts:
I've implemented a 2D AABBvsAABB sweep cast into my game, however, I'm having difficulty calculating the hit normal of the sweep cast.

I have the sweep direction, both a and b AABB positions and xy min-maxs, first and last hit times to work with, but not the colliding edge(s) or normal direction. I just can't conceptualise an efficient solution to this specific problem. Any Ideas? :)

*edit

This is what I have so far - just a general implementation of Gomez's and Christer Ericson's AABB sweep. There's no hit normal, so while the normal calculation is a mystery to me I'm unable to produce any collision response for my character controller.

bool SweepVelAABBvsAABB(AABB a, AABB b, Vector2 v, out Vector2 outVel, out Vector2 norm )
    {
        outVel = v; //Initialise out velocity
        norm = Vector2.zero;

        if( AABBvsAABB(a,b) ) return true; //return early if a,b overlap

        v = -v;
        float hitTime = 0.0f;
        float outTime = 1.0f;

        if(v.x < 0.0f) //sweep is going right
        {
            if(b.max.x < a.min.x) return false;
            if(a.max.x < b.min.x) hitTime = Mathf.Max( (a.max.x - b.min.x) / v.x, hitTime );
            if(b.max.x > a.min.x) outTime = Mathf.Min( (a.min.x - b.max.x) / v.x, outTime );
        }
        else if(v.x > 0.0f) //sweep is going left
        {
            if(b.min.x > a.max.x) return false;
            if(b.max.x < a.min.x) hitTime = Mathf.Max( (a.min.x - b.max.x) / v.x, hitTime );
            if(a.max.x > b.min.x) outTime = Mathf.Min( (a.max.x - b.min.x) / v.x, outTime );
        }

        if(hitTime > outTime) return false;

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

        if(v.y < 0.0f) //sweep is going up
        {
            if(b.max.y < a.min.y) return false;
            if(a.max.y < b.min.y) hitTime = Mathf.Max( (a.max.y - b.min.y) / v.y, hitTime );
            if(b.max.y > a.min.y) outTime = Mathf.Min( (a.min.y - b.max.y) / v.y, outTime );
        }
        else if(v.y > 0.0f) //sweep is going down
        {
            if(b.min.y > a.max.y) return false;
            if(b.max.y < a.min.y) hitTime = Mathf.Max( (a.min.y - b.max.y) / v.y, hitTime );
            if(a.max.y > b.min.y) outTime = Mathf.Min( (a.max.y - b.min.y) / v.y, outTime );
        }

        if(hitTime > outTime) return false;

        outVel = -v * hitTime;

        return true;
    }


texts: Are the Marek-knows tutorials any good or still relevant?

texts:
Anyone have any experience with this? This hasn't been refereed as mush as it 'looks/sound' like.

https://www.marekknows.com/

Among many other products, the site provides game engine development video, which is around 45hours long. Starting from context creation, model loading, scene graph, animation. But it looks like a little old. Is it still useful?


texts: How do you deal with transparent fonts that you want to be white?

texts:
I'm a bit of a total amateur, but I thought I would learn how to make a simple game during quarantine.
However, I stumbled into a problem with fonts. I'm thinking about using the free font "Pixelmania" to show a score at the top of the screen. But the font is transparent! How do I make the inner part of the font white? Do I have to manually edit the font file myself? Or is there an easier way?


texts:
So, I'm fairly new to coding with unity and c#, and I want to change my animations based on the player's mouse position. This is my script so far:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour {
    public float moveSpeed = 2f;
    private bool right = true;
    private bool left = false;
    private bool up = false;
    private bool down = true;
    public Animation rightUpAnim;
    public Animation leftUpAnim;
    public Animation rightDownAnim;
    public Animation leftDownAnim;
    public string horizontalAxis;
    public string verticalAxis;
    private Vector2 movement = Vector2.zero;
    private Rigidbody2D rb;
    public Transform tf;
    public Animator an;

    private void Start() {
        rb = GetComponent<Rigidbody2D>();
    }
    void Update() {
        movement.x = Input.GetAxisRaw(horizontalAxis);
        movement.y = Input.GetAxisRaw(verticalAxis);
    }
    private void FixedUpdate() {
        rb.MovePosition(rb.position + movement * moveSpeed * Time.deltaTime);
        var mousePos = Input.mousePosition;
        mousePos.x -= Screen.width / 2;
        mousePos.y -= Screen.height / 2;
        if (mousePos.y > tf.position.y) {
            up = true;
            down = false;
        }
        else if (mousePos.y < tf.position.y) {
            down = true;
            up = false;
        }

        if (mousePos.x > tf.position.x) {
            right = true;
            left = false;
        }
        else if (mousePos.x < tf.position.x) {
            left = true;
            right = false;
        }

        if (left && up) {
            an.controller = leftUpAnim;
        }
        else if (right && up) {
            an.controller = rightUpAnim;
        }
        else if (left && down) {
            an.controller = leftDownAnim;
        }
        else if (right && down) {
            an.controller = rightDownAnim;
        }
    }
}

However, I get an error saying that 'Animator' does not contain a definition for 'controller'. What is the correct way to do this?


texts:
In my Unity2d-platformer, I need background to follow the character, so I just attach it. And when character turn left from right (or right-to-left), background turn too.

How can I make my background constant?


texts: iOS 9.3.5 WebSocket connection always closes with code 1006

texts:
I'm working on an app that uses a LabVIEW implemented server on the backend that is proxied via apache. It works great on desktops and android devices but on iPhone and iPad the websocket connection always fails and provides code 1006 in the close event. (No reason)

The request as received in LabVIEW:

GET /r9000_ws HTTP/1.1
Host: localhost:54663
Origin: http://192.168.1.191
Pragma: no-cache
Cache-Control: no-cache
Sec-WebSocket-Key: ucoJ2G1XNSntZAOBCfG+uQ==
Sec-WebSocket-Version: 13
Sec-WebSocket-Extensions: x-webkit-deflate-frame
User-Agent: Mozilla/5.0 (iPad; CPU OS 9_3_5 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Mobile/13G36 Safari/601.1
X-Forwarded-For: 192.168.1.193
X-Forwarded-Host: 192.168.1.191
X-Forwarded-Server: localhost
Upgrade: WebSocket
Connection: Upgrade

And the response I'm sending back:

HTTP/1.1 101 Switching Protocols
Upgrade: WebSocket
Connection: Upgrade
Sec-WebSocket-Accept: NUDL0C4/691VkogIvxQRHM1xJA8=

I have tried this in both google chrome and safari on an older iPad. Unfortunately due to the fun of WebSocket security I can't get any useful information on where the failure resides. Thanks to anyone that can see what I'm missing!


texts:
In my libGDX 2D RPG-Game (like Zelda or something) I want to display some items as 3D-Objects. Since I'm using an OrthographicCamera like this:

this.gameWorldCam = new OrthographicCamera();
this.hudCam = new OrthographicCamera();
gameWorldCameraViewport = new ExtendViewport(FRUSTUM_WIDTH, FRUSTUM_HEIGHT, gameWorldCam);

I don't know how to render 3D-Object on it. In my render loop I call this:

// 2D
spritebatch.begin();
...
spritebatch.end();

// ----------------------------------------------
// Just some hardcoded model creation for testing
// ----------------------------------------------
Model model;
ModelInstance instance;
ModelBuilder modelBuilder = new ModelBuilder();
model = modelBuilder.createBox(
  5f,
  5f,
  5f,
  new Material(ColorAttribute.createDiffuse(Color.GREEN)),
  Usage.Position | Usage.Normal
);
instance = new ModelInstance(model);
// ---------------------------------------------

// 3D
modelBatch.begin(gameWorldCam);
modelBatch.render(instance);
modelBatch.end();

// 2D
spritebatch.begin();
...
spritebatch.end();

What do I have to do, to get the proper result? Right now, nothing of the green 3D cube is visible.


texts: Client side prediction in 2D rigid-body physics

texts:
I'm currently working on 2D rigid-body physics multiplayer game using Matter.js for physics (both the client and server side) and Phaser3 for rendering. Both the server and the client run the simulation and the server is authoritative.

The whole game consists of multiplayer players (who can collide with each other) and objects (boxes, balls, etc).

For now, I'm working on the client side prediction and while I understand the main concept, I just can't get it right.

Every game tick I gather the client inputs, store them locally, timestamp them and send to the server, while at the same time I start moving the player forward (by applying force). When the server receives the inputs, it processes them (by applying the same forces to the player). The server then sends the current state (coordinates, velocity, rotation, last processed input timestamp, etc) to all players at 20hz.

This is the part where it gets tricky. What I currently do, is I force the player to the coordinates sent from the server and apply the same velocity (both X and Y). After that, I remove all locally stored inputs which are older than the last processed input and apply them instantly in a single frame, by doing multiple physics steps.

With low latency (20-30ms) it works out quite well, with some jittering when rapidly changing the player direction or when I'm colliding with other players/objects, but with higher latencies 70-110ms, the prediction goes completely off. I can see the player constantly being pulled back and forth and the whole game becomes unplayable.

I can't wrap my head around, what exactly am I doing wrong? Is client side prediction even the correct way of handling this sort of thing in a rigid-body physics-based game?

Also, I turned off state updating from the server and noticed that the position in the server and locally sometimes goes completely off, for example when I'm jumping, running and quickly changing direction. I believe that means that the physics engine is not deterministic?


texts: Enemy explosion offSet is displaced away from desired point of origin

texts:
In the game, when the enemy is hit and explodes the explosion animation appears offset to the bottom right corner of the dead enemy's center point.

I ran tests to adjust the explosion positioning with no luck. The debugger says that "this.offSet.y" & "this.offSet.x" are -100. I can't seem to know how to adjust that as well.

Image example:

Here are the code snippets & CSS for bonus:

Explosion JS

class Explosions {
    constructor (assetName) {
        this.count = 0;
        this.offSet = undefined;
        this.setOffSet(assetName);

    }

    setOffSet(assetName) {
        let asset = GameManager.assets[assetName];
        this.offSet = new Point ((asset.width/2)*-1, (asset.height/2)*-1);
    }

createExplosion(position) {
    let div = document.createElement("div");
        div.classList.add("explosion");
        let divId = 'explosion_' + this.count;
        div.id = divId;
        console.log(position);
        div.style.left = (position.x + this.offSet.x) + 'px';
        div.style.top = (position.y  + this.offSet.y) + 'px';
        $(GameSettings.gameAreaDiv).append(div);
        setTimeout(function() {
            $('#' + divId).remove();
        }, GameSettings.explosionTimeout);

        this.count++;
}

}

Explosion CSS

@keyframes explosion {
    0%   {background-image: url("../../assets/explosion/smallexplode1.png");}
    10%   {background-image: url("../../assets/explosion/smallexplode2.png"); }
    20%   {background-image: url("../../assets/explosion/smallexplode3.png"); }
    30%   {background-image: url("../../assets/explosion/smallexplode4.png"); }
    40%   {background-image: url("../../assets/explosion/smallexplode5.png");}
    60%   {background-image: url("../../assets/explosion/smallexplode6.png");opacity: 0.9;}
    80%   {background-image: url("../../assets/explosion/smallexplode7.png");opacity: 0.8;}
    90%   {background-image: url("../../assets/explosion/smallexplode8.png");opacity: 0.5;}
    100%   {background-image: url("../../assets/explosion/smallexplode9.png");opacity: 0.3;}
}

.explosion {
  width: 100px;
  height: 100px;
  position: absolute;
  left: 500px;
  top: 300px;
  animation-name: explosion;
  animation-duration: 0.8s;
  background-repeat: no-repeat;
  z-index: 20;
}

Any indication what the cause is?

Let me know if there are any other snippets that needs adding, and if you can please be patient with me since I'm student programmer that is still learning.

Thank you


texts: Skill system in turn-based board-like RPG

texts:
I'm working on the implementation of a turn-based board RPG (like Descent: Journeys in the Dark) to improve my C++ skills and learn something about game-dev.

I have already done with general stuff, like Heroes and Monsters, their common action (move, attack) which they can do every turn. Now I want to add some skill system, and I'm not quite sure how to do it. I'm thinking about some skills that can be used after particular action is done (e.g. 'after attack dices are rolled, add +X to damage' or 'after another hero is revived, recover X HP'), some of those skill hero can gain by leveling up or with some item, but I don't know, how to implement this kind of skills.
Maybe adding a checking for a game state could be a good idea, but that leads to tens of different options and doesn't look like efficient way to implement.

Could anyone please help me?


texts: Imageeffects: No need for Framebuffer? Just use Textures and Shaders?

texts:
I am doing simple Image Effects, and always i see in examples, that people are binding textures to framebuffers. Why can't i just use textures?

So the process would be.

1) Input Texture
2) Shader: Do Processing on this Shader
3) Render to the same Texture

So no need for framebuffer? This step is done completely linear...no off-screen rendering. So cani say that i don't need a framebuffer in this scenario?

thanks!


texts:
I'm currently working on a 3D Game and I want a unique graphic style.

Concept Arts have a cool "painted" look. You can clearly see that this picture is painted on a graphic tablet.
(https://i.stack.imgur.com/pnyzB.jpg) - Source: Destiny Concept Arts

How can you achieve that kind of graphics?
I guess you draw the texture just like the concept art and apply a light cel-shader?


texts: Can game replays be used as cheat protection?

texts:
Say you're writing a complex turn based multiplayer strategy game in the browser (i.e. JavaScript). The game state is big and complicated (think line of sight calculations in a 3d world). There can be many simultaneous games on different maps. Thus keeping all of those maps in memory on the server and verifying every single client action as it happens would quickly become prohibitively expensive. So we're faced with the situation that we cannot trust anything from the client and we cannot verify every individual client action on the server due to cost.

Has anyone experimented with recording game sessions and running offline/asynchronous verification on them as a cheat deterrent? Ideally, the players themselves would get suspicious and spot check each others' replays. Obviously there would be a significant delay between the cheat happening and the player getting flagged, but in a long-running strategy game with persistent state, I think this would be a significant disincentive.

Do you know of such examples? Have they worked well?


texts: Networking Questions: Serialization and Frequent Small Packets or Fewer Large Packets

texts:
I'm working with a socket server and I'm trying to decide how to update all of the clients.

I'm currently sending few packets with entire objects serialized in JSON. In most cases this adds a lot of overheard in the form of unneeded data. This to me is a no brainer, get rid of the serialization and send only what is needed.

Lets say I have four server-side AIs. Should I send all four of the AIs in one giant update, therefore serializing only the needed data or should I send each one in a separate update?


texts:
I'm using DirectX 9 and attempting to write a simple terrain generation object.

I'm running into trouble with the rendering - I'm hoping that this is a common problem, and someone could spot the problem by the output:

I've generated vertices, indices and I'm attempting to render a triangle strip (as it's supposed to be the most efficent way to do a grid.

It looks like I've made some kind of error in vertex or index generation, although I can't see what.  I've posted my terrain class here.  Can someone have a look and suggest what I've done wrong?


texts: How can I speed up the shapes drawing on high-density devices?

texts:
I have a game that should draw many shapes on the canvas and in every frame these shapes position will change, the game is running smooth but after adding more shapes some jerk arise and it drops some of frames. And this is just happening in high-density devices (more than 320 dpi).

public void run() {
    while (mRunning) {
        if (mSurfaceHolder.getSurface().isValid()) {

            synchronized (mSurfaceHolder){
                canvas = mSurfaceHolder.lockCanvas();

                canvas.drawColor(Color.BLACK);
                drawOnCanvas(canvas);

                mSurfaceHolder.unlockCanvasAndPost(canvas);
            }
        }
    }
}

draw function

public void drawOnCanvas(Canvas canvas) {
    new Thread(changeGamePosRunnable).start();

    for (int i = 0; i < obstacles.size(); i++) {
        Obstacle obstacle = obstacles.get(i);
        x= obstacle.getX();
        y=obstacle.getY();

        canvas.drawLine(0, 0, x, y, linePaint);
        canvas.drawBitmap(bitmap,x,y,null);
    }
}

I have created bitmaps in the constructor, initializing all variables out of the game loop, using SurfaceView and implements Runnable, added Thread.sleep(5); to while loop, tried to decrease bitmap size to about 240 bytes, tried to draw circle instead of bitmap again no change.

It's so strange that the drawing function is so slow in high-density devices, I tried to use some bitmaps as buffer and use them in 3 threads but the game sometimes draw on the wrong location. also I think drawing on another bitmap is not a right solution.

How can I speed things up? The quality does not matter, I just need some more speed.


texts: How do I make spring animation for a 2D game?

texts: I want to create a realistic spring object, as a sprite, that compresses and expands when a force is applied and released, respectively. The only thing I know is that it requires some complex animation, but have no idea how to do it. I'm using the Unity engine, but otherwise, it is a general question.


texts: OpenGL Shading Program Object Memory Requirement

texts:
gDEbugger states that OpenGL's program objects only occupy an insignificant amount of memory. How much is this actually? I don't know if the stuff I looked up in mesa is actually that I was looking for but it requires 16KB [Edit: false, confusing struct names, less than 1KB immediate, some further behind pointers] per program object. Not quite insignificant.

So is it recommended to create a unique program object for each object of the scene? Or to share a single program object and set the scene's object's custom variables just before its draw call?


texts: How do I create a HUD that appears to occupy 3D space/can animate?

texts:
I'm working with a group to try and make a first person space platformer in Unity, and was wondering if there would be anyway to create a HUD that moves and reacts to player actions, specifically looking around - similar to the way the HUD moves in Metroid Prime. I'd also like it appear projected onto the inside of a helmet.

I'm not entirely sure what best-practice would be in this situation. Should we just attach the GUI elements to transparent objects in 3D space, then parent them to the main camera, essentially building our HUD with actual objects; or is there another way that would be more efficient? I'm still very new to game development, but this is something we'd really like to have in our game if at all possible.


texts:
I am a newbie game developer.

I have one problem. Consider the following case.

I have a simple game with only one object - a ball. A ball can move only up and down from one side to another.

A User is allowed to set the game time  and ball iteration count. An iteration is when the ball goes up to the topmost point and goes back to the bottommost point.

It should complete all iterations for the time user has set.

Here is an example.

Consider that a user has set the game time to 60 seconds, and the ball iterations option to 30.

We can find how much time do we have for an iteration 60/30 = 2 seconds. So the ball should complete the iteration for two seconds.

Let's assume we have a known frame rate and it is 30ms (update and drawing). So a single loop iteration takes 2000ms.

Next find iterations per a complete ball movement 2000/30 = 66 iterations. Also let's imagine that a distance from one side to another is 2000px.

So the ball need to complete 4000px per iteration.

Finally we can find out our movement delta 4000px/66 = 60 px . So ball will move 60px per a loop iteration.

But what to do if I don't frame rate, but what is more interesting what to do when the framerate is not static and we need to correlate it every time.

Please suggest an algorithm or an approach to solve this problem.

It seems that there should be a function, that will calculate position of a ball by the time passed from the game start, like sin (because ball is bouncing)

Thanks.


texts:
I wonder how Unity's execution order really works.
There's an ordered list at https://docs.unity3d.com/Manual/ExecutionOrder.html, but how does this work when there are different gameobjects involved? Will Unity first run the specific function for all the monobehaviours in the scene before it proceeds to the next function? Or will each monobehaviour go through that specific order of functions before Unity goes to the next monobehaviour? Or is it more complex? It isn't really clear to me from the documentation.

For example, normally Start() gets called before Update(), however when I was debugging, Update() on my Avatar prefab got called before Start() of my Camera child object. Is this supposed to happen?


texts: How should I manage meshes for the streets of a 3D city map in Unity?

texts:
I was recreating a small city in Unity3D and was going to place streets and pathways according to a sketch. I'm building for Android and the city is quite small; I'm planning to have the entire road mesh(es) loaded during play, without a load/unload algorithm. I made a few road meshes in Sketchup and imported them into Unity, but was unsure on how to manage them. I thought of two strategies but was unable to identify the pros and cons of either:

Place all the separate road meshes in Unity and position them, recreating the sketch and make them children of an empty GameObject to order them in the Editor window.
Create the entire city roadmap in Sketchup, making it a single and complete mesh. Then, import it into Unity and that's it.

The city is quite small and I'm planning to have the entire road mesh(es) loaded during play, without a load/unload algorithm. I'm building for Android.

Which strategy should I prefer in this situation? Or are both basically the same?


texts: How can I select a object (canvas) with tag using Physics.Raycast?

texts:
I made this C# script, becase I want select a Button of the menu(canvas) for choice the dificulty of the game, but I don't want select with mouse I just want select with Aim, and I made this script for make this happen, but don't it works. What am I doing wrong ?

My C# Script:

using UnityEngine;
using System.Collections;

public class AimManager : MonoBehaviour {

    float TimeInterval = 2f;
    float time = 0;
    public UI_cozinha uiCozinha;

    // Use this for initialization
    void Start () {

    }

    // Update is called once per frame
    void Update () {
        RaycastHit hit;

        if (Physics.Raycast(transform.position, transform.forward, out hit))
        {
            if(time >= TimeInterval)
            {
                if((hit.transform.tag == "ButtonE"))
                {
                    uiCozinha.setDiff(5);
                }if((hit.transform.tag == "ButtonM"))
                {
                    uiCozinha.setDiff(7);
                }
                if ((hit.transform.tag == "ButtonH"))
                {
                    uiCozinha.setDiff(10);
                }
                time = 0;
            }
            else
            {
                time += Time.deltaTime;
            }
        }

    }
}

CardBoard View:

Normal GameView:

  Image of Menu(canvas): i.stack.imgur.com/MRIbl.png


texts: Unity - Exposing a function to the inspector

texts:
I wish to expose a script's function to the inspector, but I have no clue how to. I found something about Invoke() which was a start, but it isn't clear how to finish.

My code for the class:

 [System.Serializable]
     class MoveAction : UnityEvent<MonoBehaviour>, IUIAnimationEvent
     {
         #region Move
         public MoveAction()
         {

         }
         //to ensure only one mover coroutine can be active.
         IEnumerator moveRoutine = null;
         #region Solution 2: using fields and not parameters
         Transform from;
         Transform to;
         float overTime;
         public delegate void UIchain(MonoBehaviour mono);
         public event UIchain NEXT_FUNCTION;

         public MoveAction(Transform from, Transform to, float overTime, IUIAnimationEvent chain)
         {
             this.from = from;
             this.to = to;
             this.overTime = overTime;

         }
         public void Move(MonoBehaviour mono)
         {
             if (moveRoutine != null)
             {
                 mono.StopCoroutine(moveRoutine);
             }
             moveRoutine = _Move(from, to, overTime, mono);
             mono.StartCoroutine(moveRoutine);
             Invoke(mono);
         }
         IEnumerator _Move(Transform from, Transform to, float overTime, MonoBehaviour mono)
         {
             Vector2 original = from.position;
             float timer = 0.0f;
             while (timer < overTime)
             {
                 float step = Vector2.Distance(original, to.position) * (Time.deltaTime / overTime);
                 from.position = Vector2.MoveTowards(from.position, to.position, step);
                 timer += Time.deltaTime;
                 yield return null;
             }
             if(NEXT_FUNCTION != null)
             {
                 NEXT_FUNCTION(mono);
             }
         }

This is a lot of code, but the interesting part is the Move(MonoBehaviour mono) function. I want to expose that to the editor. How?

EDIT:

Something like this would be preferable:


texts:
I'm trying to manually create a ModelContent instance that includes custom Bone data in a custom ContentProcessor in the XNA Content Pipeline. I can't seem to create or assign manually created bone data due to either private constructors or read-only collections (at every turn).

The code I have right now that creates a single triangle ModelContent that I'd like to create a bone for is:

MeshContent mc = new MeshContent();
mc.Positions.Add(new Vector3(-10, 0, 0));
mc.Positions.Add(new Vector3(0, 10, 0));
mc.Positions.Add(new Vector3(10, 0, 0));

GeometryContent gc = new GeometryContent();
gc.Indices.AddRange(new int[] { 0, 1, 2 });
gc.Vertices.AddRange(new int[] { 0, 1, 2 });
mc.Geometry.Add(gc);

// Create normals
MeshHelper.CalculateNormals(mc, true);

// finally, convert it to a model
ModelContent model = context.Convert<MeshContent, ModelContent>(mc, "ModelProcessor");

The documentation on XNA is amazingly sparse. I've been referencing the class diagrams created by DigitalRune and Sean Hargreaves blog, but I haven't found anything on creating bone content.

Once the ModelContent is created, it's not possible to add bones because the Bones collection is read-only. And it seems the only way to create the ModelContent instance is to call the standard ModelProcessor via ContentProcessorContext.Convert. So it's a bit of a catch-22.

The BoneContent class has a constructor but no methods except those inherited from NodeContent... though now (true to form) maybe I've realized the solution by asking the question. Should I create a root NodeContent with two children: one MeshContent and one BoneContent as the root of my skeleton; then pass the root NodeContent to ContentProcessorContext.Convert?

Off to try that now...


texts: Partial Shader Signatures HLSL D3D11 C++

texts:
I had been debugging a problem I was having in a single shader file with 2 functions in it. I'm using DirectX 11, vs_5_0 and ps_5_0. I have stripped it down to its basic components to understand what was going wrong with the shaders, because the different named components of the Pixel and Vertex shaders were swapping the data being input:

void QuadVertex ( inout float4 position : SV_Position,
            inout float4 color : COLOR0,
            inout float2 tex : TEXCOORD0 ) {
    // ViewProject is a 4x4 matrix,
    // just included here to show the simple passthrough of the data
    position = mul(position, ViewProjection);
}

And a Pixel Shader:

float4 QuadPixel (  float4 color : COLOR0,
            float2 tex : TEXCOORD0 ) : SV_Target0 {
    // Color is filled with position data and tex is
        // filled with color values from the Vertex Shader
    return color;
}

The ID3D11InputLayout and associated C++ code correctly compiles the shaders and sets them up with some simple primitive data:

        data[0].Position.x = 0.0f * 210;
        data[0].Position.y = 1.0f * 160;
        data[0].Position.z = 0.0f;
        data[1].Position.x = 0.0f * 210;
        data[1].Position.y = 0.0f * 160;
        data[1].Position.z = 0.0f;
        data[2].Position.x = 1.0f * 210;
        data[2].Position.y = 1.0f * 160;
        data[2].Position.z = 0.0f;
        data[0].Colour = Colors::Red;
        data[1].Colour = Colors::Red;
        data[2].Colour = Colors::Red;
        data[0].Texture = Vector2::Zero;
        data[1].Texture = Vector2::Zero;
        data[2].Texture = Vector2::Zero;

When used with the shader, the float4 color always ended up with the position data, and the float2 tex always ended up with the color data. After a moment, I figured out that the shader's input and output signatures needed to be in the correct order and the correct format and be laid out in the exact order of the output from the Vertex Shader, regardless of the semantics:

float4 QuadPixel (  float4 pos : SV_Position,
            float4 color : COLOR0,
            float2 tex : TEXCOORD0 ) : SV_Target0 {

    return color;
}

After finding this out, My question is: Why don't the semantics map the appropriate components when going from Vertex Shader to Pixel Shader? Is there any way that I can make it so certain semantics are always mapped to other semantics, or do I always have to follow the rigid Shader Signature (in this case, Position, Color, and Texture) ?

As a side note for why I'm asking: I know that when using XNA, my shader signatures for functions could differ in position and even drop items from Vertex Shader to Pixel Shader function parameters, having only the COLOR0 and TEXCOORD0 components being used (and it would still match up correctly). However, I also know that XNA relied on DX9 (and maybe a little DX10) implementation, and that maybe this kind of flexibility no longer exists in DX11?


texts: Procedural sidescroller world gen algorithm by seed

texts:
I'm trying to recreate a procedural side-scroller world gen algorithm by using a seed and I find my self stuck trying to solve a particular problem.

Seed generation applies very well with voxel-like games, but it seems slightly less suitable to generate randomly placed sprites with differing widths for sidescrollers

Here's a picture explaining the problem:

Assuming I load the game at screen-2, I'd be e.g. between coordinates 100 and 0, and the seed function would tell me that between coordinates 100 and 0 there's the sprite of a big block of mountains to render, whose center lies in the coordinate interval [0, 100] ( the center of the sprite is the pink dot in the picture)

assuming I'm loading the game from coordinate 300, as is the case in screen-1, a seed function wouldn't be able to recognize the presence of a mountain sprite there, even though part of it is still visible in the interval between e.g. [250, 350]

A straightforward solution would be to sample from the seed function the interval including the biggest-sized object in the game, which is of course highly inefficient given many objects only cover a fraction of the screen.

How is this type of problem generally solved? Are algorithms based on seeds unsuitable for this particular project? If this is the case, what could be a reasonable alternative?


texts: Shadow mapping with deffered shading for directional lights - shadow map projection problem

texts:
I'm trying to implement shadow mapping to my engine. I started with directional lights because they seemed to be the easiest one, but I was wrong :) I have implemented deferred shading and I retrieve position from depth. I think that there is the biggest problem but code looks ok for me.

Now more about problem:

Shadow map projected onto meshes looks bad scaled and translated and also some information from shadow map texture aren't visible.

Yellow frustum is light frustum and I have mixed shadow map preview and actual scene. As you can see shadows are in wrong place and shadow of cone and sphere aren't visible.

Could you look at my codes and tell me where I have a mistake?

// create shadow map
if(!_shd)glGenTextures(1, &_shd);
glBindTexture(GL_TEXTURE_2D, _shd);
glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, 1024, 1024, 0, GL_DEPTH_COMPONENT, GL_FLOAT,NULL); // shadow map size
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, _shd, 0);

glDrawBuffer(GL_NONE);

// setting camera
Vector dire=Vector(0,0,1);
ACamera.setLookAt(dire,Vector(0));
ACamera.setPerspectiveView(60.0f,1,0.1f,10.0f); // currently needed for proper frustum corners calculation

Vector min(ACamera._point[0]),max(ACamera._point[0]);
for(int i=0;i<8;i++){
    max=Max(max,ACamera._point[i]);
    min=Min(min,ACamera._point[i]);
}

ACamera.setOrthogonalView(min.x,max.x,min.y,max.y,-max.z,-min.z);

glBindFramebuffer(GL_DRAW_FRAMEBUFFER, _s_buffer); // framebuffer for shadow map

// rendering to depth buffer

glBindFramebuffer(GL_DRAW_FRAMEBUFFER, _g_buffer);

Shaders["DirLight"].set(true);

Matrix4 bias;
bias.x.set(0.5,0.0,0.0,0.0);
bias.y.set(0.0,0.5,0.0,0.0);
bias.z.set(0.0,0.0,0.5,0.0);
bias.w.set(0.5,0.5,0.5,1.0);

Shaders["DirLight"].set("textureMatrix",ACamera.matrix*Projection3D*bias); // order of multiplications are 100% correct, everything gives mi the same result as using glm

glActiveTexture(GL_TEXTURE5);
glBindTexture(GL_TEXTURE_2D,_shd);

lightDir(dir); // light calculations

Vertex Shader makes nothing related to shadow calculatons

Pixel shader function which calculates if pixel is in shadow or not:

float readShadowMap(vec3 eyeDir)
{
// retrieve depth of pixel
float z = texture2D(depth, gl_FragCoord.xy/screen).z;

vec3 pos = vec3(gl_FragCoord.xy/screen, z);

// transform by the projection and view inverse
vec4 worldSpace = inverse(View)*inverse(ProjectionMatrix)*vec4(pos*2-1,1);

worldSpace /= worldSpace.w;

vec4 coord=textureMatrix*worldSpace;

float vis=1.0f;
if(texture2D(shadow, coord.xy).z < coord.z-0.001)vis=0.2f;

return vis;
}

I also have question about shadows specifically for directional light. Currently I always look at 0,0,0 position and in further implementation I have to move light frustum along to camera frustum. I've found how to do this here: http://www.gamedev.net/topic/505893-orthographic-projection-for-shadow-mapping/ but it doesn't give me what I want. Maybe because of problems mentioned above, but I want know your opinion.

EDIT:

vec4 worldSpace is position read from depht of the scene (not shadow map). Maybe I wasn't precise so I'll try quick explain what is what: View is camera view matrix, ProjectionMatrix is camera projection,. First I try to get world space position from depth map and then multiply it by textureMatrix which is light view light projectionbias. Rest of code is the same as in many tutorials. I can't use vertex shader to make something like gl_Position=textureMatrix*gl_Vertex and get it interpolated in fragment shader because of deffered rendering use so I want get it from depht buffer.

EDIT2:

I also tried make it as in Coding Labs tutorial about Shadow Mapping with Deferred Rendering but unfortunately this either works wrong.


texts: How to make it so when my player dies, the game will restart?

texts:
when ever my player dies, he will be sent to the Menu State and when he plays again, he can start from the same place where he left off which results in an endless death. what I want is that when my game shows the Menu State, the game always resets.

How do I do that?

My Game Class

import java.awt.Graphics;
import java.awt.image.BufferStrategy;

public class Game implements Runnable {

private Display display;
private int width,
            height;
public String title;

private boolean running = false;
private Thread thread;

private BufferStrategy bs;
private Graphics g;

//States
public State gameState;
public MenuState menuState;
public SplashScreen splashscreen;

//Input
private KeyManager keyManager;
private MouseManager mouseManager;

//Camera
private GameCamera gameCamera;

//Handler
private Handler handler;

public Game(String title, int width, int height){
    this.width = width;
    this.height = height;
    this.title = title;
    keyManager = new KeyManager();
    mouseManager = new MouseManager();
    }
    //HERE IS MY INIT() METHOD

    private void init(){
    display = new Display(title, width, height);
    display.getFrame().addKeyListener(keyManager);
    display.getFrame().addMouseListener(mouseManager);
    display.getFrame().addMouseMotionListener(mouseManager);
    display.getCanvas().addMouseListener(mouseManager);
    display.getCanvas().addMouseMotionListener(mouseManager);
    Assets.init();

    handler = new Handler(this);
    gameCamera = new GameCamera(handler, 0, 0);

    gameState = new GameState(handler);
    menuState = new MenuState(handler);
    splashscreen = new SplashScreen(handler);
    State.setState(splashscreen);
}

private void tick(){
    keyManager.tick();

    if(State.getState() != null);
        State.getState().tick();
}

private void render(){
    bs = display.getCanvas().getBufferStrategy();
    if(bs == null){
        display.getCanvas().createBufferStrategy(3);
        return;
    }
    g = bs.getDrawGraphics();
    //Clear Screen
    g.clearRect(0, 0, width, height);
    //Draw Here!

    if(State.getState() != null);
        State.getState().render(g);

    //End Drawing!
    bs.show();
    g.dispose();
}

public void run(){

    init();

    int fps = 1000;
    double timePerTick = 1000000000 / fps;
    double delta = 0;
    long now;
    long lastTime = System.nanoTime();
    long timer = 0;
    int ticks = 0;

    while(running){
        now = System.nanoTime();
        delta += (now - lastTime) / timePerTick;
        timer += now - lastTime;
        lastTime = now;

        if(delta >= 1){
            tick();
            render();
            ticks++;
            delta--;
        }

        if(timer >= 1000000000){
            System.out.println("Ticks and Frames: " + ticks);
            ticks = 0;
            timer = 0;
        }

    }

    stop();

}

public KeyManager getKeyManager(){
    return keyManager;
}

public MouseManager getMouseManager(){
    return mouseManager;
}

public GameCamera getGameCamera(){
    return gameCamera;
}

public int getWidth(){
    return width;
}

public int getHeight(){
    return height;
}

public synchronized void start(){
    if(running)
        return;
    running = true;
    thread = new Thread(this);
    thread.start();
}

public synchronized void stop(){
    if(!running)
        return;
    running = false;
    try {
        thread.join();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}
}

My GameState

import java.awt.Graphics;

public class GameState extends State {

private Player player;
private World world;

public GameState(Handler handler){
    super(handler);
    world = new World(handler, "res/worlds/world1.txt");
    handler.setWorld(world);
    player = new Player(handler, 200, 200);
}

@Override
public void tick() {
    world.tick();
    player.tick();

    if(handler.getMouseManager().isRightPressed())
        System.exit(0);
}

@Override
public void render(Graphics g) {
    world.render(g);
    player.render(g);
}
}


texts: How do I make the PS4 controller vibrate in Unity3D on mac?

texts: I am currently working on a 2D game in Unity3D with an option to play with a gamepad/controller. I would like the PS4/dualshock 4 controller to vibrate. I am on mac. I have looked into Xinput but I think it is only for Windows, I may be wrong.


texts: How do I consume the input events in the new 4.6 unity gui system? If I click on a button for instance I don't want anything else non GUI related that might be listening for mouse input to react to the event.


texts: How to fix stretched splash image in Unity?

texts:
I'm trying to add my own splash on my Unity project. However, when I implement it, the splash is stretched vertically, real bad.

Here is the screenshot:

While the original splash is:

I'm not altering the settings for the sprite that much:

How to fix that problem? I'm using a 1080x1080 PNG file for the splash and Unity 5.5.0f for building the application. Altering the resolution of the PNG results no luck. Am I missing something important here?

EDIT: Sorry for the late mention, but I've made the border on the sprite editor. Still no luck.


texts: ForEach vs For loop in JavaScript | Which is more efficient?

texts:
I was wondering which for loop is less hard on the computer, and why it is

Example:

    var greet = ["Hey", "Howdy", "Hello", "Hi"];
    greet.forEach(function(index){
        console.log(index);
    });

vs

    var greet = ["Hey", "Howdy", "Hello", "Hi"];
    for(var i = 0; i < greet.length; i++) {
        console.log(greet[i]);
    }


texts: How to make a character move with WASD in unity

texts:
So, I have been trying for so long to make a WASD movement script, and I can't. It has come to the point that I am even getting the code off the official Unity site.

And here is the code:

using UnityEngine;
using System.Collections;

// This script moves the character controller forward
// and sideways based on the arrow keys.
// It also jumps when pressing space.
// Make sure to attach a character controller to the same game object.
// It is recommended that you make only one call to Move or SimpleMove per frame.

public class ExampleClass : MonoBehaviour
{
    CharacterController characterController;

    public float speed = 6.0f;
    public float jumpSpeed = 8.0f;
    public float gravity = 20.0f;

    private Vector3 moveDirection = Vector3.zero;

    void Start()
    {
        characterController = GetComponent<CharacterController>();
    }

    void Update()
    {
        if (characterController.isGrounded)
        {
            // We are grounded, so recalculate
            // move direction directly from axes

            moveDirection = new Vector3(Input.GetAxis("Horizontal"), 0.0f, Input.GetAxis("Vertical"));
            moveDirection *= speed;

            if (Input.GetButton("Jump"))
            {
                moveDirection.y = jumpSpeed;
            }
        }

        // Apply gravity. Gravity is multiplied by deltaTime twice (once here, and once below
        // when the moveDirection is multiplied by deltaTime). This is because gravity should be applied
        // as an acceleration (ms^-2)
        moveDirection.y -= gravity * Time.deltaTime;

        // Move the controller
        characterController.Move(moveDirection * Time.deltaTime);
    }
}

Then I have imported it to Unity, then it says 'GrapplingHook.cs is not defined' when I haven't even got a GrapplingHook.cs, so why is it doing it?

So why does this do that?


texts: Understanding a client/server relationship

texts:
I'm currently designing a simple game in C# and want to implement online multiplayer support. Before venturing onto doing something like this, I just had a few questions about clients and servers.

Is a server responsible for sending and receiving data to and from clients?
If a client wants to send data to another client, should it send the data to the server, and let the server send that data to the specified client?
When it comes to handling data, should the server have access the same classes the client does? This way the server can convert the bytes sent in, to a specific class? Or should the server just handle all the data in bytes, and send it back out if necessary?

Sorry if there are to many questions, any help would be appreciated!


texts:
I am new to game development but I heard, that already in the 80s with Prince of Persia, indie developers where capable to create textures from footage. I am developing a game and so far I get an illustrator to draw things I need.

I'd like to explore the opportunity of taking some video footage of complex movements and create some basic textures from it (as I guess Jordan Mechner did), so to then "feed" them to a more digital artist to draw "over" them in order to make them cartoonish and coherent with the style of the pre-existing in the game.

Anyone of you could also explore the answer for mobile game development? Any crazy mobile developer that did so already for a 2D game? :)


texts:
A quick search through the web suggests there's quite a few methods of potentially detecting back-culled faces on the CPU.

The purpose of the check is to evaluate whether to performing other operations such as tessellations is reasonable by dynamically altering the LOD of visible polys based on the number of polys on the screen.

What would your suggestions be for implementing this? Speed isn't necessarily the greatest concern - for this prototype mathematical simplicity is more important. Code snippets welcome :-)

Edit: It seems obvious to me to calculate the dot product based on the camera's viewing vector in world-space against the surface normal vector - but I'm asking this question because I'm intrigued as to why everyone and their (programming genius) dog seems to have an alternative method of handling this.


texts:
The following line fails in my class:

MeshRenderer nRenderer = _Sphere.AddComponent<MeshRenderer>();

This is the entire class. All works except the mentioned line.

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

public class SphereMaker : MonoBehaviour
{
    private GameObject _Sphere;

    void Start()
    {
        _Sphere = GameObject.CreatePrimitive(PrimitiveType.Sphere);
        _Sphere.AddComponent<MeshFilter>();

        MeshRenderer nRenderer = _Sphere.AddComponent<MeshRenderer>();
        Material nMat = new Material(Shader.Find("Universal Render Pipeline/Lit"));//I'm using the URP

        if (nMat == null)
        {
            Debug.LogError("no mat!!\n");
        }
        nMat.color = Color.red;

        nRenderer.material = nMat;

        float fSize = 0.4f;

        _Sphere.transform.localScale = new Vector3(fSize, fSize, fSize);
        _Sphere.transform.position = new Vector3(0, 0, 0);

    }
}

Does anybody see what I'm doing wrong?

Thank you!


texts: Difference between Unity's Camera.ScreenPointToRay and Camera.ScreenToWorldPoint?

texts: What is the difference between Unity's  Camera.ScreenPointToRay and Camera.ScreenToWorldPoint. And where we can use these. I've watched some tutorial and documentation but I didn't get a clear understanding.


texts: How can I block Copy/Paste from Input Fields in Unity?

texts: I don't want the user to write a text by copying and then pasting the content to an Input Field, how can I do that?


texts: What ways are there for making vector types available in scripting?

texts:
I use Google V8 engine to embed Javascript into my game for scripting. As interface to my native code, I already registered some C++ functions to the scripting context.

In the native code, I make intense use of the C++ library GLM which adds vector types and geometry functions. The naming is in a style that may be known from shader code, for example vec3, uvec2, normalize(), length(), and much more.

Now I would like to make these types available in scripting. That would be useful because of both, the geometry functions and the vector types. Especially, I want to use the vector types as parameters in the C++ functions I mapped to the Javascript context. At the moment I'm using arrays like float[3] instead of the vectors like vec3.

So I am looking for possible ways to bring GLM functionality into Javascript. This is what I can think of.

Create the most important types by hand, either in a Javascript file or injected from C++ code using object templates. Unfortunately, I cannot do this for all of the many functions in GLM. But it would better than nothing.
There might already be a GLM port of Javascript, which I haven't found on the internet.
I could pick a different geometry library for use in Javascript. For bound C++ functions, I'd have to translate their types into GLM ones then.
What can you think of...

Maybe there is a cool way to all the functionality of GLM over to Javascript. Are there things like C++ to Javascript source code converters? Or automatically binding a whole C++ namespace to scripting? I don't think that is possible. But Javascript is such a dynamic language, there must be a way to make the GLM types available for it.

What ways are there for making the vector types, and preferably also the useful geometry helper functions, available in scripting?


texts: How to do an infinite torus topology battlefield for over-the-shoulder perspective

texts:
I'm currently prototyping a simple two-player adversarial game, where the players are able to move around and shoot at each other with cannons. I would like the playing area to feel essentially unbounded, but I don't want one of the players to be able to stall the game by just rushing away from his opponent.

The standard solution to this dilemma in the 2D days was to introduce a torus topology: if a player leaves the screen from the top, they enter at the bottom. If they leave from the right, they enter from the left. I am looking for a workable analogon to this system for games played from a third-person perspective.

Technically you can implement this just fine. However, since they lack complete battlefield overview, it will confuse the heck out of the players if their opponent pops out of/into existence.

Currently I'm thinking of combining the following techniques:

A map that shows top-down overview. This provides the context you used ot have in the 2D game.
Rendering the closest periodic image of the enemy as solid. This is not necessarily the one in the same "screen".
Rendering the others as "ghosts".

Will this be enough to make this design work? Can it be made to work better with some tweaks? Is torus topology and third person perspective just a really bad idea?


texts: How can I implement dialog trees into my game?

texts: What is the best way to implement a dialog tree system in my game? I want an NPC to give the player different sets of responses, some which may only appear when the Player has an item or a previous event has occurred.


texts: Will polishing my current project be a better learning experience than starting a new one?

texts:
I started programming many years ago. Now I'm trying to make games. I have read many recommendations to start cloning some well known games like galaga, tetris, arkanoid, etc. I have also read that I should go for the whole game (including menus, sound, score, etc.).

Yesterday I finished the first complete version of my arkanoid clone. But it is far from over. I can still work on it for months (I program as a hobby in my free time) implementing a screen resolution switcher, remap of the control keys, power-ups falling from broken bricks, and a huge etc.

But I do not want to be forever learning how to clone ONE game. I have the urge to get to the next clone in order to apply some design ideas I have come upon while developing this arkanoid clone (at the same time I am reading the GoF book and much source code from Ludum Dare 21 game contest).

So the question is: Should I keep improving the arkanoid clone until it has all the features the original game had? or should I move to the next clone (there are almost infinite games to clone) and start mending the things I did wrong with the previous clone?

This can be a very subjective question, so please restrain the answers to the most effective way to learn how to make my own games (not cloning someone ideas). Thank you!

CLARIFICATION

In order to clarify what I have implemented I make this list:

Features implemented:

Bouncing capabilities (the ball bounces on walls, on bricks, and on the bar).
Sounds when bouncing on bricks and the bar, and when the player wins or loses.
Basic title menu (new game and exit only). Also in-game menu and win/lose menus.
Only three levels, but the map system is so easy I do not think it will teach me much (am I wrong?).

Features not-implemented:

Power-ups when breaking the bricks.
Complex bricks (with more than one "hit point" and invincible).
Better graphics (I am not really good at it).
Programming polishing (use more intensively the design patterns).

Here's a link to its (minimal) webpage: http://blog.acamara.es/piperine/
I kind of feel ashamed to show it, so please do not hit me too hard :-)

My question was related to the not-implemented features. I wondered what was the fastest (optimal) path to learn. 1) implement the not-implemented features in this project which is getting big, or 2) make a new game which probably will teach me those lessons and new ones.

ANSWER

I choose @ashes999 answer because, in my case, I think I should polish more and try to "ship" the game. I think all the other answers are also important to bear in mind, so if you came here having the same question, before taking a rush decision read all the discussion.

Thank you all!


texts: In 2D, how do I efficiently find the nearest object to a point?

texts:
I have a sizable game engine and I'd like a feature for finding the nearest of a list of points.

I could simply use the Pythagorean theorem to find each distance and choose the minimum one, but that requires iterating through all of them.

I also have a collision system, where essentially I turn objects into smaller objects on a smaller grid (kind of like a minimap) and only if objects exist in the same gridspace do I check for collisions. I could do that, only make the grid spacing larger to check for closeness. (Rather than checking every single object.) However, that would take additional setup in my base class and clutter up the already cluttered object. Is it worth it?

Is there something efficient and accurate I could use to detect which object is closest, based on a list of points and sizes?


texts:
I've implemented an omni-directional shadow map and I've noticed a rather unwanted behaviour on the shadows. It seems like when the angle between the occluded points and the light source is really steap, then the egde of the shadow starts to wobble. It's almost looks like it's pulsating.

Could it have something to do with when the light source moves further away from the occluded polygons, the pixels next to each other are further away from each other than the corresponding texels on the shadow map face that I sample from which result in some sort of magnification side-effect when performing aliasing? This is just a really wild guess!

Is anyone familiar with this type of behaviour and/or have any solution to it?

Thank you!


texts: Do you have any Linux-specific game development resources?


texts: In Cricket games, how is the ball synced with batsman's shot animation? How does the ball hit right at the center of the bat? How does this work?

texts:
I've been trying to figure this out for quite some time now.

In Cricket games, when the bowler bowls, and batsman takes a shot, how does the ball sync with batsman's shot animation?
For example, let's say the batsman hits a straight drive, how does the ball hit the bat perfectly?

Can anyone help me out with this?

I'm also curious  about how in football games, the player animations sync with the football. How does the player's foot correctly hit the ball?

Thanks in advance.


texts: Does it require any license to use a real city landscape in a car racing game?

texts:
I'm now planning a casual car racing game that want to model some real cities sight into it. I doubt if there is copyright of the landscape or city planning of those real cities in the world. Can I model such as existing city or I can't?

Thanks a lot.


texts: Are GPU drivers hand optimized for specific games using low-level APIs?

texts:
The GPU drivers often have slightly different behavior depending on game or program, which is using them. It optimizes performance, bypasses bugs and improves overall experience in popular games, especially demanding AAA ones. There was even a question on this stack about it a few years ago.

This strategy seems reasonable in the world of high level GPU APIs, like Direct3D up to 11 and OpenGL. These standards are very complicated, drivers don't comply with them perfectly and much of computation burden is pushed to the driver.

But what about the new, low level APIs like Direct3D 12, Vulkan and Metal? The standards are simpler for drivers to implement correctly and less computations are hidden inside the driver, they are in the hands of game authors. There seems to be just much less to do on driver side about improving game experience.

Are GPU drivers hand optimized for specific applications using low level APIs?


texts:
Talking BasicEffects,
where is the source of the three directional lights?

When I write this:

effect.DirectionalLight0.DiffuseColor = new Vector3(0.5f, 0, 0); // a red light
effect.DirectionalLight0.Direction = new Vector3(1, 0, 0);

What does it mean for the direction? From where is it directing?


texts: Any reason 3D character models aren't split into multiple models / files?

texts: I'm just curious if there as any reason why artists are so resistant to split their 3D models into multiple fbx files. I just find the code design much cleaner if 3D models are split up into multiple files, rather than having to dig through bone hierarchies to choose different parts of a model the code needs to control. Something similar is the 2D project layout with characters broken into different sprites, and being able to grab those by name. (I get that the artist can name bones to make the search nicer, but a search still needs to be done instead of giving a path) So, I get that it has to do with animating movement, but why can't that be split into multiple files? (For a maya workflow at least)


texts: OpenGLES GLSL Shader attributes always bound to 0

texts:
So I have a very simple vertex shader as follows
#version 120
attribute vec3 position;
attribute vec3 inColor;
uniform mat4 mvp;
varying vec3 fragColor;

void main(void){
    fragColor = inColor;
    gl_Position = mvp * vec4(position, 1.0);
}

Which I load, as well as the fragment shader:
#version 120
varying vec3 fragColor;

void main(void) {
    gl_FragColor = vec4(fragColor,1.0);
}

Which I then load, compile, and link to my shader program. I check for link status using
glGetProgramiv(shaderProgram, GL_LINK_STATUS, &shaderSuccess);

which returns GL_TRUE so I think its ok. However, when I query the active attributes and uniforms using
#ifdef DEBUG
        int totalAttributes = -1;
        glGetProgramiv(shaderProgram, GL_ACTIVE_ATTRIBUTES, &totalAttributes);
        for(int i=0; i<totalAttributes; ++i)  {
            int name_len=-1, num=-1;
            GLenum type = GL_ZERO;
            char name[100];
            glGetActiveAttrib(shaderProgram, GLuint(i), sizeof(name)-1,
                               &name_len, &num, &type, name );
            name[name_len] = 0;
            GLuint location = glGetAttribLocation(shaderProgram, name);
            fprintf(stderr, "Attribute %s is bound at %d\n", name, location);
        }
        int totalUniforms = -1;
        glGetProgramiv(shaderProgram, GL_ACTIVE_UNIFORMS, &totalUniforms);
        for(int i=0; i<totalUniforms; ++i)  {
            int name_len=-1, num=-1;
            GLenum type = GL_ZERO;
            char name[100];
            glGetActiveUniform(shaderProgram, GLuint(i), sizeof(name)-1,
                              &name_len, &num, &type, name );
            name[name_len] = 0;
            GLuint location = glGetUniformLocation(shaderProgram, name);
            fprintf(stderr, "Uniform %s is bound at %d\n", name, location);
        }
#endif

I get:

Attribute inColor is bound at 0
Attribute position is bound at 1
Uniform mvp is bound at 0

Which leads to failure when trying to use the shader to render the objects. I have tried switching the order of declaration of position & inColor, but still, only position is bound with the other two giving 0
Can someone please explain why this is happening? Thanks


texts: Calculating Experience Points earned after a battle

texts:
I'm developing a simple text battle game and having some issues calculating how much XP should be earned after a battle, theres a few factors that i want to consider:

1) Players should of course earn good XP if they beat someone of the same level

2) Players should earn great XP if they beat someone of a higher level

3) Players should earn poor XP if they defeat someone of a lower level

4) The above should scale nicely, i.e. if player A is level 10 and battles Player B who's level 9 or 11 the difference shouldn't be huge (they would of course gain more XP for defeating the level 11 character but we wouldn't expect this to be huge), but if he was to battle a level 5 or 15 this difference should be huge.

Just having trouble calculating something that works well in all scenarios, currently my XP table looks like the below:

Current Level   XP Needed   Increase from Last Level
1   30  0
2   65  35
3   106 41
4   154 48
5   210 56
...
10  672 123

In PHP my code looks like the below to calculate the XP Needed:

$offset = 30;
$multiplier = 1.17;
$base = $prevXp * $multiplier;

$xp = $base + $offset;

I've tried a few different things but i haven't been impressed with any of them, I'd like to work with calculating the difference in XP and then using some kind of multiplier but i haven't been impressed with the results.

Any help / input would be appreciated.


texts: How to decide how much to charge for development?

texts:
So two other friends and I are a very small game dev studio. So far we haven't released a game but we have 2 games almost ready to launch. A bigger studio saw our work and now they want to work with us; they need people to develop mobile games for them (iOS, Android).

They want us to set the price for the projects (can't tell the specifics we signed a NDA). They will give us all the assets (graphics/sound) so we only have to code. And because they only work with Unity3D we have to learn it.

How do we decide how much to charge for the projects?