texts: Deleting an item in the game world: detecting if an item supports other items

texts:
I'm writing a 3D construction module similar to the how you build houses in the Sims. Users are able to build walls and floors (which also act as ceilings) on multiple floors (layers). This question needs a little background info:

I'm not using an physics, there is no gravity. I use the term floor/ceiling tile here interchangeably. Essentially all are floor tiles, ceiling tiles are just floor tiles on a higher layer.

I store the build data in a multi dimensional array like:

grid[layer][row][column][position]

The layer represents the layer (ground floor, 1st floor etc..). The row and columns make up the grid. The position can hold any number of 3 positional values, namely:

0 : wall on west side of cell
1 : wall on south side of cell
2 : ceiling

So for example, a south wall on the row/column 2/4 on layer 3 would looks like:

grid[3][2][4][0=>null,1=>item,2=>null]

This works great, and it's easy to write functionality to check if a item can be placed at any position (by looking at neighbouring cells, layers below etc...)

Here is the actual problem and question:

I'm writing functionality to delete items within the game world. The rules by which I decide if something can be deleted are what you would expect in real life:

Any item that's not on the ground floor needs something else supporting it

So for the following examples:

Only 1 of the 2 blue tiles adjacent to the red tile could be deleted

The red tile cannot be deleted because the wall connected to it would no longer have a support.

Walls are simple enough, I just check nothing is in the same row/col above them (since it would only be another wall or ceiling). It's the floor/ceiling tiles that are difficult.

It's easy enough to check if an item has neighbouring items, or if is supported by a wall below, but I can't seem to find an efficient way to do the checks if, for example, a ceiling tile has many neighbouring tiles that it supports:

VS those same neighbouring tiles, but they are supported by another item:

I thought maybe I should be storing the information about which other items support the current item during placement, but that just feels like moving the same complexity to another part of the code.

Is there and algorithm or concept that I could use/adapt to do the checks?


texts: How to avoid 2d enemy using trigonometry?

texts:
I'm making a game in Javascript & HTML5.

I have a "bullet" (let's call it so) that needs to reach the enemy (at fixed position) and that need to avoid the enemy's "bullet".

To make the bullet move to the enemy i'm using this code:

var direction = Math.atan2(self.enemy.y - self.y, self.enemy.x - self.x);
var dir_diff = self.rotation - direction;
// ... other code
self.rotation -= dir_diff;
self.x += Math.cos(self.rotation) * self.speed / dt;
self.y += Math.sin(self.rotation) * self.speed / dt;

How can I make the bullet avoid another moving bullet?

I tried to search but algorithms like A* etc. doesn't seem right for this.

Thank you.


texts: Getting a TOISolver ArrayIndexOutOfBoundsException creating a tile based game

texts:
I've been making a tile-based game on java using jBox2D.For adding tiles to physical world I use static bodies which are stored in updating ArrayList(i use PhysicBlock class as a wrapper). Whenever I call body.setTransform(...) only half of the blocks is being added(there is always a 1-block-gap between them).When I try to insert a block between or under any of them  I get the following when a dynamic body collides with any of them:

Exception in thread "Thread-2" java.lang.ArrayIndexOutOfBoundsException: 8
at org.jbox2d.dynamics.contacts.TOISolver.initialize(TOISolver.java:99)
at org.jbox2d.dynamics.World.solveTOI(World.java:1235)
at org.jbox2d.dynamics.World.solveTOI(World.java:1053)
at org.jbox2d.dynamics.World.step(World.java:565)
at org.projectez.world.World.updateActiveBlocks(World.java:40)
at org.projectez.world.World.update(World.java:94)
at org.projectez.core.UpdateThread.update(Core.java:117)
at org.projectez.core.UpdateThread.run(Core.java:87)
at java.lang.Thread.run(Unknown Source)

Fragment of the World class(not jbox2d world,this class represents all blocks and GameObjects in game, it has jbox2d world as a field:

...
public ArrayList<PhysicBlock> activeBlocks=new ArrayList<PhysicBlock>();
public World(int x,int y)
{
    worldX=x;worldY=y;
}
public void updateActiveBlocks()
{
    physWorld.step(1/100f,2, 2);
    for(PhysicBlock pb : activeBlocks)
    {
        pb.nullify();
    }
    int counter = 0;
    for(int i=0;i<=100;i++)
    {
        activeBlocks.get(counter).redefine(i, 10, BlockRegistry.blockStone);
        counter++;
    }
    for(int i=1;i<=100;i++)
    {
        activeBlocks.get(counter).redefine(i, 11, BlockRegistry.blockStone);
        counter++;
    }
    ...

PhysicBlock class:public class PhysicBlock
{
    public BodyDef boxDef;
    public Body box;
    public FixtureDef boxFixture;
    public int i;
    public int j;
    public PhysicBlock(int i,int j,org.jbox2d.dynamics.World physWorld, Block block)
    {
        boxDef=new BodyDef();
        boxDef.position.set(i/2+0.25f,-j/2-0.25f);
        boxDef.type = BodyType.STATIC;
        PolygonShape boxShape = new PolygonShape();
        boxShape.setAsBox(0.25f, 0.25f);
        box = physWorld.createBody(boxDef);
        boxFixture = new FixtureDef();
        boxFixture.density = 1;
        boxFixture.shape = boxShape;
        boxFixture.restitution = 0f;
        box.createFixture(boxFixture);
        box.setFixedRotation(true);
        if(block==null) box.setActive(false);
    }
    public void redefine(int i,int j,Block block)
    {
        this.i=i;
        this.j=j;
        box.setTransform(new Vec2(i/2+0.25f,-j/2-.25f),0f);
        if(block==null) box.setActive(false);
        else box.setActive(true);
    }
    public void nullify()
    {
        box.setActive(false);
    }
}


texts:
I'm learning OpenGL and I understand that OpenGL performs clipping as part of the pipeline, but is it a good idea to also perform manual clipping? By manual clipping, I mean not asking the GPU to draw an object if I'm certain it won't be visible on the screen.

The advantage I can think of is that the GPU will not be wasting time on executing the vertex shader only to find out the primitives are to be discarded. On the other hand, performing calculations on the CPU may cause the overall performance to decrease. I believe the world terrain model is loaded once and so it isn't a good idea to perform manual clipping for the terrain and reloading selective parts on the GPU's memory, but maybe doing this for things like trees boost performance.

Thank you!


texts:
First of all, I am aware that there's no camera in OpenGL (ES 2), but from my understanding proper manipulation of the projection matrix can simulate the concept of a camera.

What I'm trying to do is make my camera follow my character. My game is 2D, btw. I think the principle is the following (take Super Mario Bros or Doodle Jump as reference - actually I'm trying to replicate the mechanics of the latter): when the caracter goes beyond the center of the screen (in the positive axis/direction), update the camera to be centred on the character. Else keep the camera still. I did accomplish that, however the camera movement is noticeably jittery and I ran out of ideas how to make it smoother.

First of all, my game loop (following this article):

private int TICKS_PER_SECOND = 30;
private int SKIP_TICKS = 1000 / TICKS_PER_SECOND;
private int MAX_FRAMESKIP = 5;

@Override
public void run() {
    loops = 0;

    if(firstLoop) {
        nextGameTick = SystemClock.elapsedRealtime();
        firstLoop = false;
    }

    while(SystemClock.elapsedRealtime() > nextGameTick && loops < MAX_FRAMESKIP) {
        step();
        nextGameTick += SKIP_TICKS;
        loops++;
    }

    interpolation = ( SystemClock.elapsedRealtime() + SKIP_TICKS - nextGameTick ) / (float)SKIP_TICKS;

    draw();
}

And the following code deals with moving the camera. I was unsure whether to place it in step() or draw(), but it doesn't make a difference to my problem at the moment, as I tried both and neither seemed to fix it. center just represents the y coordinate of the centre of the screen at any time. Initially it is 0. The camera object is my own custom "camera" which basically is a class that just manipulates the view and projection matrices.

if(character.getVerticalSpeed() >= 0) { //only update camera if going up
        float[] projectionMatrix = camera.getProjectionMatrix();

        if( character.getY() > center) {

            center += character.getVerticalSpeed();

            cameraBottom = center + camera.getBottom();
            cameraTop = center + camera.getTop();

            Matrix.orthoM(projectionMatrix, 0, camera.getLeft(), camera.getRight(), center + camera.getBottom(), center + camera.getTop(), camera.getNear(), camera.getFar());
        }
    }

Any thought about what I should try or what I am doing wrong?

Update 1: I think I updated every value you can see on screen to check whether the jittery movement is affected by that, but nothing changed, so something must be fundamentally flawed with my approach/calculations.


texts: How to coordinate sprites, player's position and collisions in a Bomberman-like 2D game?

texts:
I'm programming a Bomberman in Java (my first game) and I'm having problems with the player's sprites and position in the map. I'm using a 2D integer array to represent:

Unbreakable blocks
Explodable brick walls
Free spaces
Player itself (not sure if this is correct)

By now I could correctly place every background tile (40*40 each) iterating the array. Bomberman's sprites are MAX 40*40 (sometimes a little smaller). My question is, how can I correctly handle the collisions with walls? I already tried to do it, but that solution was very horribly buggy.

Thanks in advance.


texts:
So, I'm using the legacy particle "small flames". Basically what I want it to do is always emit below the ship, so when the ship turns and such it still looks like the thrusters are firing.

I know adjusting the World Velocity Y can adjust what direction the particles throw, but what I'm wondering is how do I always get what direction the back of the ship is facing, so I know what direction to emit the particles in? It doesn't have to use World Velocity, it could use rotation or some such, I just can't figure this out.


texts: How to compile custom module for iOS in Godot3.1

texts:
I'm trying to add Share module in my game for iOS platform. i have this repo for sharing module Godot-Share.

I'm using godot 3.1 and i download latest godot source code from Link.

To implement share module i follow this step to compile custom module.

Copy share folder to godot/modules folder.
Then i compile for iOS using this Link. I used following command to compile.

scons p=iphone tools=no target=debug arch=arm

scons p=iphone tools=no target=debug arch=arm64

In godot/bin i get as result two files :

  libgodot.iphone.debug.arm.a

  libgodot.iphone.debug.arm64.a

After i used following command to generate *.debug.fat.a file.

lipo -create bin/libgodot.iphone.debug.arm64.a bin/libgodot.iphone.debug.arm.a -output bin/libgodot.iphone.debug.fat.a

as result i get libgodot.iphone.debug.fat.a file in godot/bin folder.

i replaced libgodot.iphone.debug.fat.a file into godot/misc/dist/ios_xcode folder
i copied ios_xcode folder in documents, rename ios_xcode to iphone, then zip it. i get result file iphone.zip in Document folder.
Then i add iphone.zip file to Project>Export>Options>Custom Package>Debug

Then Export project.

Error I'm Facing :

Undefined symbols for architecture armv7:
"_z_verbose", referenced from:
_inflateInit2_ in FBLogin.a(ftgzip.iphone.debug.arm.o)
_inflate in FBLogin.a(ftgzip.iphone.debug.arm.o)
_inflateEnd in FBLogin.a(ftgzip.iphone.debug.arm.o)
_inflateReset in FBLogin.a(ftgzip.iphone.debug.arm.o)
_inflate_blocks_reset in FBLogin.a(ftgzip.iphone.debug.arm.o)
_inflate_codes_free in FBLogin.a(ftgzip.iphone.debug.arm.o)
_inflate_blocks_new in FBLogin.a(ftgzip.iphone.debug.arm.o)
...
"_z_error", referenced from:
_inflate_codes in FBLogin.a(ftgzip.iphone.debug.arm.o)
ld: symbol(s) not found for architecture armv7
clang: error: linker command failed with exit code 1 (use -v to see invocation)

So my question is : Am i compiling and linking custom module for iOS is right?

How do i solve above issue?


texts: How to change the color of an image when getting points

texts:
Currently I have a car game which I give points when a car touches the monster.Now extra to that I also wanted to change the color of the car or replace the car image with a different color car image when it is touching the monster.

So where I give point is

monsters.array.forEach(monster => {
            if(monster.isTouching(this)){
                monster.reset();
                monstersCaught += 1;
            }
        });

So now when I give point I also want to change the color of the car.
Any help is appreciated.My pen for the game :pen


texts: Simple scene graph in 2D, without matrices?

texts:
First of all, I think I roughly know how a scene graph works. Please correct me if I'm wrong.

It is a tree based structure, with each branch/leaf being a node. It means you can better organise children, like tyres on a car or something. I want to use a simple version of it, which makes me think matrices, but the graphics API I'm using (SFML) doesn't allow them. I would use GL here, but the project has to be done in a reasonable time frame.

Instead, I only have the ability to set 'absolute' window coords by default. Without anything, it would be something like:

carBody.position(10,10);
carWheel1.position(9.5f, 8.7f);//etc. I think that's a badly placed wheel. :P

How could I go about this? Have each object/renderable thing/entity be a node, obviously, but then how would I handle position changes? I would think passing down the branch, somehow.

Is there some kind of tree structure in the STL containers? Would I have to make my own?

There's one other thing that's hit me. Is all of this overkill? All I really need is some way to control more of 'local' positioning, which this does, but this seems OTT for what I need. So it's sort of organization + positioning vs the sheer complexity for a 2D side scroller.


texts: Simulate parallel dimensions / subspaces in Unity without colliding coordinate systems

texts:
I've built an online game with Unity with a very large open world.  The server (which can be a local player, or run as a standalone application without a local player) simulates everything around players - so for example if there is an object or NPC at coordinates (100,34,20) but there aren't any players nearby then the object is not simulated.  Objects are streamed dynamically from a database or generated procedurally depending on the object.

Problem

I want to enable players to go to other worlds.  Of course it is impractical if not impossible to have global coordinates shared across all of these different worlds due to floating point limitations. I'll have to share the limited coordinate system for each simulated world.

The issue is the server would still need to render and handle physics of multiple worlds but could now potentially have conflicts with objects and/or people on one world appearing in other worlds.  Essentially I need a way to divide up these "worlds" into parallel dimensions that are executed simultaneously on the same server (in one Unity scene).

Parallel Dimensions

A partial solution would be to have some sort of indicator, such as an integer (I'll call it "worldIndex") on each object to indicate which "world" that object exists in.  This would work for clients since the server would be able to tell the clients only about objects that are on their world.

There would still be a problem on the server itself.  Every world needs to be simulated in the same coordinate space.  For a local player I could use the "worldIndex" to hide objects that aren't in the local player's current "world".  But I still need to simulate physics for every world.

Unity's Layers could be used to mask physics interactions between objects.  However I would then need to have at least one layer per world - and I already use multiple layers for various different interactions.

My thoughts are I would need something like a layer I could specify on each GameObject or some way to group a bunch of GameObjects together and instruct the physics system to only allow interactions within the group.  But as far as I know no such mechanism exists within Unity.

Subspace Pockets

Another thought I've had is rather than using the Unity coordinate space directly, I could slice it up into "subspaces" or pockets.  Each player would be in their own subspace, unless a player physically enters the same space that is already being simulated by another player, in which case that player would join the same subspace.  But then I would have shift around the coordinate systems and it would increase complexity of merging players into and out of these subspaces.  I would also have to generate subspaces dynamically as players enter new areas that are not currently being simulated.

Even if each world is extremely large, it is not necessary to use the entire Unity coordinate system around each player - a few thousand kilometers is more than enough.

Overall I think something along these lines is probably the best solution.

Multiple Servers

I could run one server per "world" and have a hand off process to make it transparent to players.  But then I'd have to run multiple server instances and players would not be able to host their own server - at least not without a lot of additional overhead.

Question

So my question is: what is the best method for essentially running multiple, parallel simulations within a single Unity scene?


texts:
private void OnEnable()
{
    Debug.Log(EventSystem.current);
    EventSystem.current.SetSelectedGameObject(gameObject);
}

Very simple script for selecting a UI element on enable. However, EventSystem.current prints null to the console.
Unity 2019.3.15f1
I have an Rewired event system in the scene.
Also tried putting this in an IEnumerator and waiting a frame before logging to the console - no change.


texts: How to access raw texture data in DirectX 11?

texts:
I want to get access to a texture's pixel color data on the CPU. When trying to map the texture, I get E_INVALIDARG in return from ID3D11DeviceContext::Map.

ID3D11ShaderResourceView* resourceView; //represents my texture, already loaded up
//...

//Getting the resources of the texture view...
ID3D11Resource* res = nullptr;
ID3D11Texture2D* tex = nullptr;
resourceView->GetResource(&res);
res->QueryInterface(&tex);
D3D11_TEXTURE2D_DESC desc;
tex->GetDesc(&desc); //Correct data gets filled out
D3D11_RESOURCE_DIMENSION dim;
res->GetType(&dim); //value gets set as Texture2D which it should

D3D11_MAPPED_SUBRESOURCE mappedResource;
HRESULT h;
h = context->Map(tex,0,D3D11_MAP_READ,0,&mappedResource); //This always fails
h = context->Map(res,0,D3D11_MAP_READ,0,&mappedResource); //This also fails

The idea is that I keep only shaderResourceViews for my textures, because that is all I needed until now, and get the relevant resources here.

I tried mapping as WRITE_DISCARD also, but to no success. I am really confused, because I never had any problem with mapping constant buffers and vertex buffers. I seem to be certainly missing something?
By the way, I am using Wic Texture loader and DDS Texture loader for the DirectXTex toolkit, and tried this code for png, dds textures, with and without mip-maps.


texts:
I'm working on a game right now and running into some noticeable performance issues and limitations.

Basically, I have this:

A few QGLWidgets, all sharing contexts with eachother (probably irrelevant that I'm using Qt [also: Windows, fwiw]).
About 216000 total frames of 128x128 videos (with alpha, internal format GL_RGBA, data format GL_BGRA/GL_UNSIGNED_INT_8_8_8_8_REV, video codec is Quicktime RLE, decoded with libav), spread into approximately 120 videos of 1800 frame average length. This translates to roughly 216000*128*128*4 = 14.2 GB of raw data, not including overhead.

The game behaves as follows:

There are many "modes". At any given time only one mode is active. Each mode uses a very small known subset of the available videos, say 5-10 videos (= about 9000 - 18000 frames) tops.
There's a bunch of 2D quads flying around the screen, each displaying whatever videos depending on the current mode. Objects don't all display the same frame, the video time offsets are random. The videos loop.
Every few minutes, the mode changes. Objects cross-fade to their new videos, so there is some overlap regarding when various sets of videos are needed.
It is critical that this thing keep running smoothly, at 60 FPS, with no pauses for loading, etc.

My problem is this:

My initial approach was to simply preload all videos off the disk and into textures, in video memory (via glTexImage2D and friends). I didn't mind the slow startup. This worked great early on, when I didn't have a lot of videos. The game could run smoothly because all the textures were already loaded.

Now I have too many videos. I'm becoming extremely limited by available video memory, and the preload-everything strategy is no longer working. I haven't become limited by system memory yet but that's also inevitable. I suspected this was going to be an issue and kept my fingers crossed, but alas. I hit the limit way sooner than I expected.

I tried switching to a strategy where, every time a mode transition started I pre-loaded the videos for that mode (and every time a transition ended I unloaded the videos for the previous mode). This works as far as memory goes but it pauses everything for a very long time while loading (as in 3-8 seconds depending on the number of videos and the graphics hardware).

I've done the best searching that I know how to do, all of the texture memory management posts, blogs, tutorials etc. just talk about the basic technique of creating and destroying textures, rather than strategies for managing large numbers of them in an application. I went through every question in the auto-search on here that had a relevant-looking title. I did find out that OpenGL is definitely not thread-safe, which kind of kills my asynchronous background loading idea, unless there's some other way to implement that.

So my question is: What's a good strategy to use for swapping out tons of textures (200000+, 128x128 typical size) when at any given time only a small portion of those are needed, while maintaining a smooth frame rate? How is this typically done?


texts: Do I need to update my DirectX SDK in order to fix a crash with D3D10_CREATE_DEVICE_DEBUG?

texts:
I am currently using the DirectX June 2010 SDK. Everything was working fine with my installation until recently. Unfortunately I'm not sure what changed or when, but now when I create a device with D3D10CreateDevice1(), it always crashes with a memory error if the device is created with the D3D10_CREATE_DEVICE_DEBUG flag. Even reverting to old code which used to work causes this error.
Additionally, PIX always crashes every time I use it with my game.
I did some searching and found a lead that I may need to update my SDK installation. This page also indicates that I need to "install the updated SDK Debug Layers".
How do I do this? I have no idea how to install the "Debug Layers"...
Additionally, is it a mistake for me to be using the June 2010 SDK? Apparently DirectX is now included with the Windows 8 SDK, which I haven't been using because I've no interest in Windows 8 development. Is this foolish? Is there any downside to me using the Windows 8 SDK just for Windows 7 DirectX development using Visual Studio 2010?


texts: Godot: What options are there for removing the filtering or anti-aliasing from text

texts:
If I were to start making a pixel-art game with the Godot engine, what options do I have for removing the filtering or anti-aliasing from text?

EDIT:

I want to know how to remove the AA from rendered text in a label node.


texts: Why does collision only work when keys are being pressed?

texts:
My player object containing a rigidbody that is controlled using Input, is not colliding with an enemy unless keys are pressed. When no keys are pressed, the enemy simply goes through the player without collision. I'm using Unity 5.6.1f1.

I figured the problem is in the Patrol class because when I don't attach the script to the enemy object the collision appears to take place fine.
But I don't know what I'm doing wrong in this script because I seems to do it's task well. I wrote this script to make the enemy object move between points in patrolPoints which are just some empty's in the game world.

So, I would like to know if I'm doing it right or is there another way to do it.

Patrol.cs

public class Patrol : MonoBehaviour {
    public Transform[] patrolPoints;
    public float speed;
    private int currentPoint;
    private bool forward;

    // Use this for initialization
    void Start () {
        transform.position = patrolPoints [0].position;
        currentPoint = 0;
        forward = true;
    }

    // Update is called once per frame
    void Update () {
        if (transform.position == patrolPoints [currentPoint].position) {
            if (currentPoint < patrolPoints.Length - 1 && forward) {
                currentPoint++;
            } else {
                currentPoint--;
                forward = false;
            }

            if (currentPoint == 0)
                forward = true;
        }

        transform.position = Vector3.MoveTowards (transform.position,
            patrolPoints [currentPoint].position, speed * Time.deltaTime);
    }
}


texts: Do two balls of different mass bounce different heights?

texts:
There are two balls and the only difference between them is the mass. Both are dropped from the same height on to the floor (static object with infinite mass), would both balls bounce up to the same height, or would the heavier ball bounce higher as it enters the collision with more momentum?

From my own derivation it would appear that the calculation reduces down to a simple vector reflection about the contact normal, but it doesn't feel right. Can anyone verify this?

EDIT:

To be clearer, I am looking for a code sample of how to resolve a ball collision against a plane using a collision impulse. Does the collision impulse rely on the ball's mass when colliding with an object of infinite mass?


texts: How do I have multiple audio sources on a single object in Unity?

texts:
I have an audio system set up wherein I have loaded all my audio clips centrally and play them on demand by passing the requesting audioSource into the sound manager.

However, there is a complication wherein if I want to overlay multiple looping sounds, I need to have multiple audio sources on an object, which is fine , so I created two in my script instantiated them and played my clips on them and then the world went crazy.

For some reason, when I create two audio Sources in an object only the latest one is ever used, even if I explicitly keep objects separated, playing a clip on one or the other plays the clip on the last one that was created, furthermore, either this last one is not created in the right place or somehow messes with the rolloff rules because I can hear it all across my level, havign just one source works fine, but putting a second one on it causes shit to go batshit insane.

Does anyone know the reason / solution for this ?

Some pseudocode :

guardSoundsSource = (AudioSource)gameObject.AddComponent("AudioSource");
guardSoundsSource.name = "Guard_Sounds_source";
// Setup this source

guardThrusterSource = (AudioSource)gameObject.AddComponent("AudioSource");
guardThrusterSource.name = "Guard_Thruster_Source";
// setup this source
   // play using custom Sound manager
soundMan.soundMgr.playOnSource(guardSoundsSource,"Guard_Idle_loop"
,true,GameManager.Manager.PlayerType);
   // this method prints out the name of the source the sound was to be played on and it always shows "Guard_Thruster_Source" even on the "Guard_Idle_loop" even though I clearly told it to use "Guard_Sounds_source"


texts: Why do I get an 'invalid call' error when creating an R8G8B8 volume texture?

texts:
I'm trying to create a VolumeTexture in C# with SharpDX, but it fails:

var form = new RenderForm("SharpDX - Test");
var device = new Device(new Direct3D(), 0, DeviceType.Hardware, form.Handle, CreateFlags.HardwareVertexProcessing, new PresentParameters(form.ClientSize.Width, form.ClientSize.Height));

VolumeTexture texture = new VolumeTexture(device, 4, 4, 4, 1, Usage.None, Format.R8G8B8, Pool.Managed);

The error is:

HRESULT: [0x8876086C], Module: [SharpDX.Direct3D9], ApiCode: [D3DERR_INVALIDCALL/InvalidCall], Message: Unknown

I searched but found no sample for volume textures in .NET; why am I getting this error and how can I fix it?


texts:
I'm using pygame.rect.colliderect() to check hitbox collision between sprites in my game, but now that I'm rotating the sprites, I'm realizing I can't do this because there's no way to rotate a PyGame rect, so the hitboxes are way off now.

How should I handle collision in a game with rotating sprites if I don't want to use masks or pixel perfect collision? Is there a way to make a hitbox that rotates with the sprite?


texts: Should there be a limit to how many in game models there is for a 3d MMORPG?

texts:
I was considering building a character creator/customizer program that would enable a player to create their own 3d model based off of a series of preset body parts. i.e. A player could choose to add the legs of a horse, the body of a man, wings of a falcon and the head of a snake. From there the player can then customize each body part by tweaking sliders responsible for length, thickness, color, position, etc.

Ultimately this will give players the ability to customize their characters with infinite degrees of freedom (not like preset customizations we see in some MMORPGs i.e. 8 hair cuts, 10 faces, 8 body types, etc.). So as you can imagine this would most likely lead to ever player having a different character.

Would having thousands upon thousands of separate 3d character models some how slow the game down?

I consider that it would not because the most characters that would be rendered in the game I am working on would be 25 to 50 if that.


texts: Iterating through all animator layers in Unity Mecanim

texts:
I'm aware of how SetAnimatorLayerWeight works, I'm looking for a way to iterate through all layers of my controller at runtime.

I've four layers and expect more, and need to update them at once, in essence, what I'm trying to do is something like this.

To clarify: The code below is boilerplate of what I'm trying to do.

    void SetCurrentWeaponLayerWeight(int index)
    {
        _animator.SetLayerWeight(index, 1);

        foreach(AnimatorLayer l in Animator.Layers)
        {
            if (l.index != index)
                _animator.SetLayerWeight(l.index, 0);
        }
    }


texts:
I'm making a simple 2D game in libgdx, and now I'm at the point where I have to save data. I already have a mechanism to save the data itself.
The problem is that I don't know when/where the procedure to save the state should be executed. Should it be executed in dispose method? Or pause method?
Save the state every time the player dies doesn't seem very efficient to me.
Anyone can give me tips about this?
Thanks in advance.


texts: Recommended hardware for developing ios games?

texts:
I know you have to have mac os x to use xcode and thus to develop/compile apps for the iphone. And I'm not exactly wanting to go the hackintosh way, so I'm looking at buying a used mac.

What specs are recommended. If I buy a cheap mac mini that has only 1gb of ram would that be enough? (I'm not talking about using that to create the graphics/audio, I'll use my normal windows/ubuntu pc for that). I'm just talking about being able to use xcode and write applications.

I'm trying to spend the least amount I can without running into problems developing the app.


texts: What are the specifications for 3D animated game assets on the Android platform?

texts:
(apologies if this is phrased vaguely due to my lack of knowledge; I'm happy to change the question entirely if someone can suggest a more realistic query)

I'm getting a grip on creating 3D characters in Lightwave, Maya, Blender, etc. My goal is to focus on creating creature & character animations specifically for games. I thought it would be a good exercise to make a few critters with a specific scope. As a non-programmer (I've written a few scripts, but I really don't have a passion to code) - can you point me in the right direction to find some guidelines? (I have a programmer handy who will write the code, but I want to be able to give him assets that are as usable as possible)

I assume that Android games are intended to run on limited hardware - maybe there's a polycount I should shoot for, or a particular memory limit? The resources I've found so far all seem to be helpful to developers - haven't found much oriented in my direction


texts:
I'm using Assimp to do skeletal animation in my OpenGL application.

I used Blender to export this one-boned model to a COLLADA file:

The model has only one bone, called arm bone, that controls the arm mesh. All the other meshes are static.

I made several structures and classes that help me play animations.
All the nodes are added to an std::vector of Node objects. each Node contains aiNode data and a toRoot matrix.
The bone hierarchy is encapsulated in a Skeleton class, and the animation matrix (T * R) are updated for each bone in a class called Animation.

My Model::Draw() function is this:

void Model::draw()
{
    //iterate through all animation sets. if the animation is running, update the bones it affects.
    for(size_t i = 0; i < _animations.size(); i++)
        if(_animations[i].running())
            _animations[i].updateAnimationMatrices(&_skeleton);

    //calculate Bone::finalMatrix for each bone
    _skeleton.calculateFinalMatrices(_skeleton.rootBone());

    //iterate through the nodes and draw their meshes.
    for(size_t i = 0; i < _nodes.size(); i++)
    {
        _shaderProgram.setUniform("ModelMatrix", _nodes[i].toRoot());

        _nodes[i].draw();
    }
}

To get the "animationMatrix" for each bone (the TR matrix) I call Animation::updateAnimationMatrices().
Here's what it looks like:

void Animation::updateAnimationMatrices(Skeleton *_skeleton)
{
    double time = ((double)_timer.elapsed() / 1000.0);
    while(time >= _animation->mDuration) time -= _animation->mDuration;

    //iterate through aiNodeAnim (called channels) and update their corresponding Bone.
    for(unsigned int iChannel = 0; iChannel < _animation->mNumChannels; iChannel++)
    {
        aiNodeAnim *channel = _animation->mChannels[iChannel];
        Bone *bone = _skeleton->getBoneByName(channel->mNodeName.C_Str(), _skeleton->rootBone());

        //rotation
        glm::mat4 R = ... //calculate rotation matrix based on time

        //translation
        glm::mat4 T = ... //calculate translation matrix based on time

        //set animation matrix for the bone
        bone->animationMatrix = T * R;
        bone->needsUpdate = true;
    }
}

Now in order to calculate the "finalMatrix" for each bone (based on animationMatrix, offsetMatrix etc..), and upload it to the vertex shader, I call Skeleton::calculateFinalMatrices().

void Skeleton::calculateFinalMatrices(Bone *root)
{
    if(root)
    {
        Node *node = _getNodeByName(root->name->C_Str());
        if(node == nullptr) {
            std::cout << "could not find corresponding node for bone: " << root->name->C_Str() << "\n";
            return;
        }

        if(root->needsUpdate) //update only the bones that need to be updated (their animationMatrix has been changed)
        {
            root->finalMatrix = root->animationMatrix * root->offsetMatrix;

            //upload the bone matrix to the shader. the array is defined as "uniform mat4 Bones[64];"
            {
                std::string str = "Bones[";

                char buf[4] = {0};
                _itoa_s(root->index, buf, 10);

                str += buf;
                str += "]";

                _shaderProgram->setUniform(str.c_str(), root->finalMatrix);
            }

            root->needsUpdate = false;
        }

        for(unsigned int i = 0; i < root->numChildren; i++)
            calculateFinalMatrices(root->children[i]);
    }
}

Here's my bone structure, if it helps.

My glsl vertex shader is pretty standard. Here it is.

And finally, here's the result I get: (ignore the model's static legs. that must be some bug in the Blender exporter).

And here's the result I should get: (using a 3d party software)

It looks like there's something wrong with the bone's matrix calculation, although I don't know what. Any ideas or tips?

Thanks!


texts: Real time lighting in a 2D game with angled camera perspective

texts:
The game "Monaco: What is yours is mine", has a nice real time lighting/shading effect as shown in this picture:

Notice how the vision is blocked by obstacles. I would be interested in seeing if this effect could work in a game with angled camera view. There are about a million such games, for example see Stardew Valley:

It is not clear to me if these two graphics styles could be easily combined. I'm looking for examples - either full games or just technical demos, etc. of the Monaco-like lighting effect applied to angled camera perspective (like in Stardew Valley).


texts:
I have done a texture in GIMP and imported it in Unity but for some reason the texture appears to be squashed in the sides.

Image done in gimp:

And here is what happens in Unity:


texts:
I am new to unity scripting.

I am trying to move my character towards right side(on x-axis) to create a running effect, I've imported the character from blender which contains two animations, "jump" and "run". What I want to do is I want my character to move on x-axis for which I've written following code

void Update () {
    transform.Translate(5f * Time.deltaTime, 0f, 0f);
}

But I am facing one problem, if I set my character's y-axis rotation to 90 degrees in order to make him look towards right side I am getting strange results. That is, in play mode instead of moving towards right side(on x-axis) it move on x-axis and z-axis simultaneously & if I set the y-axis rotation to zero it behaves like I want it to. Please see the attached image for detail. How can I solve this problem?


texts:
In my game I use box2d objects and, as I understand it, you can move them only in two ways, SetLinearVelocity, and ApplyImpulse. I need to move the object 32 pixels in 1 turn. So I make a constant speed and the next problem appears. If the laptop is connected to the charge and gives 60 frames, the object begins to move faster. How do I make frameindependent movement? Without connection - 30 FPS and the game makes slowly.

I also know that if you want to be frameIndependent you need to use this formula:

x = x + speedPerSecond * secondsElapsedSinceLastFrame

But i cant use this formula, because i cant set box2d position. It is make box2d itself. I only can set the Velocity :( Or may me i just dont know.

2 - it is meters per second. 64 pixels.
private void handleInput(float delta) {

    if (Gdx.input.isKeyPressed(Input.Keys.W)) {

        b2body.setLinearVelocity(0, 2);
    }

    if (Gdx.input.isKeyPressed(Input.Keys.S)) {

        b2body.setLinearVelocity(0,-2);
    }

    if (Gdx.input.isKeyPressed(Input.Keys.A)) {
        b2body.setLinearVelocity(-2, 0);
    }

    if (Gdx.input.isKeyPressed(Input.Keys.D)) {
        b2body.setLinearVelocity(2, 0);
    }
}

How can i move object in another way or how to make movement frameindependent? SetTransform is not a good decision becasuse collisions are ignored. Thank You!


texts: How to load models with possibility to change textures in Three.js

texts:
I'm working on a game in Three.js where I have a few variations of the same model in blender.

What I want to achieve is that I'll load the model once with all the material settings, but then I'll just change the texture dynamically. Is there a way to do that? and in what format should I export it from blender in order to do this effeciently (json, obj)?

Thank you so much in advance.


texts: Efficient physics and collision detection for RTS

texts:
I'm thinking about writing my own RTS game and while I'm more or less clear about how the game engine should work, I need some directions as to how to implement physics and collision detection.

Now, I am an experienced programmer but I have never ever done game dev before, so please excuse me my poor/incorrect terminology.

There will be a large 3D (i.e. planes, hills, valley, etc) world with lots of units, moving and/or fighting simultaneously and lots of projectiles flying around. So the most important thing is, physics and collision computation must be very fast.

Could you please point me in the right direction?
Idea I'm elaborating on is some kind of 3D tiles, with every unit's position being x,y index of tile + elevation (e.g unit staning on the hill or on the fortress wall). the smallest unit will occupy for examle one tile horizonally and 5 vertically. With every tile having 3x3x1 aspect ratio (e.g. 15x15 horizontally and 5 pixels height).

How realistic is this? How would you approach this? Are there any 3d physics/collision engines which are fast enough for such application?

Hope for your help
Alex


texts: How to constrain a ball and chain like object?

texts:
Following up  on this question, I have created a snakelike enemy which consists of a head followed by segments. I get the segments to follow the head by constraining each segment's position relative to the segment in front of it. I get the difference between the actual distances between the segments and the desired distance, and correct that error 30% per frame.

The GDScript code looks like this:

for segment in [segment1, segment2, segment3, segment4, segment5, segment6]:
    # get actual distance between segment and its target
    var distance = segment.global_position.distance_to(segment.target.global_position)
    # find difference with desired distance
    var error = distance - desired_distance
    # move segment a percentage of the error toward its target segment
    var vector_to_target = (segment.target.global_position - segment.global_position).normalized()
    segment.global_position += vector_to_target * error * 0.30

I am happy with the result.

Now I want to create a similar enemy also composed of segments, but whose final segment is a kind of base, rooted to one position. Similar to the Chain Chomp from Mario.

I then want to code movement of the head, but for everything to be constrained. I'm guessing all intermediate segments would be doubly constrained by both of their neighbor segments, and the head itself would also have to be constrained by its neighbor segment, even though I'd be coding movement for it.

I'm not sure how to set up constraints like these which have to look in both directions, and would appreciate any advice?

Although I work in Godot, an engine-neutral explanation of the technique would suffice.


texts: Unity 2D, C# - Make object move diagonally by a certain angle?

texts:
I have a sprite object which I want to move in 8 directions. Left, Right, Up, Down, Left top, Right top, Left down, Right  down. The view is 2D with a isometric projection. The difficulties I am having is when the object needs to move diagonally. I need to work out how I can move the sprite in fixed degrees diagonally so its parallel to the isometric world.

I have a diagram to demonstrate.

Here the green arrows are the diagonal movement that I need. The code I have for up, down, left and right movement is already in,

void FixedUpdate ()
    {

            speed = 10f;
            //pos = Camera.main.ViewportToWorldPoint (new Vector3 (0.5F, 0.5F, Camera.main.nearClipPlane));
            //transform.position = new Vector3 (pos.x, pos.y, -1F);

            if (Input.GetKey (KeyCode.D)) {
                    ///rigidbody2D.AddForce (Vector2.right * speed);
                    rigidbody2D.velocity = Vector2.right * speed;

            } else if (Input.GetKey (KeyCode.A)) {
                    //rigidbody2D.AddForce (-Vector2.right* speed);
                    rigidbody2D.velocity = -Vector2.right * speed;
            } else if (Input.GetKey (KeyCode.S)) {
                    //rigidbody2D.AddForce (-Vector2.up * speed);
                    rigidbody2D.velocity = -Vector2.up * speed;
            } else if (Input.GetKey (KeyCode.W)) {
                    //rigidbody2D.AddForce (Vector2.up * speed);
                    rigidbody2D.velocity = Vector2.up * speed;
            } else {
                    rigidbody2D.velocity = Vector2.zero;
            }
    }

I had a look at the Transform class and the various variables and functions but I don't know what to use or start with. This is because I am very new to Unity and maths such as rotations, axis, etc. So a helping direction would be massively appreciated. Thanks.


texts: What Javascript game engines are out there, other than Impact?

texts: Does anybody know of a decent (meaning preferably free ;)) alternative to Impact? Any suggestions are very much appreciated!


texts: Pathfinding in non tile-based 2d map (maybe potential field)

texts:
I am developing a top-down 2d zombie shooter in AS3.
I have implemented collisions against segments (line from point a to point b), polygons (array of points, convex) and round obstacles (center and radius)
Player and enemies are basically moving round obstacles, with different radii.

Now, I'm having trouble with zombie AI's pathfinding.
I have read about potential fields, and I found it fascinating, but I can't figure out how to adapt it to a non tile-based map.
I can calculate the distance from a point to the closest obstacle, and get the obstacle repulsive potential in that point.
I don't know how to get the player's attracting potential in that point though. In tile-based maps you use the A* algorithm, considering every walkable tile as a node. This is my first problem.

Once I have calculated the player's attracting potential in a point, what I get is a Number. In tile-based maps, I would test this number against the potential of the 8 adjacent tiles, and move the enemy to the tile with the lowest potential. In my non-tile based map instead I do not have a fixed set of tiles to test, so I can't understand how to get the moviment vector to apply to the enemy. This is my second problem.

If I, say, set a waypoint every x*y pixels, I could use it as the centre of a tile, but that sounds very unelegant, mainly because enemies would be forced to move along the 8 directions of adjacent nodes.

Should I forget PFs and try a different approach?


texts:
I have tried to use my own lighting model in surface shader in Unity. But there is a problem.

If I init my own lighting via

#pragma surface surf _SimpleSpecular

Lighting_SimpleSpecular method is executed. But, even if I return single color from it, my model has still applied texture (with the tint of my returned color). What I am doing wrong? I am using forward rendering.

If I switch to Standard and return single color, all is at it should be.


texts: How to use Moving Average to avoid lucky streaks in RNG

texts:
I spent the last week reading about Luck Mitigation and what a dev can do to avoid extreme cases where the player's psychology will be messed up.

I came up to this question How do I avoid “too” lucky / unlucky streaks in random number generation?, plus some others outside GameDev site. To illustrate my question, let's have this simple game example.

We have a turned base fighting game, like BiteFight. Two characters have their attributes and the match outcome is based entirely to those attributes.

In specific:

Player 1: Str: 10 Def: 15 Agl: 20

Player 2: Str: 12 Def: 20 Agl: 15

The process is simple:

If rnd() * P1_Agl >= rnd() * P2_Agl:
    P1 will attack
else:
    P1 will attack

Then with the same way in case of Player 1 is attacking

If rnd() * P1_Str >= rnd()* P2_Def:
    reduce life points from P2

Repeat the same unlimited times until one of players' life reach zero.

Solutions I found:

Instead of 1 rnd() call, use x-times rnd() and get the average. Something like ( rnd() + rnd() + rnd() ) / 3. This will move the results closer to 0.5 and make the whole process less "random". However, it is still possible enough to have streaks of lucky or unlucky events.
Keep track of the results and if you have x-times the same result then hard-code the other. For example, if on the above, P1 won the Agility test 3 times in the row, then the 4th time will always go to P2. What I didn't like on this are the predictability. Users might understand that behavior through time. But the most important is what would happen if P1 uses an item that changes his attributes on the 4th step? When you hard-code the outcome, the result would be based on different attributes.
I read many times the suggestion to use a Moving Average or a Cumulative Moving Average on the rnd() to guess if their is a streak of lucky results. For example, if Player 1 keeps getting rnd() above 0.9, it is a lucky streak. I wrote a script to calculate those two and here is an example for CMA and MA

Cumulative Moving Average

0 : Random number:  0.348  CMA:  0.348
1 : Random number:  0.74  CMA:  0.544
2 : Random number:  0.967  CMA:  0.685
3 : Random number:  0.578  CMA:  0.659
4 : Random number:  0.932  CMA:  0.713
5 : Random number:  0.134  CMA:  0.617
6 : Random number:  0.397  CMA:  0.585
7 : Random number:  0.537  CMA:  0.579
8 : Random number:  0.861  CMA:  0.611
9 : Random number:  0.893  CMA:  0.639

Moving Average

0 : Random number:  0.295 Moving Average:  0.098
1 : Random number:  0.866 Moving Average:  0.354
2 : Random number:  0.768 Moving Average:  0.492
3 : Random number:  0.888 Moving Average:  0.624
4 : Random number:  0.94 Moving Average:  0.729
5 : Random number:  0.325 Moving Average:  0.595
6 : Random number:  0.823 Moving Average:  0.671
7 : Random number:  0.208 Moving Average:  0.517
8 : Random number:  0.743 Moving Average:  0.592
9 : Random number:  0.038 Moving Average:  0.407

So, I end up to my 2 questions

1) Even if I read many times the suggestion of Moving Average, no-one mentioned how exactly you use it. So, my guess is that each time, you compare the rnd() with the moving average and based on that you take some actions. But what exactly you can do?

2) In the above example, you can see that we have two comparisons. One for Agility and one for Strength. Should one use two different Moving Averages to "identify" lucky streaks for each case, or it should be one for every case that RNG comes to the game?


texts:
I have an object that can jump.

When it jumps, its Y velocity becomes -600 (pixels/second).

For up to .2 seconds, it can ignore gravity.

After .2 seconds, it begins to accelerate downward at 2100 (pixels/second).

Independently from its Y velocity, the object can move on the X axis up to 220 (pixels/second) or -220 (pixels/second).

How do I calculate whether or not, with a given starting x/y coordinates it can jump to a target x/y coordinate?

Also, how do I calculate the necessary X velocity to reach its target in the proper amount of time so that it doesn't overshoot or undershoot?


texts: When saving data locally for a mobile game, how to protect it?

texts:
I am designing a mobile (iOS/Android) game and I try to save data (such as levels, coins, status) in local files.

In this way, I am concerning a case that someone can just copy these files and give them to a friend, so the friend can have achieve certain levels and all the coins held in the data files right away.

Instead of saving the data in a server, is there any way to prevent this happen?

I am thinking to encrypt the data with a key that is unique for a device. Is this a good idea or it might cause some other problem?


texts: OpenGL Water reflection seems to follow camera yaw and pitch

texts:
I'm attempting to add reflective water to my procedural terrain. I've got it to a point which seems like it's reflecting however when I move the camera left/right/up/down the reflections move with it.

I believe the problem has something to do with the way I convert from world space to clip space for the projective texture mapping.

Here is a gif of what is happening.
http://i.imgur.com/PDta5Qu.gifv

Vertex  Shader

#version 400
in vec4 vPosition;
out vec4 clipSpace;
uniform mat4 model;
uniform mat4 view;
uniform mat4 projection;

void main ()
{
  clipSpace = projection * view * model * vec4(vPosition.x, 0.0, vPosition.z, 1.0);
  gl_Position = clipSpace;
}

Fragment Shader

#version 400
in vec4 clipSpace;
out vec4 frag_colour;
uniform sampler2D reflectionTexture;

void main ()
{
    vec2 ndc = (clipSpace.xy / clipSpace.z) / 2.0 + 0.5;
    vec2 reflectTexCoords = vec2(ndc.x, -ndc.y);
    vec4 reflectColour = texture(reflectionTexture, reflectTexCoords);

    frag_colour = reflectColour;
}

I'm using this code to move the camera under the water's surface to get the reflection

float distance = 2 * (m_camera->GetPosition().y - m_water->GetHeight());
m_camera->m_cameraPosition.y -= distance;
m_camera->m_cameraPitch = -m_camera->m_cameraPitch;

If this is insufficient code to diagnose the problem, I'll post more. I tried to keep it to what I thought could be the problem.


texts: What data-type should I use for in-game currency?

texts:
In a simple business simulation game (built in Java + Slick2D), should a player's current amount of money be stored as a float or an int, or something else?

In my use-case, most transactions will use cents ($0.50, $1.20, etc.), and simple interest rate calculations will be involved.

I've seen people saying you should never use float for currency, as well as people saying you should never use int for currency. I feel like I should use int and round any necessary percentage calculations. What should I use?


texts: Why doesn't my GameMaker step event work?

texts:
So I want to make some kind of floor that which the player when walks in gets his movement reduced but im having thousand of different issues implementing this since it doesnt appear to do anything ...

So i have tried different way:

1 - I have tried Step Event which had the following script:

if keyboard_check(ord('A'))
{
    player.x = -5;
}
if keyboard_check(ord('D'))
{
    player.x = -5;
}
if keyboard_check(ord('W'))
{
    player.x = -5;
}
if keyboard_check(ord('S'))
{
    player.x = -5;
}

2 - I have tried a Collision Event with the same code

3- I have tried a Step event with collision detection on a script

None of these options seem to work at all ... Can you help me?


texts: Path-finding with obstacles that can be destroyed

texts: There are several buildings on the map with size n * n， and a lot of tiles of obstacles that can be destroyed.  Suppose I put one soldier on (x,y) of the map, the soldier can reach a building by moving and destroying the obstacles.  I need a way to figure out the best choice for the soldier and because there might be a lot of soldiers I hope this process can use as little computing resources as possible.  I have come up with path finding and K-D tree finding the nearest neighbor, but neither fits well, since K-D tree works with no obstacles and  path-finding needs to traverse a lot building.  Besides, the destroying obstacles will affect those have made one path plan.


texts: Is networked gameplay inherently hard to debug and create?

texts:
I have worked with XNA before and made a simple networked game.  I have also worked with Unity3D as well.  One thing I notice on many game engine web pages is that they talk about how the engine is great for networking and makes it easier.  I then see on these pages links to articles by Valve and such about network predictions and lag which I have seen a bit of with my XNA networked game.

My question is, is networking a game inherently hard to debug and similar to design no matter what engine/framework you use?  For example is making a 4 player game with XNA or unity or UDK the same thing in terms of networking code or do some engines relieve this burden.


texts: Do games process all received user input?

texts:
A mouse might have a frequency of 125Hz, meaning that the system will read off the mouses position every 8ms. Keyboards work in a similar manner.

If a key is pressed and held down, events are continuously raised.

Does every one of these events make it to the game loop?

I imagine that if the game loop does not complete fast enough, the user interactions will buffer, causing a noticeable interaction latency.

I can think of ways to deal with this:

Add a maximum size to the input buffer so that as new events arrive, older   ones are pushed from the front of the queue as the new events are pushed to the back of the queue (enqueued).
When the key is pressed, send a "key-down" message and let the game loop repeat the received message until a "key-up" message is received.

Can anyone think of other ways to deal with user input, and do any of my suggestions have obvious flaws?

UPDATE
I am not developing a game, I am doing research and so my above questions are purely academic. I am not using any API.


texts:
I am working on Bowlingball game. And when I move the ball left and right by touching or clicking the camera moves, but it also makes ball keeps moving in the same direction even though I just moved the mouse once in that direction.

The code for moving ball left and right by touching and dragging.

void TouchInput()
{
    if (Input.GetMouseButtonDown(0))
    {
        Ray ray = RayGenerator();
        RaycastHit hit;

        if (Physics.Raycast(ray.origin, ray.direction, out hit))
        {
            if (hit.transform.tag == "BowlingBall")
            {
                obj = hit.transform.gameObject;
                objPlane = new Plane(Camera.main.transform.forward * -1, obj.transform.position);

                Ray mRay = Camera.main.ScreenPointToRay(Input.mousePosition);
                float distance = 0.0f;
                objPlane.Raycast(mRay, out distance);
                ballTouchOffset = obj.transform.position - mRay.GetPoint(distance);
            }
        }
    } else if (Input.GetMouseButton(0) && obj)
    {
        Ray mRay = Camera.main.ScreenPointToRay(Input.mousePosition);
        float distance;
        if (objPlane.Raycast(mRay, out distance))
        {
            obj.transform.position = new Vector3(mRay.GetPoint(distance).x + ballTouchOffset.x, obj.transform.position.y, obj.transform.position.z);
        }
    } else if (Input.GetMouseButtonUp(0) & obj)
    {
        obj = null;
    }
}

And the code for camera follow

public Transform bowlingBall;
public Vector3 offset;

private void LateUpdate()
{
    transform.position = bowlingBall.position + offset;
}


texts:
Brief:
I've been following this tutorial about OpenGL for 2 days, and I still can't have a triangle drawn, so I'm asking for help here. The tutorial is turned to OpenGL version 3.3 programing, using vertex arrays, buffers, etc. The libraries are: GLFW3 and GLEW, and I setted them by myself. The screen keeps black all the time.

Full code:

link here
(It's just like a Hello World opengl program)

Further Details:

I get no errors at all.
I downloaded a software to test my video card, and it supports OpenGL 4.1+
Standard OpenGL code for drawing (from earlier version) such as this one works normally.
I'm using Microsoft Visual Studio 10.0
I presume all the OpenGL implementation was dune right: I added Additional Dependences  to the linker as glew32.lib, opengl32.lib, glfw3.lib. The glew.dll was placed at SysWOW64 - because I'm running window 64bits, and glew is 32.

Notes: I've been working hard to find out what this is, but I can't find. I would appreciate if anyone could test this code for me, so I can know if I implemented something wrong, and that its not my code.


texts: What are some ways to prevent or reduce cheating in online multiplayer games?

texts:
Punkbuster exists just to prevent cheating, and yet cheating is common in punkbuster enabled games. Modern Warefare 2 is seriously locked down from the end user running their own server or making any mods, and cheating happens constantly.

For a multiplayer game where each client is running on a PC, what can be done to reduce or eliminate cheating?


texts:
I have just been reviewing Frenet Frame math. It is an interesting geometrical issue.

I know that common applications are:

camera movement along a curve
tube and ribbons surface

Can someone suggest other interesting applications?


texts:
I have created a random height map and now i want to create rivers. I've made an algorithm based on a* to make rivers flow from peaks to sea and now i'm in the quest of figuring out an elegant algorithm to render them.

It's a 2D, square, mapgrid. The cells which the river pases has a simple integer value with this form :rivernumber && pointOrder. Ie: 10, 11, 12, 13, 14, 15, 16...1+N for the first river, 20,21,22,23...2+N for the second, etc. This is created in the map grid generation time and it's executed just once, when the world is generated.

I wanted to treat each river as a vector, but there is a problem, if the same river has branches (because i put some noise to generate branches), i can not just connect the points in order.

The second alternative is to generate a complex algorithm where analizes each point, checks if the next is not a branch, if so trigger another algorithm that take care of the branch then returns to the main river, etc. Very complex and inelegant.

Perhaps there is a solution in the world generation algorithm or in the river rendering algorithm that is commonly used in these cases and i'm not aware of.

Any tips? Thanks!!


texts: CreateRenderTarget returns 0x80070057 in big surface resolution

texts:
I have created the SLI merged desktop of three 1920x1680 monitors, so the desktop resolution is 5760x1080.

There is a 0x80070057 error, while calling CreateRenderTarget to create the RT_Surface:

IDirect3DSurface9* _render_surface;
HRESULT hr = _device->CreateRenderTarget(
        _desktop_width * 2,
        _desktop_height + 1,
        D3DFMT_A8R8G8B8,
        D3DMULTISAMPLE_NONE,
        0,
        TRUE,
        &_render_surface, NULL);

It works OK with desktop resolution 1024x768, and the total resolution is 3072x768.

In http://msdn.microsoft.com/en-us/library/windows/desktop/bb174361(v=vs.85).aspx, it says

  If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be one of the following: D3DERR_NOTAVAILABLE, D3DERR_INVALIDCALL, D3DERR_OUTOFVIDEOMEMORY, E_OUTOFMEMORY.

and no description about 0x80070057.

  HRESULT: 0x80070057 (2147942487)
  Name: E_INVALIDARG
  Description: An invalid parameter was passed to the returning function

Somebody please help me.

I tried to check MaxTextureWidth and MaxTextureHeigh in D3DCAPS9 structure as @mh01 indicated, and got the value 8192 both. And what I trying to create is 11520x1080.
So, my question is what effects the value of MaxTextureWidth and MaxTextureHeigh? VideoCard model or some setting in the BIOS?

I got the below information as @RayDey said, while turn on the debug level:

  Direct3D9: (INFO) :======================= Hal HWVP device selected
  Direct3D9: (INFO) :HalDevice Driver Style b
  Direct3D9: :Subclassing window 000d0612
  Direct3D9: :StartExclusiveMode
  Direct3D9: (INFO) :Using FF to VS converter
  Direct3D9: (INFO) :Using FF to PS converter
  Direct3D9: (INFO) :Enabling multi-processor optimizations
  Direct3D9: (INFO) :DDI threading started
  D3D9 Helper: Warning: Default value for D3DRS_POINTSIZE_MAX is 2.19902e+012f, not 9.2074e-316f.  This is ok.
  Direct3D9: :WM_ACTIVATEAPP: BEGIN Deactivating app pid=00000c9c, tid=00000728
  Direct3D9: :DoneExclusiveMode
  Direct3D9: :INACTIVE: 00000c9c: Restoring original mode (1680x1050x22x120) at adapter index 0
  Direct3D9: :* Active state changing
  Direct3D9: :WM_ACTIVATEAPP: DONE Deactivating app pid=00000c9c, tid=00000728
  Direct3D9: (ERROR) :Failed to create driver surface
  Direct3D9: (ERROR) :Error during initialization of surface. CreateRenderTarget/CreateDepthStencil failed
  Direct3D9: (ERROR) :Failure trying to create render-target
  D3D9 Helper: IDirect3DDevice9::CreateRenderTarget failed: E_INVALIDARG


texts:
I want to ask about the best method of storing data that represents information's about specified objects.

I want to find a better way to storing somewhere items in my RPG game before problems had occurred, I had big ugly class, that was defining armors, weapons etc.

[System.Serializable]
public class Item
{
    public string   name;
    public int      cost;
    public float    weaponRange;
    public string   imagePath; //starting from Resources
    public ItemType itemType;
    public enum ItemType   { Item, Armor, Weapon };
    public enum WeaponType { None, ShortSecant, LongSecant, Blunt, Prickly, Bow };
    public enum ArmorType  { None, Cuirass, Helmet, Boots };

    public WeaponType   weaponType;
    //public int          damages;
    public CharacterPropertyList damages = CharacterPropertyList.AttackProperties;
    public bool         twoHanded;

    public ArmorType    armorType;
    //public int          armorPoints;
    public CharacterPropertyList armorPoints = CharacterPropertyList.DefenseProperties;

    public int   infoIndex = -1; // Represents item info position in Model Spawner Coordinate array, -1 when item have not model info -> item can't be spawned.

    [XmlIgnore]
    public bool itemExpanded = false; //expanded item in inspector?
}

But I have been able to nicely render it in inspector using PropertyDrawer.. until I had to refactor it...

I add to code some class to have better data management:

[Serializable]
public class CharacterProperty
{
    [SerializeField]
    private string name;
    [SerializeField]
    private float value;

    public float Value { get { return value; } set { this.value = value; } }
    public string Name { get { return name; } }

    public CharacterProperty(string name, float value = 0.0F)
    {
        this.value = value;
        this.name = name;
    }
}

[Serializable]
public class CharacterPropertyList
{
    [SerializeField]
    private List<CharacterProperty> properties = new List<CharacterProperty>();

    public List<CharacterProperty> Properties
    {
        get { return properties; }
    }

    public CharacterPropertyList(params CharacterProperty [] properties)
    {
        this.properties.AddRange(properties);
    }

    public CharacterProperty this[string name]
    {
        get
        {
            return
                properties.Find(p => p.Name == name);
        }}
    }

    public CharacterProperty this[int index]
    {
        get
        {
            return properties[index];
        }

        set
        {
            properties[index] = value;
        }
    }
}

And I cannot Render it correctly so finally I want to remove that big ugly Item class, and find better, more OO solution, without inspector rendering.

So I want to ask if my idea is good:

Let's say that I have a class Item, and that class will have a list that will contain child items of some interface / abstract class and that objects will be representing functionality of that Item, for example:

interface IComponent
{
 //some general data
};

public class Valuable : IComponent
{
//override some data
int Value {get;set;}
}

public class DamagesItem : IComponent
{
//damages
}

public class ProtectionItem : IComponent
{
//protection
}

public class Item
{
public List<IComponent> Components {get; set;}

public Item(IComponent [] components)
{
Components = new List<IComponent>();
Components.AddRange(components);
}
}

And next I will create those items in code, or via data stored in some XML file,
for example:

var sword = new Item(new IComponent[]{ new DamagesItem(), new Valuable()});


texts:
bool tntFall = true;

void Awake()
{
    tntFallTime = Time.deltaTime / 0.05f;
}

void OnCollisionEnter(Collision coll)
{
    if (CurrentScene != "ColorGame" && CurrentScene != "PaintingGame" && coll.gameObject.tag != "Player" && CurrentScene == "TNT Run" && tntFall)
    {
        Debug.Log(coll.gameObject.GetComponent<MeshRenderer>().material.name);
        if (coll.gameObject.GetComponent<MeshRenderer>().material.name == "TNT_0 (Instance)")
        {
            coll.gameObject.GetComponent<MeshRenderer>().material = TNT_Mat1;
            StartCoroutine(coroutine);
        }
        else if (coll.gameObject.GetComponent<MeshRenderer>().material.name == "TNT_1 (Instance)")
        {
            coll.gameObject.GetComponent<MeshRenderer>().material = TNT_Mat2;
            StartCoroutine(coroutine);
        }
        else if (coll.gameObject.GetComponent<MeshRenderer>().material.name == "TNT_2 (Instance)")
        {
            coll.gameObject.transform.position = Vector3.Lerp(coll.gameObject.transform.position, new Vector3(coll.gameObject.transform.position.x,-10,coll.gameObject.transform.position.z), tntFallTime);
            Destroy(coll.gameObject, 3);
        }
    }
}

IEnumerator TNTFallDelay(int WaitTime)
{
    tntFall = false;
    yield return new WaitForSeconds(WaitTime);
    tntFall = true;
}

This my code from Player script. If you look at my  as you can see it's actually cubes holding together. All i want is;

When player touches one of the cubes For the first time it will change material
When player touches that cube Second time it will change material again
When player touches that cube Third time cube is going to fall down.

But in these case (with my code) when i touch one of the cubes it does all of the if-else statements in a second and cube falls down.


texts: How can I find the minimum required radius to draw a visible circle?

texts:
The problem is that if for example xradius and yradius are set to 5 and the object is too big the circle will be hide under the object and won't be visible.
So I want to find the minimum radius require to draw a visible circle.

So I'm trying to use a recurse and loop over all the childs including the root objects to find what is the biggest radius and then to draw a circle according to the biggest radius.

I created a new method FindRadius.
The problem is how to get from this method the biggest radius from the List and then how to draw the circle on this radius size ? What xradius and yardius will be after finding the biggest radius ?

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

[RequireComponent(typeof(LineRenderer))]
public class DrawCircle : MonoBehaviour
{
    [Range(0, 50)]
    public int segments = 50;
    [Range(0, 50)]
    public float xradius = 5;
    [Range(0, 50)]
    public float yradius = 5;
    public bool minimumRequireRadius = false;
    LineRenderer line;
    private List<float> radiusList = new List<float>();

    void Start()
    {
        FindRadius(transform);

        line = gameObject.GetComponent<LineRenderer>();
        line.positionCount = segments + 1;
        line.useWorldSpace = false;
        CreatePoints();
    }

    void Update()
    {
        CreatePoints();
    }

    void CreatePoints()
    {
        float x;
        float y;
        float z;

        float angle = 20f;

        for (int i = 0; i < (segments + 1); i++)
        {
            x = Mathf.Sin(Mathf.Deg2Rad * angle) * xradius;
            z = Mathf.Cos(Mathf.Deg2Rad * angle) * yradius;

            line.SetPosition(i, new Vector3(x, 0, z));

            angle += (360f / segments + 1);
        }
    }

    private float FindRadius(Transform root)
    {
        foreach (Transform child in root)
        {
            TraverseHierarchy(child);

            var rend = child.GetComponent<Renderer>();
            if (rend != null)
            {
                float radius = rend.bounds.extents.magnitude;
                radiusList.Add(radius);
            }
        }

        return radiusList[0];
    }
}

This is for RTS games too when selecting a unit and there should be a circle around it mark that the unit have been selected.

For example now there is a circle drawn on the MissilesTurret the problem is that the circle radius is xradius 5 and yradius 5 the circle is too short and hiding under the turret base part so it can't be seen only if I will make a lot of zoom in:

And this is after making zoom in to the base part:

Now if before running the game I'm changing the radius of the circle from 5/5 to for example xradius and yradius to 10 now you can see the circle:

My problem is how do I know what radius the circle should be drawn for each unit/s ? Each unit have another radius/size. I don't want to draw it with the mouse for selecting yet I want it to be drawn and selected automatic. So I thought to calculate the minimum required radius for drawing the circle to be see it.


texts: How to make snake movement smooth not grid based like slither.io snake?

texts:
I try to find the right formula to mimic the smooth non-grid movement of the slither.io snake.

I can do it manually to save each point the "head" movement  went and do some interpolation in between its body parts but it is very error prone.

Also I find this: http://www.emanueleferonato.com/2014/06/10/html5-string-avoider-game-made-with-phaser/

Which is not working in my case but do show something similar

Here is a picture to express what I want to do:

Any idea how to do it right?


texts: How to apply a force to a wheeled veichle and make wheel rotate ?

texts:
I've a veichle with 4 wheel and 4 wheel collider.

My veichle is a toy.. so i would like to apply an impulse force (veichle rigidbody.addforce) to that veichle, move it and make wheel rotate...

How can i do ?

Thanks


texts: Bullet Physics - Collision not working when moving btBvhTriangleMeshShape

texts:
I have a robot (btTriangleMeshShape for each component) and a chain of boxes used as a cable, which is anchored on two components of the robot. I want to rotate a robot component and when this happens, I want to twist/ roll the cable on that component. The problem is - when i rotate a robot component, collision does not work anymore with that component.

I cannot use btHullShape because of the lack of accuracy, neither btGimpact because of the complexity of computations (which gives a really unsatisfying performance). I couldn't improve enough any of these two shapes, so that is why I use btTriangleMeshShape and rotate it by code.

Also, I have replaced the btTriangleMeshShape of the rotating component with a simple static box and rotate the box. Using the box shape, collision is working with that box.

So the problem of collision not working is only when trying to rotate a (static) btTriangleMeshShape.

Here is the code I use to rotate the static body, although I don't think it's necessary (it works for box shape, not for triangle mesh shape):

   btTransform tr = m_dynamicsWorld->getCollisionObjectArray()[7]->getWorldTransform();
   static float angle = 0.f;
   angle += 0.1f;
   tr.setRotation(btQuaternion(btVector3(1, 0, 0), -angle));
   m_dynamicsWorld->getCollisionObjectArray()[7]->setWorldTransform(tr);

   m_dynamicsWorld->updateAabbs();
   m_dynamicsWorld->computeOverlappingPairs();

I have to mention that I've searched the web before and couldn't find any solution and also I'm a newbie on Bullet Physics and any graphic libraries.

Any help would by really apreciated,


texts: What to focus on in developing a game demo for an interview?

texts:
In other threads on this very website, it has been repeatedly stressed that having a game demo to showcase at a job interview is of paramount importance, so I decided to have a go and write my own game demo.

I would like to know what is typical for interviewers to focus their attention on while reviewing your game demo.

I shall clarify that I don't have a specific opening available to me right now, but that I would probably target gameplay and/or AI programming positions. Because of this I can answer by myself in terms of broad categories: "fancy graphics" shouldn't be my priority focus while "computer's players behaviour" should... Yet - having no direct experience of this industry - I would like to know if there are less obvious stuff I should pay attention to:

How important is code modularity?
How important is to showcase a typical algorithm implementation?
How important is to include novel features?
How important is playability?
Should I privilege code readability or code optimisation?
How important is code documentation?
etc...

Mind that the above are just examples to illustrate the level of detail I would appreciate in the answer, they are not specific subquestion that I would necessarily like to be addressed (unless you think it's relevant to discuss some of them).

Thanks in advance for your time and expertise.


texts: Adding 2D versions of real cars in a game can be a legal issue?

texts: I've been thinking in doing a car game, but i wanted to add "real" cars into the game. Are 2D renditions of the cars with sprites/vector 2d graphics fine?


texts: Physics-perfect (or somewhere near) 3d sound engine

texts:
I'm new to game programming, although I have some years of experience in console/web development. My problem is not so much that I can't find what I'm looking for, it's just that I don't have the terminology to actually perform a successful search.

I am looking for a physics engine which has great focus on sounds. In fact, I do not care at all for anything else. What I mean is better explained by an example:

Suppose a 1st person type game. You are facing North, and someone somewhere around you throws a flute at you (nevermind the absurdity of the situation). The flute spins while it is on its way, making sounds through its holes. There is a wind of say, 5 knots South.

I imagine a physics engine will be capable of calculating the trajectory of the flute, as well as the direction it takes after it hits. What I want is for the physics engine to calculate the precise sounds it will make, from any listener's perspective.

Does any such engine exists? If there are several, which one would be best for the example above?


texts: Any major perf (or otherwise) concerns with rendering to/from big partial texture rather than multiple?

texts:
I have a very low res mobile game I'm working on that takes multiple rendering passes followed by a pass the composes them. Currently, I have a tex for each pass- each of which gets given to the shader for final composition.

I want to keep # of textures used low, and I'm only able to sample from so many textures per-shader anyways (esp. for mobile). So I'm thinking each render pass would instead render to a portion of a single, bigger texture. Then the composition pass would sample the same texture from multiple places. Are there any red flags that pop out regarding this strategy?

My biggest worry is it would totally thrash the texel cache (since every frame, every pixel samples the exact same texels for all the textures (each texture is a 1 to 1 mapping of the screen) = incredibly predictable/efficient caching. However, I really only have a very basic understanding of how that works so I could be totally wrong.

Also, note that my game is incredibly low resolution (128x256), so a single "giant" texture that could hold maybe 6 screens would still be pretty small at the end of the day.

Any insight is helpful! Thanks!


texts: How to create fog effect over specific tiles in dungeon game

texts:
I'm working on a game in unity and I have areas the player cannot enter blocked off by game objects that are animated sprites that are supposed to look like fog. They don't look that great and I'd like to try something a little more complex, but as a beginner with Unity I don't know where to start.

I'd like to make a fog effect that surrounds the tiles that are blocked (Similair to this asset I found. But I only want it to be seen over specific tiles.)

I also looked into something like a darkness emitting light, but haven't found anything that works.

Here is a picture of the scene hierarchy.


texts: Dump texture from memory to the original format?

texts: How can you dump GPU memory (images and such that are loaded on it) to the standard format ?


texts: I need to check if the game's SDL Window is open before I can start rendering graphics, normally I would know how to this, but the problem is the window is created in the main class, and I need to check if the window is open in the menu class. How do I check if the window is open in an entirely different class?


texts: So, a few days ago, I got the itch to try my hand at creating a modded version of one of my favorite Wii games: Star Wars: The Force Unleashed. However, when I unpacked the ISO, I noticed some of the files had the extension .RKV. I have scoured the internet in search of any information, but all I could find was that this file extension is typically associated with RKive archives. After going through all the trouble of getting that software to run on a Win95 VM, it too could not open the file. In fact, it said it wasn't even an RKive archive. I have spent all whole day researching with no progress, so if anyone could tell me what this file extension is and how to open it, I would greatly appreciate it.


texts: How to programmatically place objects in an arc and rotate them?

texts:
I have created an arc of circles from the inspector without any issues, but I need to create them programmatically. The image below shows what I'm looking for.

How can I get the positions at which to instantiate them, and how would I easily rotate them around the circle path, so that the arc ends up on the other side of the circle?


texts: How would I prevent parts of my player model from displaying on the camera?

texts:
The "legs" of my playermodel are shown when looking down. I'm using the Unity First Person Controller template.

Character when in Scene view:

Character when looking down in Play mode:


texts: Would flipping a sprite depending on direction be too inhibitive for modders?

texts: For a game I'm making (similar to games like Terraria, Starbound etc.) I want to ensure that the framework is as modder friendly as possible. This leads me to wonder if it would be too inhibitive to modders if I only allowed them to create one sprite, then the game flips the sprite depending on what direction you're walking/facing. The only reason I want to make the game flip sprites is because my file structure is already horrible, and I feel like creating another right/left folder would make the whole think even worse.


texts: Setting up a shader for RTS construction grid visibility (around cursor)

texts:
I've set up a shader, thanks to the good help of @DMGregory over at : Draw animating grid with terrain deformation and variable colors
here's what I got so far :

here's what it's supposed to look like :

here's what my shader code looks like as it stands :

forgive my non-2K + screen it's only a 1080p but this is the full shader.
here's each bit in isolation :

here's the main options for the node :

If I set surface to transparent...
I get a much better result :

yet still not what I want because the grid area fades out immediately instead of staying at the center of the cube :

also the corner clearly has a green and red line overlap when line should only ever be red or green.
this is the mock file that I'm currently using for buildable and non buildable area :

it's 256x256 (the size of my map) for now because I want to start small (where 1px maps to one unity square on the terrain of 1 unit) before I move on to the real deal which should be a 3584x3584 Texture 2D (where 1px corresponds to 1/14th of a unity unit).
I want my grid to be 1/14th of an digit. eg cell one is (in diagonal) from (0.0f, 0.0f) to (0.14f, 0.14f).
I've got preliminary code which will serve to generate this texture 2D programmatically :
    editable2DconstructibleMap = new Texture2D(256, 256, TextureFormat.RGBA32, false);
    constructionGrid = GameObject.FindGameObjectWithTag("GridViewer").GetComponent<MeshRenderer>();

    // fill texture color corresponding to navMesh
    for (int x = 0; x < editable2DconstructibleMap.width; x++) {
        for (int y = 0; y < editable2DconstructibleMap.height; y++) {
            NavMeshHit hit;
            if (NavMesh.SamplePosition(new Vector3(x * 1.0f, 0f,y * 1.0f), out hit, 1.0f, NavMesh.AllAreas))
            {
                editable2DconstructibleMap.SetPixel(x, y, Color.white);
            }
            else
            {
                editable2DconstructibleMap.SetPixel(x, y, Color.black);
            }
        }
    }
    constructionGrid.sharedMaterial.SetTexture("BuildableMask", editable2DconstructibleMap);

Here I'm using the navMesh which itself is automatically generated based on terrain slope.
I target each point of the map and see if it falls in or out of the navmesh.
Instead of redrawing this texture 2D when a building is placed and placement becomes impossible. I think I'll simply programmatically edit the 2D texture to add the new black pixels whilst the navmesh will be updated independently.
Anyways, I guess the green + red overlap issue comes from my texture2D being currently too small, but if I don't know yet what one pixel corresponds to, I'll have trouble getting this right.

Update :
so changing the texture to one of 3584x3584 did not help. I still have the exact same behavior.
So basically what did I get wrong in following the instructions from the other answer?


texts: Is 50KBs of bandwidth practical for players?

texts:
For my client-server lockstep 16-player RTS game, I've calculated the maximum bandwidth usage per second to be 50KBs for hosting a game (though this value is closer to 20KBs practically). ~90% of this bandwidth usage is due to sending out packets and the rest, incoming packets.

To cut down on costs, I'd like to have players host games and official servers function in the background as backups (in case the player host drops). Is it reasonable to expect 1 in every 16 players is able to handle this bandwidth demand?

Note: The game will be on PC.


texts: Unity Vertex Color Shader with Transparency

texts:
I'm trying to achieve a simple effect: I have a cube mesh and I want some of the vertices to change color. In this case, I want it to form some sort of a gradient where the unchanged vertices are set to the default color (with alpha = 1) and the changed vertices to slowly fade (default color with alpha decreasing towards 0).

I'm able to modify these vertices' color with this piece of code:

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

public class Test : MonoBehaviour
{
    Mesh mesh;
    Vector3[] vertices;
    Color[] colors;
    List<int> verticesToChange;

    void Start()
    {
        mesh = GetComponent<MeshFilter>().mesh;
        vertices = mesh.vertices;
        colors = new Color[vertices.Length];
        verticesToChange = new List<int>();

        for(int i = 0; i < vertices.Length; i++) {
            colors[i] = Color.white; //Set the default vertex color
            if(Mathf.Approximately(vertices[i].y, 0.5f)) //Change only the vertices on the plane y=0.5
                verticesToChange.Add(i);
        }

    }

    void Update()
    {
        foreach(int i in verticesToChange) {
            colors[i].a = Mathf.Max(colors[i].a - Time.deltaTime * 0.5f, 0f);
        }

        mesh.colors = colors;
        //Not needed here, but I will be changing the vertices' position too later
        mesh.RecalculateBounds();
        mesh.RecalculateNormals();
        mesh.RecalculateTangents();
    }
}

My problem is selecting a shader that actually uses this color and this color only. I've tried Unlit/Color, Unlit/Transparent and Particles/Standard Unlit with multiple combinations of Rendering Mode, Color Mode and Albedo color.

Is there a built-in shader that does this and I'm not getting the right combination of its parameters? Or do I have to build my own shader?
I've never wrote a shader with Unity, so I would prefer a built-in option or an open source / free shader.


texts: How to resize the child node fit inside SKSpriteNode when resizing?

texts:
I am creating a virtual gamepad for my game, It has one main SKSpriteNode with circle image and four child node(up, down, left, right) with image. When I am using default size for all it looks perfect but it's big in size and when I tried to resize the main circle SKSpriteNode all it's child node are bigger then it's parent and I am unable to calculate size for child node that will fit for every condition(different size of Main node).

-(id)initWithJoystickImage:(NSString *)baseImage
                   upImage:(NSString *)upImage downImage:(NSString *)downImage leftImage:(NSString *)leftImage rightImage:(NSString *)rightImage
{
    if((self = [super initWithImageNamed:baseImage]))
    {
        SKSpriteNode *up = [[SKSpriteNode alloc] initWithImageNamed:upImage];
        up.position = CGPointMake(0, up.frame.size.height/2);
        [self addChild:up];

        SKSpriteNode *down = [[SKSpriteNode alloc] initWithImageNamed:downImage];
        down.position = CGPointMake(0, -down.frame.size.height/2);
        [self addChild:down];

        SKSpriteNode *right = [[SKSpriteNode alloc] initWithImageNamed:rightImage];
        right.position = CGPointMake(right.frame.size.width/2, 0);
self.size.height/2.5);
        [self addChild:right];

        SKSpriteNode *left = [[SKSpriteNode alloc] initWithImageNamed:leftImage];
        left.position = CGPointMake(-left.frame.size.width/2, 0);
 self.size.height/2.5);
        [self addChild:left];
    }
    return self;
}


texts: Unity Lighting in 2D, block light source

texts:
I'm making a 2D game in Unity, and I want to have characters walking around with flashlights. I've set the 2D sprites to a a Sprites/Diffuse material so they can using unity's lighting system. I want the flashlights to have a realistic lighting effect, in that they can't shine through walls onto other tiles.

I've created a Spot light that uses 'Hard Shadows'. (Pictured Below).

To illustrate my problem, I've created some cubes to show that the light correctly works with these 3D cubes, in that the light is blocked properly. However, you can see that the light passes through the cube and illuminates the 2D floor sprites PAST the cube.

Looks like a problem with orthogonal planes not getting the hard shadows from the cubes.

Is there any way to use Unity's 3D lighting to properly make walls so light doesn't go through objects?
(I've looked at assets in the asset store, the free ones aren't very good and require changing a lot of things).


texts:
I have an Unreal asset, and we need to convert or replicate a similar visual appearance in Unity.
Initially, we started converting the Unreal asset into FBX. Used MAYA to reload the content with relative textures and maps.
As a result, the colour scheme I see on the buildings in the Unreal engine is not the same in MAYA.
Few of the known experts said that in Unreal they might have used vertex colour for the polygons.
Question:

Can we apply a vertex colour in the Unreal engine? if you have a huge scene, how can we control assigning the wall colour (vertex colour)?
If there is an option to add the vertex colour, How can I read that data(Information) in Unreal?
Is it possible to export these properties in any form of data? so that we can load and replicate(duplicate the effect done to get a different wall colour) in MAYA?
Is it possible to make the identical scene in Unity by using Unreal asset?

I am very curious to know the answers to the above questions, any answers from you can provide an insight for us to look for the solution from a different angle.
Thanks in advance for the help.


texts:
I've been trying to program a tile based game, and I'm stuck at the collision detection.

Here is my code (not the best ^^):

void checkTile(Character *c, int **map)
{
     int x1,x2,y1,y2;

     /* Character position in the map */
     c->upY     = (c->y)                / TILE_SIZE; // Top left corner
     c->downY   = (c->y + c->h)         / TILE_SIZE; // Bottom left corner
     c->leftX   = (c->x)                / TILE_SIZE; // Top right corner
     c->rightX  = (c->x + c->w)         / TILE_SIZE; // Bottom right corner

     x1         = (c->x + 10)           / TILE_SIZE; // 10px from left side point
     x2         = (c->x + c->w - 10)    / TILE_SIZE; // 10px from right side point
     y1         = (c->y + 10)           / TILE_SIZE; // 10px from top side point
     y2         = (c->y + c->h - 10)    / TILE_SIZE; // 10px from bottom side point

     /* Top */
     if (map[c->upY][x1] > 2 || map[c->upY][x2] > 2)
         c->topCollision = 1;
     else c->topCollision = 0;

     /* Bottom */
     if ((map[c->downY][x1] > 2 || map[c->downY][x2] > 2))
         c->downCollision = 1;
     else c->downCollision = 0;

     /* Left */
     if (map[y1][c->leftX] > 2 || map[y2][c->leftX] > 2)
         c->leftCollision = 1;
     else c->leftCollision = 0;

     /* Right */
     if (map[y1][c->rightX] > 2 || map[y2][c->rightX] > 2)
         c->rightCollision = 1;
     else c->rightCollision = 0;
 }

That calculates 8 collision points

My moving function is like that:

 void movePlayer(Character *c, int **map)
 {
    if ((c->dirX == LEFT && !c->leftCollision) || (c->dirX == RIGHT && !c->rightCollision))
    c->x += c->vx;

    if ((c->dirY == UP && !c->topCollision) || (c->dirY == DOWN && !c->downCollision))
        c->y += c->vy;

    checkPosition(c, map);
 }

and the checkPosition:

void checkPosition(Character *c, int **map)
{
checkTile(c, map);

if (c->downCollision) {
    if (c->state != JUMPING) {
        c->vy = 0;
        c->y = (c->downY * TILE_SIZE - c->h);
    }
}

if (c->leftCollision) {
    c->vx = 0;
    c->x = (c->leftX) * TILE_SIZE + TILE_SIZE;
}

if (c->rightCollision) {
    c->vx = 0;
    c->x = c->rightX * TILE_SIZE - c->w;
}
}

This works, but sometimes, when the player is landing on ground, right and left collision points become equal to 1. So it's as if there were collision coming from left or right.

Does anyone know why this is doing this?


texts: Platform game: applying gravity and jumping

texts:
I am making a 2D platform game in Java but I don't know how to apply gravity and jumping on my player and other living creatures in game that it looks natural and that it is physical correct.
I have formula: speed = v0 + gt^2/2
but i don't know how to implement it in my code...

Thanks for any help.


texts:
Assuming you have classes like Player, Enemy, Map and Tile.

The first approach to structuring rendering code would be to give each a render() method and let it draw itself:

void render(){
   player.draw();
   enemy.draw();
   // etc.
}

But considering the Model-View-Controller perspective, that feels wrong... Another idea would be to make a Renderer class, but then I wonder how you give the Renderer information what to draw.

Which one should I choose and why?


texts: Is it possible to create a Facebook game that is a Windows executable?

texts:
I'm thinking of trying to make a game, and I heard Facebook is good place to make it popular, but I don't want to make a sprite-based Flash game, I want to use OpenGL for rendering to get nice graphics and good performance with it.

I know there is Java which supports OpenGL (I think), but I would like to make my game closed-source so that people cannot make their own mods for it like what happened with Minecraft.

Another option I thought was to make OpenGL executable and a Flash version, but I think it might be too much work for one guy. Not to mention I have never done anything in Flash.

So, is there any way to develop closed-source game that can be also played through a browser? By closed-source I mean the people have no way of getting the source code by decompiling it in any way.


texts: Run a few seconds of simulation just after loading a scene

texts:
I'm looking for a way to execute 3 to 15 seconds of simulation once a scene is loaded.

The problem is: some objects can be left suspended in motion while the player exits the scene. their state is saved. And the player can come back later to see the simulation resume. I have solved this type of problems in the past by running the physics engine in parallel for multiple scenes, but I could not find a way to do this in Unity.

I understand Time.timeScale could be used here, but how should I proceed to hide/not display the scene while the simulation runs or run all the time ticks in one pass before display?


texts: Löve2d: How can i select object with mouse if it's overlap?

texts:
I have already some code but i can't solved this.
How can i select one object with mouse if the objects are overlap? It's looks like solitaire game.
I wish you can understand me...

For example my code;

function love.load()

    love.graphics.setBackgroundColor(245, 255, 255)
    --1
    carda = {}
    carda.x       = 110
    carda.y       = 5
    carda.width   = 100
    carda.height  = 150
    carda.dragged = false
    carda.dropped = false
    --3
    cardb = {}
    cardb.x       = 110
    cardb.y       = 20
    cardb.width   = 100
    cardb.height  = 150
    cardb.dragged = false
    cardb.dropped = false
end
function love.draw()
    love.graphics.setColor(255, 255, 255)
    love.graphics.rectangle("fill", carda.x, carda.y, carda.width, carda.height)
    love.graphics.setColor(255, 128, 128)
    love.graphics.rectangle("line", carda.x, carda.y, carda.width, carda.height)
    love.graphics.setColor(0, 0, 100)
    love.graphics.print("Card\nA", carda.x + 5, carda.y + 5)
    --2
    love.graphics.setColor(215, 255, 225)
    love.graphics.rectangle("fill", cardb.x, cardb.y, cardb.width, cardb.height)
    love.graphics.setColor(255, 128, 128)
    love.graphics.rectangle("line", cardb.x, cardb.y, cardb.width, cardb.height)
    love.graphics.setColor(0, 0, 100)
    love.graphics.print("Card\nB", cardb.x + 5, cardb.y + 5)
end
function love.keypressed(key)
    if key=="escape" then
        love.event.quit()
    end
end
function love.mousepressed(x, y, button)
    if button == 1 and x >= carda.x and x <= carda.x + carda.width and y >= carda.y and y <= carda.y + carda.height then
        carda.dragged = true
    end
    --2
    if button == 1 and x >= cardb.x and x <= cardb.x + cardb.width and y >= cardb.y and y <= cardb.y + cardb.height then
        cardb.dragged = true
    end
end
function love.mousemoved(x, y, dx, dy)
    if carda.dragged then
        carda.x = carda.x + dx
        carda.y = carda.y + dy
    end
    --2
    if cardb.dragged then
        cardb.x = cardb.x + dx
        cardb.y = cardb.y + dy
    end
end
function love.mousereleased(x, y)
    carda.dragged = false
    --2
    cardb.dragged = false
end