texts: Collisions being detected before objects are intersecting

texts:
I'm making space invaders (in OpenGL/SDL) and I'm currently having issues with getting the collisions (box collisions) between the bullets and the enemies to be properly detected. In my update() function, I have a nested for loop which iterates through all of entities  (for each bullet) detecting if each bullet has collided with it. To do this, I have a function checkCollision() in which I'm calculating the dimensions of each enemy and bullet that gets passed in and then checking if the "boxes" for each entity are intersecting:
Function for checking collisions
bool checkCollision(Enemy* anEnemy, Bullet* aBullet) {
    float enemyTop = anEnemy->y + (anEnemy->height / 2.0f);
    float enemyBottom = anEnemy->y - (anEnemy->height / 2.0f);
    float enemyRight = anEnemy->x + (anEnemy->width / 2.0f);
    float enemyLeft = anEnemy->x - (anEnemy->width / 2.0f);

    float bulletTop = aBullet->y + (aBullet->height / 2.0f);
    float bulletBottom = aBullet->y - (aBullet->height / 2.0f);
    float bulletLeft = aBullet->x - (aBullet->width / 2.0f);
    float bulletRight = aBullet->x + (aBullet->width / 2.0f);

    //This is supposed to check that if the objects are not intersecting, return false
    if (
        (bulletBottom > enemyTop) ||
        (bulletTop < enemyBottom) ||
        (bulletLeft > enemyRight) ||
        (bulletRight < enemyLeft)
        ) {
        return false;
    }
    else {
        return true;
    }
}

Code to check collisions for each enemy in update function
//Check if each of the bullets has hit any of the enemies
    for (int i = 0; i < bullets.size(); i++) {
        for (int j = 0; j < entities.size(); j++) {
            if (entities[j] != nullptr && bullets[i] != nullptr) {
                if (checkCollision(entities[j], bullets[i])) {
                    std::cout << "bullets y position: " << bullets[i]->y << std::endl;
                    std::cout << " hit enemy y position: " << entities[j]->y << std::endl;
                    std::cout << "bullets x position: " << bullets[i]->x << std::endl;
                    std::cout << " hit enemy x position: " << entities[j]->x << std::endl;
                    delete entities[j];
                    entities[j] = nullptr;
                    delete bullets[i];
                    bullets[i] = nullptr;
                }
            }
        }
    }

For some reason, when the bullet it shot from the spaceship (player), the collisions are detected before the bullet even reaches the enemy on the screen and I get the following console output:
bullet y position: 0.610021
enemy y position: 1.85
bullet x position: 0
enemy x position: -1.0335

How should I be structuring the collision detection differently so that the objects are actually intersecting before the collision is detected?
Edit:
I was able to modify the code to make the collisions happen closer to the enemies but they still aren't very precise. I had been scaling the entities by the widths and heights so I decided to reduce the scaling factor. The problem now is that the bullets are taking out two enemies before they are destroyed.
Full Code for reference
The image below shows the instance in which the collision is being detected between the bullet and the enemy


texts: How To Smoothly Animate From One Camera Position To Another

texts:
The Question is basically self explanatory. I have a scene with many cameras and I'd like to smoothly switch from one to another. I am not looking for a cross fade effect but more to a camera moving and rotating the view in order to reach the next camera point of view and so on. To this end I have tried the following code:

    firstCamera.transform.position.x = Mathf.Lerp(firstCamera.transform.position.x, nextCamer.transform.position.x,Time.deltaTime*smooth);
    firstCamera.transform.position.y = Mathf.Lerp(firstCamera.transform.position.y, nextCamera.transform.position.y,Time.deltaTime*smooth);
    firstCamera.transform.position.z = Mathf.Lerp(firstCamera.transform.position.z, nextCamera.transform.position.z,Time.deltaTime*smooth);

    firstCamera.transform.rotation.x = Mathf.Lerp(firstCamera.transform.rotation.x, nextCamera.transform.rotation.x,Time.deltaTime*smooth);
    firstCamera.transform.rotation.z = Mathf.Lerp(firstCamera.transform.rotation.z, nextCamera.transform.rotation.z,Time.deltaTime*smooth);
    firstCamera.transform.rotation.y = Mathf.Lerp(firstCamera.transform.rotation.y, nextCamera.transform.rotation.y,Time.deltaTime*smooth);

But the result is actually not that good.

Thank you all, I fixed it this way

 var pos:Vector3 = firstCamera.transform.position;
    var rot:Quaternion = firstCamera.transform.rotation;
    firstCamera.transform.position = Vector3.Lerp(pos, nextCamera.transform.position,Time.deltaTime*smooth);
    firstCamera.transform.rotation = Quaternion.Lerp(rot, nextCamera.transform.rotation,Time.deltaTime*smooth);


texts: Implementing one-way platforms in Chipmunk

texts:
I am making game in cocos2d-x, but it's the first time I am using a physics engine i.e. Chipmunk. (It's built-in to cocos2d-x.)

I want to make a one-way platform: When my character jumps into a platform from below, they should not collide, but when falling on to one from above, they should collide. Then the player could jump up onto platforms from below, like this:


texts: how to check if player stands on platform?

texts:
I want to test if player stands on platform.

I have 32x32 platform sprites.

My code looks like

   for (block in blocks) {
    if (collides(playerX, playerY - 7, block.blockX, block.blockY)) {
     fall = true;
    }
  }

but it is works wrong.
My player sometimes fall while walking on other platforms.
my collision function works well but maybe 7 is not enough or too much.


texts: Get a Jump normal gravity based on Attractor Points, lines or Quad placed in the Level Design (in a Mario galaxy like gravity)

texts:
I have an algorithme to find.

I have a player in a 3D space on a random planet. My goal is to have an oriented gravity toward my planet. And when I jump: Find the right normal direction.

BUT I can't just get the normal of collision, here is why:

As you can see, the gravity must NOT be depending on the Normals collision, but must depend on this gravity point, line or quad I place in the Level Design

(see the 2 cube at the bottom of the planet, the jump of the player must NOT depend on the normal of collision (orange arrow), but must depend on the red arrow)

I have to find out depending on the position of the player, if the gravity will depend on the closest Gravity Point attractor, OR the closest line, OR the quad's normal direction.
Here a real screenShot exemple:

I want this algorithm to be dynamic enough to be able to place points, lines or quad in the LevelDesign as I want. This algorithm will be called at each frame when the player is in the air.

And here an exemple of the most complexe shape I would like to manage:

Here I have a white point alone, a cyan line, and 2 quad (or 4 triangles)


texts: Store and create game objects at positions along terrain

texts:
I have a circular character that rolls down terrain like that shown in the picture below.

The terrain is created from an array holding 1000 points. The ground is drawn one screen width infront and one screen width behind. So as the character moves, edges are created infront and edges are removed behind.

My problem is, I want to create box2d bodies at certain locations along the path and need a way to store these creator methods or objects.

I need some way to store a position at which they are created and some pointer to a function to create them, once the character is in range. I guess this would be an array of some sort that is checked each time the ground is updated and then if in range, the function is executed and removed from the array. But I'm not sure if its even possible to store pointers to functions with parameters included... any help is much appreciated!


texts:
When developing with libGDX, you can often read, that your should not use static variables if you plan to eventually release your game on android later.

But while trying to follow that rule, I often ran into problems where I need to use an object only once and keep it accessible from everywhere at the same time.

For example, Im developing on a game which uses an ECS-Approach where different Systems need to use the EventManager-Object to communicate with each other. By default, I would make EventManager static so I can call it from multiple Systems like that EventManager.register(EventType.TYPE_01, this) and EventManager.callEvent(EventType).

How can I avoid using static variables? Is there a best practice design pattern for something like that?


texts:
I need some help because i'm trying to open a obj file with Code Blocks.
Im already downloaded the requirements for OpenGL and GLUT libraries.
somebody knows some basic and specific steps to do it?


texts:
I'm reading up on Behavior Trees and would like to know how a good implementation for a scenario where the conditions can change or where a selector with a higher priority interrupts the current one.
To keep it simple I will use only tree "states".

FLEE
IDLE (/DECIDE NEXT POSITION)
WALK

WALK is running as long as the player has a target position. IDLE is running when player reached position or if player has no position.
Now to my question. FLEE should always interrupt the other nodes. How is this achieved in a good way?
I know this can be done in a lot of different ways so I just want to know how you would solve it.
(Sorry for no fancy node graphic. I'm on my mobile)


texts:
I'm implementing a Qix clone game and I do not have any problems with implementation but rather with possible scenario.
Is this a valid scenario for this game and if yes how exactly should gameplay go in this case?
Black - Filled, Red - Current Player's Path, Blue - Player

If this is a possible scenario, then after completing the path player will end up with two diagonally adjacent rectangles.

After that player can start moving from the bottom of the top rectangle to the right.

In this case it should be immediately considered as a complete path and fill 1x1 square or player can create a path adjacent to the top of the bottom rectangle?


texts: Can anybody guide me about where can I get the basic starter tutorials for developing using XNA framework?


texts: Which DirectX Version to use for a low poly game?

texts:
Which DirectX Version (10, 11 or 12) is recommended to use, if you want to have a low-poly game with shaders, shadow and aliasing. But not normal or height maps. Moreover my question is, because once we upgraded from directx 9 to 11 now, the GPU usage for the game was like duplicated. I can not even play it with CPU at all. It means directx 11 has higher usage even then 9.

If using Directx10, could it help to decrease the gpu usage? (Which was caused by directx upgrade)


texts:
I have been banging my head against the wall trying to get a sky sphere to work appropriately in XNA 4.0. I have the sphere loading correctly, and even textured, but i would like something a little more dynamic that can support a day/night cycle.

My issue is that, while i know a good amount of C# and XNA, i know next to nothing about HLSL. (I could make an ambient light shader if my life depended on it...) I also have not been able to find a tutorial on how to build a sky sphere like this. Of course i don't expect to be able to make an amazing one right off the bat, i would like to start small, with a dynamic coloring sky i'll work out the clouds and sun later.

My first question:
Does anyone know of any good tutorial sites that could help me get a decent grasp around HLSL?

Second:
Does anyone have a good example of or know where to find one of a gradient sky using XNA and C#?


texts:
I was going through UnityAds for Unity3D, and came across this setting:

AD TEST MODE
Force all

So as I understood it states that I will be able to see real ads, in test mode, without monetizations on my testing tool, which in my case is Unity3D IDE, but I am still getting that blue sample ad screen "Here would be your ad screen". Is there anything that I can do to check if any ad is placed for my app, and check this via code before Advertisement.Show(); statement? Or am I missing something?


texts: World Location issues with camera and particle

texts:
I have a bit of a strange question, I am adapting the existing code base including the tile engine as per the book: XNA 4.0 Game Development by example by Kurt Jaegers, particularly the aspect that I am working on is the part about the 2D platformer in the last couple of chapters.

I am creating a platformer which has a scrolling screen (similar to an old school screen chase), I originally did not have any problems with this aspect as it is simply a case of updating the camera position on the X axis with game time, however I have since added a particle system to allow the players to fire weapons. This particle shot is updated via the world position, I have translated everything correctly in terms of the world position when the collisions are checked.

The crux of the problem is that the collisions only work once the screen is static, whilst the camera is moving to follow the player, the collisions are offset and are hitting blocks that are no longer there.

My collision for particles is as follows (There are two vertical and horizontal):

    protected override Vector2 horizontalCollisionTest(Vector2 moveAmount)
    {
        if (moveAmount.X == 0)
            return moveAmount;

        Rectangle afterMoveRect = CollisionRectangle;
        afterMoveRect.Offset((int)moveAmount.X, 0);
        Vector2 corner1, corner2;

        // new particle world alignment code.
        afterMoveRect = Camera.ScreenToWorld(afterMoveRect);
        // end.

        if (moveAmount.X < 0)
        {
            corner1 = new Vector2(afterMoveRect.Left,
                                  afterMoveRect.Top + 1);
            corner2 = new Vector2(afterMoveRect.Left,
                                  afterMoveRect.Bottom - 1);
        }
        else
        {
            corner1 = new Vector2(afterMoveRect.Right,
                                  afterMoveRect.Top + 1);
            corner2 = new Vector2(afterMoveRect.Right,
                                  afterMoveRect.Bottom - 1);
        }

        Vector2 mapCell1 = TileMap.GetCellByPixel(corner1);
        Vector2 mapCell2 = TileMap.GetCellByPixel(corner2);

        if (!TileMap.CellIsPassable(mapCell1) ||
            !TileMap.CellIsPassable(mapCell2))
        {
            moveAmount.X = 0;
            velocity.X = 0;
        }

        return moveAmount;
    }

And the camera is pretty much the same as the one in the book... with this added (as an early test).

    public static void Update(GameTime gameTime)
    {
        position.X += 1;
    }


texts: How do I implement a retro-style password-based "savegame" system?

texts:
How would I make a password system for a single-player game like the ones used in older console games?

For example, Mega Man X saves work by giving you a series of numbers that you can enter later to load your save.


texts: Why do Dynamic Bones disconnect natural flow if they have ANY child gameobjects?

texts:
I've been having an issue for months now where if I have a dynamic bone chain that splits off in any way (ie. any of the chain's bones have child gameobjects), then the flow of the dynamic bone chain becomes completely disconnected and seems to do something akin to ignoring weight painting. This is hard to explain through text, so I've linked images of before and after I added a child gameobject to one of the bones in a dynamic bone chain.
Behavior without gameobject interrupting Dynamic Bone Chain:

Behavior WITH gameobject under one bone in the Dynamic Bone Chain:

This is the block of settings I have available to edit with my existing Dynamic Bone script:

This model is intended to be imported as a functional "Hand Puppet" avatar into VRchat, therefore any major project-side changes to the Unity physics engine will not be carried over in-game. VRchat has blacklisted most scripts for their game with the exceptions of Rigidbodies/Fixed Joints, Constraints, Dynamic Bones, Audio Sources, and some limited functions of Final IK.
As a brief explanation, the reason there are two white lines signifying Dynamic Bone behavior in my screenshots is that I have applied Dynamic Bone roots to two bones on the model's skeleton so that their behavior compounds to create a more fluid and natural motion (at the cost of some performance). My posted concern occurs no matter how many/few dynamic bone components are applied as long as there is at least one component on the chain.
I'm using Unity 2018.4.20f1.
I have tried countless methods involving constraints, Blender work, revised armatures, updating dynamic bones, etc, but this issue persists no matter what.
How can I fix this problem?


texts: What Collider should I use for my Player object?

texts: I am making a 3rd person game with a simple orbit cam and it works fine most of the time, but since I have a box collider and I walk across an uneven surface, the player tends to tip over. How should I set it up so the player would not tip over anymore?


texts: XNA - How to scale sizes and speeds for a minimap?

texts:
I'm recreating the arcade game StarGate, and I need to create a minimap. But I'm having problems scaling the minimap textures to fit in the radar box, and ontop of that, making sure the speed of the scrolling for the main map and mini map are proportional.

My textures are sized below:

Entire side scrolling map: 4800 x 620
Screen Size 960 x 720

StarGate screen shot below:


texts: How to prevent/"reverse" displacement from a collision?

texts:
In my game I can throw a hammer. The hammer moves based on physics in Unity.
The hammer destroys the first object it touches. I want it to continue moving as though it didn't touch anything when this happens.
To try and achieve this, I made it destroy objects using a separate, larger trigger collider, intending to destroy the object before the physical collision occurs.
However, when moving at very high speeds (as in the GIF), both colliders hit at once, so the hammer moves and the object deletes.

How can I prevent the hammer from moving when/before the trigger occurs, or (I suppose more realistically) "reverse" the movement such that there's no perceptible collision?

I tried using the impulses from each of the contacts in the collision to apply forces in reverse, but didn't really understand what I was doing and ultimately failed.

NOTE: I cannot simply disable the physics collider, because it doesn't destroy everything.


texts: What size window should i use for making an Xbox 360 game in XNA

texts: I have a basic understanding of XNA 4.0 and i want to create an xbox game. What size window should i use? should i use the 16:9 aspect ratio then put it in full screen?


texts:
I have a 2D image that i want to use to cut into a 3D mesh while leaving it closed (basically cut straight through it, and close it by generating vertices in both places it cut, front and back, to close the hole). The shape i'm cutting through is a manifold and i'm wondering if there's an easy & fast way to do it considering the shape is very high resolution (3K texture).

The 2D Shape in the image is closed but complex (probably thouthand of points vectorized)
The target mesh is a closed mesh, the odd case of intersecting with an edge of the mesh can be ignored in my case so the shape will either not intersect at all or intersect with 2 points (front and back of the mesh).

I guess i could simply vectorize the shape and then create a mesh from that and do a mesh-mesh intersection but i'm wondering if there's an easier / faster way to do it directly from the source texture.


texts: How do I get the seed of a randomly generated level?

texts:
I intend to use the Mersenne twister to generate a level using a seed , but I also want to make fixed levels, so for now I'm using XML to store data of the level (~40 numbers).

However, it would be awesome if I could get the seed of a specific level by reversing the process.

I guess if I used my own pseudo-random number generator I possibly could do it, but my question is can I do it with the Mersenne twister?

Here is an example of what I want to do:

If the seed 1234 gives output 25 65 78 01, can I get the seed 1234 knowing only the generated output?

Thanks in advance! (For those who wonder why I'd want to do this; my XML parsing is a lot slower than generating a level, plus XML files are bigger than seed numbers.)


texts: I am getting started in game development. I started by learning SDL because it seems before I start developing big games, I have to start with the most basic stuff, like Tetris or Snake. I was wondering if SDL is too low-level. If I start with something as low level as SDL, will that make other high level libraries easier to pick up? Like for example, when someone is good with assembler, C seems easy.


texts: Quad tree vs Grid based collision detection

texts:
I'm making a 4 player co-op r-type game, and I'm about to implement the collision detection code. I've read a lot of articles and stuff about how to handle collision detection, but I'm having a hard time figuring out what to go with.
It seems the quad tree is the most common way to go, but in some resources they mention the grid based solution. For having used a grid for detections in a previous game, I'm comfortable with that, but is it actually better than a quad tree ?
I'm not sure which offers best performance, and I've also ran a little benchmark, there is not much difference between both solutions.

Is one better than the other ? or more elegant ? I'm really not sure which one I should use.

Any advice is welcome.
Thanks.


texts: change random number into specific range using resolution

texts:
I am having a simple mathematical problem that i would like to scale a randomly created decimal points using numpy , then apply a formula to align this decimal points to range

range \$:\$-  \$x_\min : x_\max\$

number of points of the interval [xmin : xmax ]  :  M

number of points to be created  :  N

$$ \\resolution = \frac{(x_\max-x_\min)}{M}$$

equation if found \$:\$-

\$t_s\$ \$:\$- first point

$$ \\ t_s  = { random *  ( x_\max\ - x_\min\ - N*resolution)}\ $$

i would like to understand this equation


texts: Can I generate character with several layers?

texts:
Newbie question: I wonder if it is possible in terms of performance to generate characters in several layers in phaser (and in general). And overall if it is a good idea/practice in terms of pro/cons.

For instance, one character would be the sum of the following layers (from top to bottom)

Hairs
Face
Head
hands and forearms
clothes and shoes
arms, legs, neck and feet

I suppose that I will have to realize most of the animations for every layers and it will not be possible to change the layer orders during an animation, but by combining all these layers, I could generate more combinations, hence more characters.


texts: Circular dependency when creating entities

texts:
I have the following problem:

I have a a class called Stage, that keeps an list of entities, which it iterates over every update loop, and updates them.
One of these entities might be a weapon (PEW PEW!) that when updating spawns new entities (projectiles, KA-ZOOM, KER BANG!).
How do I add these new entities to the list in of entities in Stage?
Currently, I have Stage as an singleton with global access, so that the entities which in turn spawns entities just calls the instance of Stage's addEntity method, but that feels silly.

Stage -> Entity (weapon) -> Stage again?

I have a similar problem when creating enemies:

Stage -> Entity (enemy wave) -> Stage again

I've been thinking about passing the List into all entities that can create other entities, but then I'd have to change the update method for the base Entity class so that it takes this list, a list which most entities have no need of.
Also, when adding an entity to Stage, Stage must be made aware of a number of graphics components for that entity, in order for Stage to be able to tell the renderer (which has an OpenGL context) to load the appropriate resources for those graphic components.

Any ideas what I should do?
Am I doing it the wrong way now?

Also, while we're at it, why is Singletons so frowned upon?


texts: Maximum range of projectile fired at given force and elevation

texts:
I've gone over this again and again, and my result is obviously wrong when viewed in-action. Here's the initial formula I converted (first one):

http://en.wikipedia.org/wiki/Range_of_a_projectile

and here's my C# code:

float CalculateMaximumRange() {
    float g = Physics.gravity.y;
    float y = origin.position.y;
    float v = projectileSpeed;
    float a = 45;

    float vSin = v * Mathf.Sin(a);
    float vCos = v * Mathf.Cos(a);

    float sqrt = Mathf.Sqrt(vSin * vSin + 2 * g * y);

    return Mathf.Abs((vCos / g) * (vSin + sqrt));
}

Does anyone see what I did wrong?


texts: UDK weapon on first person not showing up

texts:
I've been following this tutorial
http://www.moug-portfolio.info/udk-weapon-basics/

all my code is the same as the page...

except here

DefaultPropeties
{
Begin Object Name=GunMesh
    SkeletalMesh=SkeletalMesh'WP_LinkGun.Mesh.SK_WP_Linkgun_3P'
    HiddenGame=FALSE
    HiddenEditor=FALSE
end object

Mesh=GunMesh
Components.Add(GunMesh)
}

i had to replace begin object for this

Begin Object Class=SkeletalMeshComponent Name=GunMesh

i think i might have forgot to add a model/skeletal so i dont have anywhere to attach the weapon to? How can I do that??

Can some UnrealScript expert please look to it for me or give me a valid tutorial link for creating a custom weapon?

thank you very much


texts: How can I generate the smallest enclosing sphere from a mesh?

texts:
I have a polygon which is defined by a set of vertices and I need the smallest sphere encompassing the mesh.

The spheres are defined by a position vector (x,y,z) and a radius.

Is there an algorithm that given a solid collision mesh with no holes generates the smallest sphere that encompasses a solid collision mesh with no holes in all cases

This is not a duplicate of this question because the question is only about a sphere encompassing a polygon soup a. I'm asking if there is an algorithm that given any solid collision mesh with no holes generates the smallest sphere that encompasses a solid collision mesh in all cases.


texts:
I want to create a game with a Minecraft style world. Now I need uv mapping for some cubes in my game. But I could not find any good tutorial in the internet. I want to use the following texture with an uv map:

Each side of the cube has a texture with 64x64 pixels. The dirt texture on the right side has to be the top of the cube.
Can anyone tell me how to use uv mapping in my case?


texts: On Android, why would you handle expansion files yourself instead of using Google Play?

texts: Why aren't all Android games using Google Play's ability to serve their expansion files? Why some are handling it themselves inside their apps?


texts: When and how to apply affine translations to vertices of a mesh with LWJGL

texts: So, I have a rigid body class, containing a list of vertices and a 4x4 transformation matrix. At the moment, I'm applying the transformation matrix to each vertex individually, and am unable to revert the translation after rendering(multiplying the vertices by the inverse causes massive model distortion), so it just keeps stacking up, and eventually the model just violently wobbles back and forth. I understand mathematically how to accomplish the transformation, I'm just not sure where to actually DO the transformation without distorting the model. I'm using Java and LWJGL, and porting the Cyclone physics engine to Java.


texts: Gamepad Input: How to assign the Dpad as individual buttons?

texts:
I've looked around and had no luck, so I want to ask here. I'm using an XBOX ONE controller for my game, I've set up the input, however my issue is with the Dpad itself.
Below is an example of how I want to implement the Dpad, but with actions instead of weapons:

but the problem is, I can't find any tutorials to explain how to actually go about setting something like this up. Initially, I tried going into the Project Settings, changing the Input but the Dpad is limited to axises and won't actually work as individual buttons.
What would be the best way to get the Dpad to work individually as buttons?


texts: LibGDX make player rotate towards mouse pointer (Player facing mouse)

texts:
I am tryna makin' a 2D game with a 3D player (kinda of Factorium). I got stuck on the rotating of the player. I'd like it look always torwards to the mouse. e.g. If I move mouse on the top-left of the window, player will rotate towards the same direction.
I read on some other question about the method below, but it doesn't work properly:
private void rotatePlayerToMouse(OrthographicCamera camera) {

    Vector3 mousePos = camera.unproject(new Vector3(Gdx.input.getX(), Gdx.input.getY(), 0));
    Vector3 playerPos = this.getPosition();//this.instance.transform.getTranslation(Vector3)

    float degree = (float)Math.atan2(mousePos.y - playerPos.y, mousePos.x - playerPos.x);
    System.out.println(degree);
    this.instance.transform.rotate(new Vector3(0f, 0f, 1f), degree);
}

This method allows player to rotate. Player rotates both direction, but it doesn't stop rotating...
What is wrong?


texts: Occasionally nothing renders until the game window is resized - how to fix?

texts:
So, I'm making a game in Java, I'm using the BufferStrategy and Graphics class to render onto the screen.

But sometimes, when I run the game nothing is rendered onto the screen. But as soon as I resize the window, everything gets rendered fine.

At first I thought it had something to do with the BufferStrategy and graphics class, but when I printed those classes in the console after the initialization, they have the same values when the game is rendering fine and when the bug occurs.

I'm confused, is there a fix for this without altering a lot of code?

I'm creating my BufferStrategy as :

canvas.createBufferStrategy(3);

bs = canvas.getBufferStrategy();
g = bs.getDrawGraphics();

I'm not sure if the bug is occuring there though...


texts: 2D Quads : Translation with OpenGL ES 2.0 on Android

texts:
I have a simple 2D engine that renders 2D textured quads, and right now I can scale the quad or rotate it, but when I try to translate it I have a strange distortion (the quad is squashed in the half left part of the screen with an infinite perspective effect), here's the code :

private final float quad_vertex[] = {
-0.5f, 0.5f, 0.0f,   // top left
-0.5f, -0.5f, 0.0f,  // bottom left
0.5f, -0.5f, 0.0f,   // bottom right
0.5f,  0.5f, 0.0f    // top right
};

final float left = -width/2.0f;
final float right = width/2.0f;
final float bottom = -height/2.0f;
final float top = height/2.0f;
final float near = 0.1f;
final float far = 200.0f;

Matrix.orthoM(projection_matrix, 0, left, right, top, bottom, near, far);
Matrix.setLookAtM(view_matrix, 0, 0, 0, 1.0f, 0.0f, 0f, 0f, 0f, 1.0f, 0.0f);

...

Matrix.setIdentityM(model_matrix, 0);

Matrix.scaleM(model_matrix, 0, scale_width, scale_height, 1.0f);
Matrix.translateM(model_matrix, 0, x, 0, 0);
//Matrix.rotateM(model_matrix, 0, x, 1, 0, 0);
x = x + 1.0f;

Matrix.multiplyMM(viewprojection_matrix, 0, projection_matrix, 0, view_matrix, 0);
Matrix.multiplyMM(modelviewprojection_matrix, 0, viewprojection_matrix, 0, model_matrix, 0);

So, any idea what is the problem ? Thanks in advance :)


texts: Any way to optimize testing each bullet for each enemy in shoot em' ups?

texts:
Possible Duplicate:
  Is there a way to increase the collision check efficiency of a system of n objects?

Lately I have been making a shoot em' up, and for collision detection I would use foreach loops, testing each bullet for each ship, like so:

foreach (Bullet bullet in BulletOnScreen.ToList())
{
    foreach (EnemyShip ship in Enemies.ToList())
    {
        if (bullet.BulletRectangle.Intersects(ship.Rectangle))
        {
            ship.ReceiveDamage(bullet.Damage);
        }
    }
}

But is there a better way to check for collision?


texts: Unity Unable to blend 2D Light renderers

texts:
I've followed the documentation on Unity regarding 2D lighting. It said to turn on Alpha blending in the options. But this is how it turns out:
If Alpha blending is off:

If Alpha blending is on:

I'm not entirely sure why it's turning black. These are my settings for the 2D light:

I've checked my layers, specifically the tile map floor, and it's on the Default layer.

I just want my lights to blend well.


texts: Move Particle to touch position on android

texts:
I am attempting to make a Particle start moving to the position of my finger on the touch of the screen.

I have been using this as the basis so far:

public void update()
{
    deltaX *= .9;
    deltaY *= .9;

    this.x += this.deltaX;
    this.y += this.deltaY;
}

public void moveTo(int newX, int newY)
{
    float dx = newX-this.x;
    float dy = newY-this.y;

    float length = (float) Math.sqrt(dx*dx+dy*dy);

    dx/=length;
    dy/=length;

    dx *= 10;
    dy *= 10;

    deltaX = dx;
    deltaY= dy;
}

now while it does move the Particle, it is rarely in the direction of my finger.
How can I make the particle have the correct amount of velocity to get to the position of my finger, but no farther?

Thanks in advance!


texts:
I learn XNA 4 and made a simple game for Windows. Now i want to run it on Xbox360.
I choose "Create Copy of Project for Xbox360" and build it. After that i have in bin folder two files with extensions .exe and .pdb and Content folder.
How i can run this on Xbox360?


texts: How should I store and load structures for 2d tile based game?

texts:
I am working on structure generation for my 2d tile based game. Structures can be anything from houses, castles, dungeons, mazes etc.

Structures are pre-defined, meaning I defined the width/height of the structure and wrote every single tile that should be placed for each coordinate.

Structure "template":

public class Structure
{
    private int width;
    private int height;

    private int[,] element;

    public Structure(int _w, int _h, int[,] _e)
    {
        width = _w;
        height = _h;
        element = _e;
    }
}

Creating a new structure:

// 0 = air

// 1 = wall

// 2 = door

Structure house = new Structure(4, 4,
{

{1, 1, 1, 1},

{1, 0, 0, 1},

{1, 0, 0, 1},

{1, 2, 1, 1}

});

This works fine for small amounts of structures. However, having tens/hundreds of structures in code is not only mess, but taking memory unnecessarily since structure generation gets called rarily. So how should I store that data?

1) Should I make a file for each structure and load from it?

2) Should I dump all structures in 1 file?

3) What file format should I use for this?

4) Does Unity provide some data containers that can be easily accessed and read from?

5) How is this usually done?


texts: Is there a free source for flat/32-bit character avatars to build off of?

texts:
I'd like to use some pixel characters as a base for tweaking into characters for my browser-based-game http://ninjawars.net .  (In other words, I take a base template and I modify it with colors and pixels slightly to make character variations)

Now, my bbg is mostly ninja oriented, so a ninja avatar to work off of would be great, but more varied character types would be good as well.  And I can probably fudge a "ninja" from some other template.

But, err, free-to-use-for-commercial-purposes (e.g. public domain) would be necessary.  I'm already makin' a little money off the site from Ads, and would certainly like to make more, so I can't use stuff for "non-commercial use only", unfortunately.

So any source for free-for-commercial-use pixel-y 32-bit-y characters to use as a starting design base?


texts:
Im trying to figure out when a vertex is visible from the main camera. I have this function:

bool in_frustum(float4x4 M, float4 p) {
            float4 Pclip = mul(M, float4(p.x, p.y, p.z, 1.0));
            return abs(Pclip.x) < Pclip.w &&
                abs(Pclip.y) < Pclip.w &&
                0 < Pclip.z &&
                Pclip.z < Pclip.w;
        }

I call it in the vertex shader, and it works fine. The problem is when I have multiple cameras, and I only want to know if it is within the frustum on one of the cameras. If the vertex is not visible from my target camera, I want all other cameras to render it (if it is visible) a particular way (for example red).

I am a little rusty on matrix transformations and the graphics pipeline, but maybe instead of passing UNITY_MVP_MATRIX into the in_frustum function, I need to pass in the MVP matrix of the target camera? Or maybe just the View of the target camera needs to be replaced in.


texts: What Is A Good Way To Make A Self Updating Game? (Python)

texts: I've been making games and I have always had a problem if I wanted to sell a game. People would have to re-buy games to get the updated version. Does anyone have any ideas on how to make a self updating game? (In python 3.)


texts:
I am looking for tips to profile the server side game loop of a Java program for CPU usage. I tried to use the TPTP plugin for Eclipse so far.

The problem I am having is that it is really slow. For example the startup of the server is normally done in less than a minute. But with the profiler it takes about 30 minutes.

Okay, I can enable the profiler only after the server is started, but I am still facing the problem that it is way too slow and using much CPU. So I am unable to connect a number of clients in order to reproduce the problem (even with disabled timeouts).

I already did some optimization based on no client at all and some very short profiling sessions with one client. This is, however, not really helpful because the game server is doing most of its work only if a player is in reach.

I am thankful for any tips on profiling for CPU usage.


texts: How to calculate all points in a 2D grid defined by an arc, given a starting point and range

texts:
I've an unit in a 2d (integer) grid-based game, which has a bearing. Now I want to display an arc, with a given radius (for instance simulating a 90 degree cone of a sensor with respect to the bearing of the unit, attaching this sensor).

How can I efficently get all points in the 2d grid to draw that 'cone' arc ?

This question actually is about a similar issue but in contrast I want to get all points and not only check if a given point is located in that sector.


texts: How can I estimate the difficulty of user-generated content in my puzzle game?

texts:
I'm making a puzzle game where one player makes a puzzle, and other players attempt to solve the puzzle the first player made.  The puzzles are a grid of squares that may contain different kinds of traps.  There's a wide variety including the following:

Traps that do initial damage, but don't fire again when you step on them again
Traps that do initial damage, and continue to fire every time you step on them again
Traps that do initial damage, and then do damage over time, but who's effect can be stopped with an antidote
Traps that do initial damage, and damage over time, but who's effects can not be stopped

In addition to all these traps, I have walls, keys, locks, and blank tiles as well.

I'm currently showing the players attempting to solve the puzzle a "difficulty" rating that I got by taking all traps that deal damage divided by all tiles total.  It seems accurate with small puzzles (4x4, 5x5), but when you scale it up (20x20, 25x25), you get deceptively low ratings for extremely difficult puzzles because of the sheer size of the puzzle.

This has led me to try to find a better solution for a difficulty rating.  Things I've considered:

Figuring out a "damage per tile" average by taking the damage all the tiles do divided by all eligible tiles a player can walk on (factor out walls), but with this approach, I can't figure out how to factor DoT (Damage over Time) tiles into it.  For instance, after 10 tiles, I can give an average amount of damage a player will take with regular traps, but how do I give them an average with a DoT trap? They could activate it on the first tile or the last, and the damage numbers are significantly different.
Figuring out a "difficulty score per tile" and trying to factor that into a rating.  All tiles are currently given a "cost" (the amount it costs the player to use them when creating the puzzle), and that number roughly correlates to how much difficulty the tile adds.  I was thinking about using that number to get a difficulty rating, but I'm unsure how I'd use it correctly.
Trying random solutions and seeing how long it takes a bot to solve it.  I don't think this is a good solution for a number of reasons.  It could be solved on the first try by sheer luck, and hide how difficult the puzzle is.  Plus, with keys and locks, backtracking is required, and I think the computing time to run these simulations would be cost prohibitive.
Ditch difficulty ratings all together.  If I can't figure out an intuitive way to show the player how difficult a puzzle is at a glance, I might just have to remove it.

I realize some of this might be hard to visualize, so here are some pictures of a puzzle and it will hopefully help you see what I mean:

The user starts at the star and makes their way to the exit.  This is a view with all the tiles visible, and when the user attempted to solve it, a lot of the tiles you see in that picture would be hidden from them until they were "activated" (by the user stepping on them).


texts: Custom editor script not updating when values are changed from script?

texts:
I have a custom editor script which I have used to neatly arrange a huge group of variables into tabs. Some of these variables change in the script and it's very useful to see what they are without printing them to the console. Before I wrote my custom inspector the values would change at runtime as expected. However, after writing my custom inspector the values only update when I first click the object in the hierarchy.

How would I go about making my editor script update whenever the values change?

This is my stripped down code:

using UnityEngine;
using UnityEditor;

[CanEditMultipleObjects]
[CustomEditor(typeof(Car))]
public class CarEditor : Editor
{
    private SomeScript myTarget;
    private SerializedObject soTarget;

    private const string tab1 = "tab1";
    private const string tab2 = "tab2";
    private const string tab3 = "tab3";

    private SerializedProperty var1;
    private SerializedProperty var2;
    private SerializedProperty var3;

    private void OnEnable()
    {
        myTarget= (SomeScript)target;
        soTarget = new SerializedObject(target);

        var1 = soTarget.FindProperty("var1");
        var2 = soTarget.FindProperty("var2");
        var2 = soTarget.FindProperty("var2");
    }

    public override void OnInspectorGUI()
    {
        //DrawDefaultInspector();
        EditorGUI.BeginChangeCheck();

        myTarget.toolbarTab = GUILayout.Toolbar(myTarget.toolbarTab, new string[] { tab1, tab2, tab3 });

        switch (myTarget.toolbarTab)
        {
            case 0:
                myTarget.currentTab = tab1;
                break;
            case 1:
                myTarget.currentTab = tab2;
                break;
            case 2:
                myTarget.currentTab = tab3;
                break;
        }

        if (EditorGUI.EndChangeCheck())
        {
            soTarget.ApplyModifiedProperties();
            GUI.FocusControl(null);
        }

        switch (myTarget.currentTab)
        {
            case tab1:
                EditorGUILayout.PropertyField(var1, true);
                break;
            case tab2:
                EditorGUILayout.PropertyField(var2, true);
                break;
            case tab3:
                EditorGUILayout.PropertyField(var3, true);
                break;
        }
    }
}


texts: What kind of skills are required to work in a content pipeline department in a high level role

texts:
I'm looking more for high level role such as producer/manager of the group making the tools for a content pipeline. This would be for a large AAA studio.

Also what kinds of tools are they creating?


texts: Why when a certain boolean variable is true, the Unity editor crashes?

texts:
In my game I've got a timer script, which counts down unless the game is paused, but whenever the variable for pausing is true, something in the timer script makes the editor itself crash, and I have to pull out the task manager to close unity because it freezes up completely.

Timer.cs

using UnityEngine;
using System.Collections;

public class Timer : MonoBehaviour {

  public LevelManager levelManager;

  // Use this for initialization
  void Start () {
    levelManager = FindObjectOfType<LevelManager>();
    StartCoroutine ("timerUpdate");
  }

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

  IEnumerator timerUpdate (){
    while (levelManager.levelTimeSeconds>0) {
      if (levelManager.isPause== false){
        yield return new WaitForSeconds(1);
        levelManager.levelTimeSeconds -= 1;
      }
    }
    levelManager.isOver = true;
  }
}

Anyone have any idea what's causing the editor to crash once isPause is true?


texts: Unity5 - A Shader to blur far plane edges?

texts:
I need some help. In my Unity5 game I'm using two cameras, First camera renders the actual terrain and game objects (wich has a far plane of a 1000 units) and the Second camera renders a 3d skybox of sorts, a miniature of the actual terrain (it's far plane is 3200 units, but it covers the entirety of the miniature). With this setup I'm able to fake the illusion of having a very far horizon, as in the image below:

*

However, the far plane's edge is very harsh, and doesn't blend well with the 2nd camera's background. Is there anyway to blur this edge, so it trasition seamlessly with the backdrop, as in the image below (a mockup I made in photoshop)?

*The blue line on the left image is just to outline the boundaries of the two cameras, it's not like this in the actual game nor is this the problem I'm talking about.


texts: Ortbit camera rotation multiplication order with quaternions?

texts:
So I switched my camera to use quaternions and the first thing I noticed is that things started to 'roll' even though I'm not using any roll values. I looked it up and I found that people suggest that using rotation = horizontal * rotation * vertical solves the issues instead of rotation = rotation * horizontal * vertical which I thought was the more intuitive thing from doing matrix multiplication. The explanations I read as to why one works and the other doesn't were pretty vague and unclear.

My question is: why does it work this way? what's wrong with 'rotation * h * v`?

Sample code:

float Horizontal = 0;
float Vertical = 0;

if (Keys['W'] == Key_Held)
{
    Camera->Position += Camera->Forward() * CamMovSpeed * DeltaTime;
}
if (Keys['S'] == Key_Held)
{
    Camera->Position -= Camera->Forward() * CamMovSpeed * DeltaTime;
}
if (Keys['A'] == Key_Held)
{
    Camera->Position -= Camera->Right() * CamMovSpeed * DeltaTime;
}
if (Keys['D'] == Key_Held)
{
    Camera->Position += Camera->Right() * CamMovSpeed * DeltaTime;
}
if (Keys['E'] == Key_Held)
{
    Camera->Position += vec_Up * CamMovSpeed * DeltaTime;
}
if (Keys['F'] == Key_Held)
{
    Camera->Position -= vec_Up * CamMovSpeed * DeltaTime;
}

// mouse
int dx = Mouse->x - Mouse->LastX; Mouse->LastX = Mouse->x;
int dy = Mouse->LastY - Mouse->y; Mouse->LastY = Mouse->y;
if (Mouse->MMB == Key_Held) // pan
{
    Camera->Position -= (Camera->Up()*dy + Camera->Right()*dx) * SpeedMul/2 * DeltaTime;
}
if (Mouse->RMB == Key_Held) // orbit
{
    Horizontal += dx * SpeedMul*10 * DeltaTime;
    Vertical += dy * SpeedMul*10 * DeltaTime;
}
if (Mouse->Wheel) // zoom
{
    Camera->Position += Camera->Forward() * Mouse->Wheel * SpeedMul*10 * DeltaTime;
}

if (Horizontal != 0 || Vertical != 0)
{
    quat QVertical(vec_Right, -Vertical);
    quat QHorizontal(vec_Up, Horizontal);
    Camera->Rotation = QHorizontal * Camera->Rotation * QVertical; // this works
    //Camera->Rotation = Camera->Rotation * QHorizontal * QVertical; // this doesn't
    Camera->Rotation.Normalize();
}


texts: Unity: Import a mesh that only has vertex and edge data but no faces

texts:
I am working on a game that requires meshes that only have edges and vertices but no faces.
In blender, you can make a mesh with only edges and vertices, but if you export it to FBX or OBJ, once it is imported into Unity, the resulting prefab has no mesh data linked to it. The prefab has no MeshFilter. It's as if I imported an mesh with absolutely no mesh data.

For example, if I create a plane in Blender and then delete the face but leave the edges and vertices, and then export as OBJ, I can open the OBJ in a file editor.
This is a square with no faces:

# Blender v2.78 (sub 0) OBJ File: ''
# www.blender.org
mtllib egdes.mtl
o Plane
v -1.000000 0.000000 1.000000
v 1.000000 0.000000 1.000000
v -1.000000 0.000000 -1.000000
v 1.000000 0.000000 -1.000000
l 3 1
l 1 2
l 2 4
l 4 3

So it appears that OBJ actually does export with the correct mesh data, however, it seems that Unity does not know how to import an OBJ if there are no faces.

Does anyone know if anyone has come up with a solution to this problem yet?
If not, I guess I'll just have to write my own parser. If that's the case, does anyone know if there is a way to extend or override Unity's built-in OBJ parser?


texts: SpriteBatch Draw Using Floats with the Destination Rectangle

texts:
So I created a nice little isometric tile engine and I have it so that when you scroll with the mouse it changes a variable called scale. Scale is a float and gets passed through the spritebatch.draw() function. I apply scale to all of the math I do when generating the positions of the tiles.

The problem I am having is Rectangle will not accept float numbers so when I make my Dest Rectangle for the spritebatch.draw() I can not use the numbers I need to because they are now floats.

I tried using vector4 instead of rectangle but the spritebatch.draw was throwing an exception saying it was expecting Rectangle not Vector4.

Is it possible to draw the dest rect using floats instead of ints?

Btw the scale is all working properly however since I am casting the floats to ints any scale that should have a decimal gets truncated and I end up with spaces between my tiles.


texts: can it be done with 2D engine or is it real 3D?

texts:
Possible Duplicate:
  How should I sort images in an isometric game so that they appear in the correct order?
  My isometric game looks flat; how can I improve this?

I'm working with andengine on a tiled map, at the moment I have only something like this

However I want to manage/introduce "heigth" like the folowing image.

Can I do this or have I do change my engine, I want now something like this :

Do you have some example/tuto explaining how to manage a "3D" tiled map?


texts: Character appearance synchronization in open world multiplayer game

texts:
I am working on a multiplayer open world game where you can equip handhelds and armor pieces. In my architecture, there are clients and an authoritative server. Every equipable item is crafted by a user. They can be different in shape, so it's important that I synchronize shape information. This is expensive data to send (basically an outline plus some more info). Together with this, I also want to synchronize any equipment event that occurs, so when a user meets another user, they can see each other's gear.

The easiest solution I've found is to force-send gear on equipment, but it will use bandwidth even when two players are far away.

This feels like a problem that has been solved a thousand times, so I don't want to reinvent the wheel. Do you know of any best practice/known strategy that suits my situation?


texts: how to release unity webgl memory from asset bundle

texts:
I have stuck in a weird problem, in my Webgl project i am loading asset bundle frequently which is working fine but after unloading the asset bundle the memory is still not releasing. I am using WWW.LoadFromCacheOrDownload method to download and cache asset bundle data.

 IEnumerator DownloadAndCacheAB(string assetName)
    {
        // Wait for the Caching system to be ready
        while (!Caching.ready)
            yield return null;

        // Load the AssetBundle file from Cache if it exists with the same version or download and store it in the cache
        using (WWW www = WWW.LoadFromCacheOrDownload(finalUrl, 1))
        {

            yield return www;

            if (www.error != null)
            {
                Debug.Log("WWW download had an error:" + www.error);
            }

            AssetBundle bundle = www.assetBundle;

            if (assetName == "")
            {
                GameObject abObject = (GameObject)Instantiate(bundle.mainAsset, gameObject.transform.position, gameObject.transform.rotation);
                abObject.transform.parent = this.transform;
                SetTreeShaderSettings(abObject);
            }
            else
            {
                GameObject abObject = (GameObject)Instantiate(bundle.LoadAsset(assetName), gameObject.transform.position, gameObject.transform.rotation);
                abObject.transform.parent = this.transform;

            }

            // Unload the AssetBundles compressed contents to conserve memory
            bundle.Unload(false);

        } // memory is freed from the web stream (www.Dispose() gets called implicitly)
    }

And even calling GC Collect to remove data

public void RemoveBundleObject()
    {

        if (loadBundleRef != null)
        {
            StopCoroutine(loadBundleRef);
        }
        if (this.gameObject.transform.childCount > 0)
        {
            Destroy(this.gameObject.transform.GetChild(0).gameObject);
            System.GC.Collect();
        }

    }

but the problem is memory is not releasing, it keep going up when i again use/load asset bundle.

Edit: I found that using LoadFromCacheOrDownload function is not good so i have updated it with UnityWebRequest but the still problem persist.


texts: How can a load and play an .x model using vertex animation in XNA?

texts:
From a game I developed years ago, I still have character models that my former 3D engine designer created and that I'd like to reuse in a Windows Phone project now.

However, the files are in DirectX format (.x) containing keyframe animation only. No bones. No skeleton.

There are a lot of animation keys defined on several frames to animate the characters.

I don't quite understand how that works, to be frankly. However, I did a lot of research regarding a possible way of getting the characters animated via XNA on Windows Phone and all I found are hints that it is generally possible but not supported. Possibly by implementing own Content Importers and Processors.

I didn't find anyone who successfully did something like that yet. How should I go about loading and displaying these models in XNA?


texts: Isometric Movement in Javascript In the DOM

texts:
I am creating a game using Javascript. I am not using the HTML5 Canvas Element.
The game requires both side view controlles, and Isometric controls, hence the movementMode variable.

I have got the specific angles, but I am stuck on an aspect of this.

https://chillibyte.makes.org/thimble/movement

function draw() {
            if (keyPressed) {
                if (whichKey == keys.left) {
                    move(-1,0)
                }
                if (whichKey == keys.right) {
                    move(1,0)
                }
                if (whichKey == keys.up) {

                    move(0,-1)
                }
                if (whichKey == keys.down) {

                    move(0,1)
                }
            }
        }

This gives normal up, down , left, and right. i want to refactor this so that i can plugin two variables into the move() function, which will give the movement wanted.

Now for the trig.

         /|
        / |
       /  | y
      /   |
     /a___|
        x

Take This Right angled Triangle.

given that x is 1, y must be equal to tan(a)

That Seems right.
However, when I do Math.tan(45), i get a number similar to 1.601.
Why?

To Sum up this question.

I have a function, and i need a function which will converts an angle to a value, which will tell me the number of pixels that i need to go up by, if i only go across 1. Is it Math.tan that i want? or is it something else?


texts: Authentication for a multiplayer game via sockets

texts:
I'm implementing a custom binary protocol for a new multiplayer game I'm working on. Its a turn-based strategy game so timing doesn't really matter. I've currently got the basic data sync portion of the system complete, and I was wondering how user login/logout and encryption is typically done for MMORPG games or similar.

Can you recommend a scheme for secure/secret password transmission during login? ( Diffie-Hellman key exchange?)
How do I implement strong encryption for data packets? (AES 128-bit? .. or whatever scheme this post refers to as "encryption stronger than you are likely to crack")
Are there datagram format schemes that help to harden the game server to replay attacks, invalid data packets and the like?


texts: How to obtain a pointer to the compiled shader in D3D11

texts:
My shader creation code looks like this.

std::shared_ptr<IRenderUtility::IVertexShader> D3D11RenderUtility::CreateVertexShader(IShader::INIT_DESC & desc) const
{
    HRESULT result;
    ID3D10Blob * errorMessage;
    ID3D10Blob * vertexShaderBuffer;
    ID3D11VertexShader * vertShader;
    D3D11VertexShader::INIT_DESC vertShaderDesc;
    char errorMsg[255];

    result = D3DX11CompileFromFileA(desc.fileName.c_str(), NULL, NULL, desc.entryPoint.c_str(), "vs_5_0", D3D10_SHADER_ENABLE_STRICTNESS, 0, NULL, &vertexShaderBuffer, &errorMessage, NULL);
    if(FAILED(result))
    {
        if(errorMessage)
        {
            OutputErrorBlob(errorMessage, desc.fileName.c_str());
        }

        sprintf_s(errorMsg, "D3D11_Renderer | D3D11RenderUtility::CreateVertexShader \n\tfailed to compile shader file %s %i", desc.fileName, __LINE__);
        throw std::exception(errorMsg);
    }

    result = m_Device->CreateVertexShader(vertexShaderBuffer->GetBufferPointer(), vertexShaderBuffer->GetBufferSize(), NULL, &vertShader);
    if(FAILED(result))
    {
        sprintf_s(errorMsg, "D3D11_Renderer | D3D11RenderUtility::CreateVertexShader \n\tfailed to create the vertex shader %i", __LINE__);
        throw std::exception(errorMsg);
    }

    vertexShaderBuffer->Release();
    vertexShaderBuffer = 0;

    vertShaderDesc.shader = vertShader;

    return std::shared_ptr<IVertexShader>(new D3D11VertexShader(vertShaderDesc));
}

IRenderUtility, D3D11RenderUtility, IVertexShader, D3D11VertexShader, and IShader are my stuff. My question only pertains to the Shader creation code. At a later point, after the shader is made, i would like to create an input layout, but without the blob to get a pointer to the compiled shader, i cannot. Is there any way to obtain a pointer to the compiled shader from ID3D11VertexShader after it is created, or should i keep the blob around, storing it in my VertexShader object? How big is it?


texts:
I would like to add a chainsaw (or something similar to it... a rotary blade) to my game as a melee weapon. In fact, a rotary blade is a better example.

Would it be better to do it in blender somehow, using skeleton, or should I just create two parts (the handle and the blade) and then rotate it in UE4?


texts:
I made a 3D game in Unity named Sniper Shot.

I am facing a problem when I build the project: at the end it shows the wrong date of build.

I have tried many scripts resolving this issue but I did not find any accurate way to fix it.

I completed this project on 4 march 2019 but this is showing me a wrong date, 23 July 2017.


texts: How to model irregular boundary of a 2D map in Game?

texts:
I am creating a map in a game, the map contains different countries, my question:

Q. How to model the irregular boundary of each countries? How to do quick country searching if I click on the map (given x,y values)?


texts:
I have a cartoon car and it has a skid sound with the car skids. But when the car flips over the skid sound plays endlessly and its really annoying. I have a basic script that is meant to detect when the car is upright and only play the skid sound with the car is upright. Here is the code:

This script is on the car itself:

public bool IsUpright () {
        Vector3 rotationInEuler = transform.rotation.eulerAngles;

        float tiltX = Mathf.Abs(rotationInEuler.x);
        float tiltZ = Mathf.Abs(rotationInEuler.z);

        if(tiltX < uprightThreshold && tiltZ < uprightThreshold){
            return true;
        }else{
            return false;
        }
    }

This script is on a skid sound prefab:

void Update () {
        if(motor.IsUpright()){
            if(motor.IsMoving()){
                transform.GetComponent<WheelCollider>().GetGroundHit(out tireHit);
                currentFrictionValue = Mathf.Abs(tireHit.sidewaysSlip);

                if(skidAt <= currentFrictionValue && skidWait <= 0){
                    Instantiate(skidSound, tireHit.point, Quaternion.identity);
                    skidWait = 1;
                }
                skidWait -= Time.deltaTime * skidEmission;
            }
        }
    }

When the IsUpright bool (first script) is printed to the console it keeps flickering between true and false and it isn't detecting when the car is upright. By the way the uprightThreshold from the first script has a value of 40. I have also check in the inspector and the rotation of the car on both the x and z axis are not constant at 0, it is flickering up and down between about 1 and -1, but unfortunately unity doesn't support having negative rotation values, so rather it goes to 359, which is mucking up the system. Could someone show me how to fix this? Thanks in advance.


texts: XNA - Saving Game Data without TypeWriter?

texts:
In the past, I've had some trouble with reading and writing content for XNA. I think I'm firmly set on this tutorial which sets up a four project structure (Game, Content, Library, Pipeline Extension) for the solution that other websites suggest, too. The options it offers for content reading seem great.

But problem! This tutorial (and all others I've found) have stated that the Content Pipeline Extension Project is not distributed with the game, which is fine in itself, but this is combined with the fact that any content writing objects are placed in this non-distributable library. The ability to actually write content of an already existing type (save game files, namely) is pretty critical to the project I'm trying to make.

I've already learned the hard way you simply can't place the Content Pipeline reference in another project besides the extension for easier access to the intermediate deserializer. Is there another object I can access for writing save game data? Am I actually, despite the warnings of this tutorial, able to use the TypeWriter outside of the Content Pipeline Extension Project? Or is there a third option I am missing here?


texts: Frequently change TextMeshPro text without garbage allocation?

texts:
Is there a way to frequently change a timer display created with TMP, without it generating garbage?

I'm currently using TMP.SetText(), which is supposed to not generate garbage, but it does.


texts: Blender Cycles materials not showing in Second Life

texts:
I ran into a problem after trying to import my own creation into second life. While I am not new to 3D modelling with Blender and other programs, I have always only created things for fun. Now I have decided to import few of those creations into Second Life but the materials I have used do not display in the preview at all. I have used the Cycles Render.

How do I solve my issue with Materials not displaying in Second Life after Exporting a Collada file from Blender Rendered in Cycles?


texts: Sever Structure for a Turn Based Game (Chess)

texts:
I am working on a Turn-based Game (Chess)

I have done the client part and single player mode so AI is no problem here. But the only problem is now I want to make my project multiplayer. I have done the part to setting and retrieving high-scores and other Informations. Now I am stuck on server structure since I got no idea on which server to use:

My game Multiplayer structure:

User logs in
Can choose between 3 rooms
each room got 10 levels (rooms) inside
game will automatically send each player to a curtain room based on their rank
players will be assigned to each other and start the game
each player got 30 secs to make a move otherwise they will lose their turn
At the end scores will be sent to the DB

Options suggested by friends:

SmartFox
Google App Engine

Why not using mentioned servers:

some many functions which I will not need (Performance)
MY project is a small project (self study no need ready servers)
Need to do it by myself for educational purposes

Program Languages used:

Clint-> C#
Server -> php, SQL

Questions:

is HTTP good enough to handle 500-1000 users at a time?
can handle this kind of games with WWW and WWWFORM in Unity2D?
if no any options?

Thanks


texts: How do I lower the resolution scale in DX11?

texts: I've tried a lot of things including lowering the backbuffer size but that causes terrible scaling that I can't really control. I've also tried rendering the scenes to a smaller texture then scaling it up but that requires me to change all my coordinates and I'm pretty sure there's a better way. I'm trying to scale 800x600 scenes down to 200x150 then scaling them back up.


texts: Calculating angle between two vectors to steer towards a target

texts:
I have been trying to implement a path following steering behaviour for AI in a 2D racing game.

I have two vectors:
futurePosition represents the predicted future position given the car's current heading.
futurePathPosition represents the nearest point on the path to the predicted future position.

By working out the relative orientation of these two vectors, I should be able to determine whether the car needs to turn left or right in order to head towards the centre of the path.

I've tried different calculations, but I just can't get it to follow the path consistently. Occasionally the car will turn the wrong way and get "stuck".

I am currently determining the angle using the cross product, as suggested here.

var a = Vector2D.normalize(this.futurePathPosition);
var b = Vector2D.normalize(this.futurePosition);
var d = Vector2D.cross(a, b);

if(this.futureDistanceFromPath > this.trackRadius) {
  if(d > 0)
    this.steerLeft();
  else if(d < 0)
    this.steerRight();
  else if(d == 0)
    this.steerAngle = 0;
}
else
  this.steerAngle = 0;

Any tips on what might be causing this bug would be appreciated.

Also, I wondered if axis orientation affects how calculations are performed on vectors? In canvas the y axis faces "south", but in the vector tutorials I have read I haven't seen axis orientation mentioned.


texts:
For some reason, the update function is only running once. Why does this happen?

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

public class LightFlicker : MonoBehaviour
{
    float timer;
    float timetowait;
    // Use this for initialization
    void Start()
    {
        timer = 0;
        timetowait = Random.Range(0.01f, 0.8f);
    }

    // Update is called once per frame
    void Update()
    {
        Debug.Log("Updating");
        timer += Time.deltaTime;
        if(timer >= timetowait)
        {

            if (gameObject.activeInHierarchy == true)
            {
                gameObject.SetActive(false);
            }
            else
            {
               gameObject.SetActive(true);
            }
            timetowait = Random.Range(0.01f, 0.8f);
            timer = 0;
        }
    }
}

The debug.log statement only fires 9 times. The timetowait changes, but the timer stays the same.


texts:
I'm trying to move my project to Addressables and upload assets, prefabs and screens to an archive on the server.
I'm a new in Unity and this a bit challenging for me.
I've prepared all prefabs for addressable usage and now I'm trying load them.

All my prefabs have loads throw GameObject.Instantiate
For example:

    public class PlatformObject : LocationObject
        {
//other properties and methods
            public PlatformObject Clone()
            {
                var clone = ((Runner.PlatformObject)GameObject.Instantiate(this));
                clone.Id = this.Id;
                clone.NextPlatforms = this.NextPlatforms;
                clone.IsStartPlatform = this.IsStartPlatform;
                clone.Level = this.Level;
                clone.Type = this.Type;
                clone.MinimumDistance = this.MinimumDistance;
                clone.AllowDispose = false;
                clone.Size = this.Size;
                return clone;
            }
    }

I've tried change this code for usage Addressables.

public async Task<PlatformObject> Clone()
        {
            var handle = Addressables.LoadAssetAsync<GameObject>(this.name);
            var clone = (await handle.Task).GetComponent<PlatformObject>();
            clone.Id = this.Id;
            clone.NextPlatforms = this.NextPlatforms;
            clone.IsStartPlatform = this.IsStartPlatform;
            clone.Level = this.Level;
            clone.Type = this.Type;
            clone.MinimumDistance = this.MinimumDistance;
            clone.AllowDispose = false;
            clone.Size = this.Size;
            return clone;
        }

I've got a cloned object successfully, but object doesn't appears on the scene. Looks like object not initialized properly, bcouz I've got a lot of warnings like that:

  Setting the parent of a transform which resides in a Prefab Asset is
  disabled to prevent data corruption (GameObject: 'Mid_Town_07').
  UnityEngine.Transform:set_parent(Transform)

I've googled and have found a few solution related with parent location.
Made changed but it didn't help. I'm still getting those warnings.


texts: Storing visibility graph for path-finding: do redundant and non-visible pairs of points have to be saved?

texts:
Using C# in Unity, I have recently implemented an algorithm that determines during run-time the visibility graph of a given scene in my game project (visibility between corners of obstacles). Now I am in doubt about the best way to save the result.

So, considering that I want the visibility graph for path-finding, I would like to know the following:

1) Suppose that points A and B are visible to each other. Then, AB and BA both detect the same visibility line. It happens to all mutually visible pairs in my case. So, in order to perform an A* algorithm do I really need all these redundant pairs or can I get rid of the redundant ones, leaving only AB or only BA?

2) Now suppose that points A and C are NOT visible to each other. Do I have to save AC and/or CA? It is, to apply an A* algorithm do I have to save pairs of points that are not visible?

I ask that because if the answer to both questions is "yes", then the final array storing the graph becomes NxN, where N is the number of points (corners of obstacles) in the scene, with each cell holding the value 0 for non-visible pairs or a value equal to the distance between each visible pairs. I think technically it is called an Adjacency Matrix.

However, if the answer to any or to both of these questions is "no", then I would be able to save a lot of memory because the final results would require a much smaller array. The reason is that I would then not save redundancy and also most points are not visible to each other (it's technically a non-dense graph), so they would not be included.

But I am not sure I can go that route for path-finding. So, in case the answer to any of the 2 questions above is "no", what is the logical format I should use for saving the results, in order to perform an A* algorithm in the visibility points?

Many thanks for your time.


texts: There is no ".text" after i type guitext in "void update" of "monodevelop"

texts: I want to write a text in game scene... but when I type GUIText (in Update()) then dot after that, when I type "t" there is no text to become a GUIText.Text, why?... I'm using Unity 5.6.4(64 bit).


texts: How do I have to take into account the direction in which the camera is facing when creating a first person strafe (left/right) movement

texts:
This is the code I am currently using, and it works great, except for the strafe always causes the camera to move along the X axis which is not relative to the direction in which the camera is actually facing. As you can see currently only the x location is updated: [delta * -1, 0, 0]

How should I take into account the direction in which the camera is facing (I have the camera's target x,y,z) when creating a first person strafe (left/right) movement?

    case 'a':
        var eyeOriginal = g_eye;
        var targetOriginal = g_target;
        var viewEye = g_math.subVector(g_eye, g_target);
        var viewTarget = g_math.subVector(g_target, g_eye);
        viewEye = g_math.addVector([delta * -1, 0, 0], viewEye);
        viewTarget = g_math.addVector([delta * -1, 0, 0], viewTarget);
        g_eye = g_math.addVector(viewEye, targetOriginal);
        g_target = g_math.addVector(viewTarget, eyeOriginal);
        break;
    case 'd':
        var eyeOriginal = g_eye;
        var targetOriginal = g_target;
        var viewEye = g_math.subVector(g_eye, g_target);
        var viewTarget = g_math.subVector(g_target, g_eye);
        viewEye = g_math.addVector([delta, 0, 0], viewEye);
        viewTarget = g_math.addVector([delta, 0, 0], viewTarget);
        g_eye = g_math.addVector(viewEye, targetOriginal);
        g_target = g_math.addVector(viewTarget, eyeOriginal);
        break;


texts: LibGDX - Turning TiledMapTiles into objects

texts:
I'm working on a harvest moon type game and I've already created lots of assets and have a working player. Now the issue is with the tile map. I use Tiled Map Editor to make the map and it renders  fine.

But if I want to be able to turn grass into farmland and plant seeds and such to allow crops to grow, how would I do that?

It would be rather simple using different classes like a Farmland and Crop class and make so that Farmland has a Crop currentCrop; attached to it.
But putting this together while still using a Tilemap editor seems rather difficult, since I don't actually get any Tile objects from the .tmx.

The way I could do it with Tiled is in my MapManager class I could have a

public void setCell(int x, int y, int type) {
    Cell cell = new Cell();
    switch(type) {
    case 0:
        cell.setTile(map.getTileSets().getTile(0);
    break;
}

etc.

But it feels like that would be a pain to keep track on how much thing have grown and so on and just feels like a clumsy system.

Am I going about this the right way?

Thanks in advance!


texts:
I'm toying with Perlin Noise after some work with Diamond Square. I followed the implementation by Hugo Elias that basically, makes a series of functions with x,y as input to throw each coordinate value.

My PHP code is here:

I have two questions:

How do I use the algorithm to generate a height map in an array? I did not fully understand it and just ported to PHP the pseudocode, but doing the last function (map_perlined) after reading somewhere that the algorithm "magically" gives you transitioned values for each x,y point given (apparently, without having to read its adjacent values), I just get this when using as random function mt_rand(-100,100)/100;

And this when using the cryptographic: 1.0-(($n*($n*$n*15731+789221)+1376312589)&0x7fffffff)/1073741824.0; (which, BTW, can be implemented "as-is" in PHP?):

So, summing up, three questions:

Is my code correct?
The random function can be ported to PHP as described in the code? It throws no errors, but the results are not there.
How do I actually use the algorithm?

UPDATE

Ok, made a PHP port of the code shown in Gustavson paper, and as other coder said, it just generate one octave. Have any other useful site/paper/guide about how to use this with the concepts of multiple octaves, amplitude, frequency, etc. to control the noise function? On Gustavson's paper just shows the results, not the actual implementation of the algorithm, perhaps i'm missing something?

UPDATE 2
@NATHAN

I made something like:

$persistence = 0.5;

for ($j = 0; $j < $size; $j++) {
    for ($i = 0; $i < $size; $i++) {

        for ($o = 0; $o < 8; $o++) {
            $frequency = pow(2,$o);
            $amplitude = pow($persistence, $o);
            $value += SimplexNoise($i*$frequency, $j * $frequency) * $amplitude;
            }

            //$value = SimplexNoise($i, $j) + 0.5 * SimplexNoise($i, $j) + 0.25 * SimplexNoise($i, $j);
            $this->mapArray[$i][$j] = new Cell($value);

And after normalizing the values to 0..1, I get a rather dull height map such as:

How do I seed the map?
Perhaps what I need to implement is the 3d version with the third value a random height? But if so, I'd have to find out to take in consideration neighbour values, which I'd be ending with something like a diamond square algorithm, exactly what I do not want to do.

UPDATE 3

More Perlin work. I have yet to find a way to guide the noise to my results. Check these octaves and the final result:

Octave I to IV

Summed up

Each octave is pretty much the same. Check the code:

$persistence = 0.5;

    for ($j = 0; $j < $size; $j++) {
      for ($i = 0; $i < $size; $i++) {
        $value = 0;

        for ($o = 0; $o < 4; $o++) {
          $frequency = pow(2,$o);
          $amplitude = pow($persistence, $o);
          $value += improved_noise($i*$frequency, $j*$frequency, 0.5)*$amplitude;

        }
        $this->map[$i][$j] = new Cell($value);

The results are normalized. What would you use have a strong influence in the development of the noise? I see examples where changing the amplitude gives soft or rough surfaces, but even if I give a huge amplitude, I see little difference.


texts:
How can I implement fast lighting with multiple lights?

I don't want to restrain the player, he can place an unlimited number and possibly overlapping (point) lights into the level.

The problem is that shaders which contain dynamic loops which would be necessary to calculate the lighting tend to be very slow.

I had the idea that if it could be possible at compiletime to compile a shader n times where n is the number of lights. If the number n is known at compiletime, the loops can be unrolled automatically. Is this possible to generate n versions of the same shader with just a different number of lights?

At runtime I could then decide which shader to use for which part of the level.


texts:
I'm trying to implement depth-only SSAO and for that, I render a depth map into a texture and pass it to my SSAO shader which then uses it.

The problem is that when I try to output the depth map values from SSAO fragment shader (for testing purpose), I get something really weird.

Here is the result :

And, here is how it normally looks rendered before giving it to the SSAO shader :

The depth buffer seems OK, so I guess it comes from a transformation done in the SSAO shader.

Here are the shaders (I'm using the bgfx library, but the shader language is very similar to GLSL):

Here is the way I output the depth from my SSAO for testing :

//Vertex Shader
$input a_position, a_texcoord0
$output v_texcoord0

#include "../common/common.sh"

void main()
{
    gl_Position = mul(u_modelViewProj, vec4(a_position, 1.0) );
    v_texcoord0 = a_texcoord0;
}

//Fragment Shader
$input v_texcoord0

#include "../common/common.sh"

SAMPLER2D(s_depth, 0);

float readDepth( in vec2 coord )
{
#if BGFX_SHADER_LANGUAGE_HLSL
    float z = texture2D( s_depth, coord );
#else
    float z = texture2D( s_depth, coord ) * 2.0 - 1.0;
#endif // BGFX_SHADER_LANGUAGE_HLSL

    return z;
}

void main()
{
    float depth = readDepth( v_texcoord0 );
    ...
    //Some computation
    ...
    gl_FragColor = vec4(vec3_splat(depth), 1);
}

And here the shader for storing the depth into a texture :

//Vertex Shader
$input a_position
#include "../common/common.sh"

void main()
{
    gl_Position = mul(u_modelViewProj, vec4(a_position, 1.0) );
}

//Fragment Shader

void main()
{
    gl_FragColor = gl_FragCoord.z/gl_FragCoord.w;
}

My guess is that I may be projecting the depth texture in a wrong way.

Thanks in advance for any help.


texts:
I am capturing screenshots at every time step in unity using ScreenCapture.CaptureScreenshot. I am able to get the shots captured and saved in a certain folder but after approximately 50 timesteps the unity crashes and I get an error : Failed to capture the screen shot. Sometimes, unity crashes after 50 time-steps and sometimes after 70 time-steps, so crashing is random.
P.S I am running my unity simulation on the guest VMware virtual machine, I have already looked into the storage and it is more than needed.


texts: In a shader, why does substituting a variable with the expression producing it cause different behaviour?

texts:
I have this correctly-working OpenGL shader producing Perlin noise:

 float left = lerp(fade(v),  downleft,  topleft);
 float right = lerp(fade(v), downright, topright);
 float result = lerp(fade(u), left, right);

Then I tried plugging the definitions of right and left into result:

float result = lerp(fade(u),
                    lerp(fade(v), downleft,  topleft),
                    lerp(fade(v), downright, topright));

Surprisingly, this behaves completely differently, giving visible edges in my Perlin noise. Below are both results:

My whole 30-line shader is here.

What is the difference between those?


texts:
I programmatically create a Mesh and want to generate a texture that patches coloured squares together so that the patchwork perfectly matches the vertices.
The mesh's dimensions are expressed in floats, the texture dimensions are expressed in pixels.

myMeshFilter.mesh = BuildMesh();
// todo: how to find out the values instead of ??
myMeshRenderer.sharedMaterials[0].mainTexture = BuildTexture(??, ??);

private Texture BuildTexture(int width, int height){
    var texture = new Texture2D(width, height);
    var pixels = textures[TileType.Grass.Value]; //array of 64*64 pixels
    var tileWidth = width/NumberOfColumns;
    var tileHeight = height/NumberOfRows;

    //todo: do this for all the tiles instead of only the first;
    texture.SetPixels(0,0, tileWidth , tileHeight, pixels);
}

In the editor, you can set the pixel-to-unit ratio, but not sure how to set this on generated textures.

My current implementation assumed that setting and using my source texture's pixel to unit ratio in my calculations would do the trick, but I noticed that it doesn't and
I Googled far and wide and have mostly become more confused with every hit.

I think I need the camera to translate my mesh's corner values to pixels, but not sure and wouldn't know how.

UPDATE
Pointing the UV's of the mesh to the correct points in the texture would be a solution (and probably a rather performant one), but would restrict me in my possibilities if I want the tiles to have visual-only 'overflows'.
eg: grass tile next to dirt tile would have a bit of grass over the dirt.


texts: UML Class Diagrams for 2D platformer Games?

texts: I have to develop a small arcade game in C++ for a college assignment using a 2D Game Engine my teacher coded. What would be the best way to make a UML class diagram for it? It's very basic stuff but I feel like I don't have the experience to make proper decisions on how to organize the classes. Seeing some examples of Class Diagrams from like Super Mario or any platformer would be perfect. For example would it be better to make a "Level" class where I load the bitmaps and handle the collisions, and then call this one in the main class, or just load my level stuff directly from my main class? Thanks in advance!


texts:
I'm a beginner in unity so I got this problem.
Here is the script:

using UnityEngine;
using System.Collections;
public class Playercontrol: MonoBehaviour {
    public float maxspeed = 10f;
    bool facingRight = true;

    void FixedUpdate () {
        float move = Input.GetAxis ("Horizontal");

        GetComponent<Rigidbody2D>().velocity
             = new Vector2(move * maxspeed, GetComponent<Rigidbody2D>().velocity.y);

        if (move > 0 && !facingRight){
            Flip ();
        } else if (move < 0 && facingRight) {
            Flip ();
        }
    }

    void Flip() {
        facingRight = !facingRight;
        Vector3 theScale = transform.localScale;
        theScale.x *= -1;
        transform.localScale = theScale;
    }
}

I don't know why but it keep saying that
Can't add script component 'Player control' because the script class cannot be found.Make sure that there no compile errors and that the file name and class name match.


texts: How do I make a Transform object follow it's parents rotation

texts:
So basically i have a transform object parented to a gun.  I use this transform to determine the position my bullets are spawned in, and their rotation.  The position part of it works fine, but the transform object doesn't follow the guns rotation. :(  I tried adding this line of code to the gun script.

(bulletPoint is a variable that references the transform object.)

bulletPoint.rotation = this.transform.rotation;

but it didn't do anything.

How do i get the transform object to follow the guns rotation? (either in code or the editor)

Thanks in advance.  :)

Edit: This is the code I have written for the gun.

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

public class rifle : MonoBehaviour
{

private int bulletSpeed = 5;
[SerializeField] Transform bulletPoint;
[SerializeField] GameObject bullet;

// Start is called before the first frame update
void Start()
{

}

// Update is called once per frame
void Update()
{
    bulletPoint.rotation = this.transform.rotation;
    if (Input.GetMouseButtonDown(0))
    {
        GameObject bulletInstance = Instantiate(bullet, bulletPoint.position, bulletPoint.rotation) as GameObject;
        bulletInstance.GetComponent<Rigidbody>().velocity = new Vector3(0, 0, bulletSpeed);
    }
}
}


texts: Bullet Physics Applying Torques Effects not noticeable

texts:
I am applying torques to a rag doll in order to make it move/walk.

For some reason, I am unable to view any effects when I use a call to rigidbody to apply torques even though these torques are pretty large i.e in the hundreds of Nm.

When I start the simulation, the doll just falls and the torques don't seem to have any effect. When I apply torque impulses however, there is a huge effect and the rag doll blows up because the angular velocity component becomes large that my velocity damping factor multiplies it and the torque impulse becomes huge.

I seem to notice effects of the torque though when I pause the simulation and then resume it after some time.

Am I missing something when I am trying to applying torques?
I know that when applying torque, it accumulates the torque value rather than updating the angular velocity directly.

I'm applying torques at every internal tick callback.

I'd be happy to supply necessary code.

Thank you all.


texts: How to publish a Unity desktop game without a security warning?

texts:
When I build a Unity game as a Windows Desktop application, zip the folder, and upload the zip to itch.io, then anyone downloading the zip from itch.io and running the game gets a security warning from Windows.
Is there a way to build the game in a way that will not show this warning?


texts: How to load chunks of 2d map segments when player reaches a certain point?

texts:
In my 2d platformer (made with Java and Slick2d), random maps are made by combining different segments together and displaying them one after the other. My problem is that I can't load too many segments or the game will run out of memory, so I want to load n number of segments at a time in chunks, then load the next chunk when the player comes near the end of one.

I've attempted to do this for a couple of hours now, but I just can't get it to work at all.

This is my chunk generation function where chunkLoad is the number of segments to load and BLOCK_WIDTH is the number of blocks/tiles each segment is across. Chunk1 and map are arrays of segments.

Random r    = new Random();
for(int i=0; i<chunkLoad; i++) {
    int id  = r.nextInt(4)+2;
    chunk1[i]   = new BlockMap("res/window/map"+id+".tmx", i*BLOCK_WIDTH);
}
map = chunk1;
chunksLoaded++;

The map is then drawn on the screen like this. tmap is a TiledMap object and each block/tile is 16 pixels wide

for(int i=0; i<chunkLoad; i++) {
    map[i].tmap.render((i * BLOCK_WIDTH * 16) + (cameraX), 0);
}

I can successfully load new chunks, but I can't display them in the correct position, nor the hitboxes.

Any suggestions? Thanks.


texts:
I'm trying to switch the tag on my Player to something else when a collision between two unrelated objects happens, and then switch the tag of another object to Player, so my camera script will follow it.

How do I detect a collision between two objects that do not have my script attached to them?

void OnCollisionEnter(Collision col) only detects collision on the object that the script is assigned to, so I can't use that. Either I need to know how to detect a unrelated collision in a script, or I need to know how to change the tag of an object that does not contain the script.

This script is on my player, whom does not collide with anything:

void OnCollisionEnter (Collision col)
{
    if (col.gameObject.name == "triggerCube")
    {
        Debug.Log ("HIT");
    }
    else
    {
        Debug.Log ("HIT2");
    }
}

The `Debug.Log("HIT") does not show when the objects collide. This script is on the object "triggerCube":

using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using UnityEngine.SceneManagement;

public class EndPoint : MonoBehaviour
{
    public Text textWin;

    private Vector3 offset;

    void OnCollisionEnter (Collision col)
    {
        if (col.gameObject.name == "triggerCube")
        {
            Debug.Log ("HIT SOMETHING");
            setWinText ();
        }
    }

    void setWinText ()
    {
        textWin.text = "LMAO";
    }
}


texts: 3D collision detection on non flat surface

texts:
I am developing a game which needs an accurate collision detection algorithm, when an object travels down a slope which isn't flat.  To be more precise I need to simulate a skier who travels down a ramp.

My first idea was to create simple bounding box around the skies and the ramp. Then place the skier in mid air and start calculating gravity. When the two bounding boxes intersect => collision detected (this is how I did it in 2D). But the problem is that the skies are flat and the slope isn't. So there is a chance that the ski will stick into the jump (due to curved surface of the jump) or even worse the skier  will go under the jump (I don't want the skies to "sink" into the jump as well) .

What would be the best way of solving this?
What I could think of is:

when collision is detected, rotate the skies until the front and the back end of the skies are colliding with the surface.

Is this idea any good? Did any face this kind of problem? Would be better to morph the skies according to the slope (but this would probably be an overhead I can't afford)?

P.S. if I didn't explain enough, write a comment and make a sketch.


texts:
so I have been working on implementing a form of HPA* but i'm really struggling to decide what to do next.

https://webdocs.cs.ualberta.ca/~mmueller/ps/hpastar.pdf <- here is the article.

There is pseudo-code but the notation is very hard for me to understand, but I struggle to read due to learning difficulties (visual snow / ADD) and I find the paper very difficult to understand, so I appreciate anyone willing to explain/ break it down to me in simpler language.

I have implemented my grid and seperated it into squares.
Example diagram - here is my guess, I haven't implemented exits and entrances yet, green terrain is normal, white terrain are roads which travellers will travel across quicker, brown is mountains inpassable unless meets a special condition, and there are boats but they will use a different algorithm, since im only implementing HPA* for ground units in the game ,and JPS for sea units as the sea grid is uniform without costs.

Lets say for sake of argument each pixel on that image is its own individual grid space.

Question 1. Do I have to resize the squares if water/mountains is involved- lets assume the water/mountains is a wall for the sake of the argument. (If so whats a good method?)

Question 2. Is there a general algorithm that can be used, I know the A* algorithm, but how do entrances and exits link to eachother ? (thinking quad tree)

Question 3. How do I reconstruct the squares dynamically if the map could change or be dynamic.

Question 4. how does one traverse across the map from higher representation to lower representation.

Assumptions, I'm assuming first we path-find across the squares as a whole, then work out individually the route inside it from one end to another yes?

Also if you know the location of a good HPA* library that would be also be nice.


texts:
I have a camera player in a scene. Scene contains a fixed north which i want to indicate on my compass with needle but how can i do it?
 I tried this code using a tut so far but its north is not right

   public void ChangeNortDirection() {

        northDirection.z = player.eulerAngles.y + 10;
        northLayer.localEulerAngles = northDirection;

    }


texts: Unity 2109.3.4 apk fails to install on to quest

texts:
Hello's I was able to successfully sideload APK's on to the quest for a while now however when I updated to unity 2019.3.4 side quest is now unable to successfully load a built APK onto the oculus quest.
Here is the error I receive,  INSTALL_FAILED_NO_MATCHING_ABIS: Failed to extract native libraries, res=-113
I have tried numerous things and am a bit stuck. Any help is appreciated
List of attempts :
Tried with SDK included in unity
Tried custom android studio location
Tried switching from MONO backend and enabling Arm 64
Tried lowering min to the lowest API level
Tried updating all SDK tools in android studio
Tried custom ndk, unable to get one unity is happy with
Tried clearing cache and uninstalling prev install


texts: Find out triangles that are not occluded from a camera view?

texts: For a project i need to find out triangles that are directly seen by the camera / user. Triangles that are occluded by other triangles should be ignored. There may be 200 thousand triangles in a model, so raycasting on a CPU is no possibility due to performance. Is there something build in to unity or opengl that can do this? If not how would you approach this problem? Many 3d editing software use techniques, e. g. to select or slice only triangles that are visible.


texts: Unity AdMob plugin - rewarding the user on the main thread

texts:
There's a simple guide on the Firebase's website on how to implement the AdMob's rewarded video:
https://firebase.google.com/docs/admob/unity/rewarded-video

Let's take some code:

public void OnVideoAdComplete(object sender, Reward reward){
    SoundMgr.Instance().PlayRewardSound();
    // double coins etc
}

Let's plug it in:

private void LoadVideoAd(){
    videoAd = RewardBasedVideoAd.Instance;

    AdRequest request = new AdRequest.Builder().AddTestDevice("XXXXXXXXXXXXX").Build();
    videoAd.LoadAd(request, androidVideoAdID);

    if(!videoCallbackSet){
        videoCallbackSet = true;
        videoAd.OnAdRewarded += OnVideoAdComplete;
    }
}

And now let's get a ThreadException cause we played a sound on the other thread:

Unity   : Function SoundChannelStopList::~SoundChannelStopList() may only be called from main thread!

Unity   : ExecutionEngineException: SIGILL
Unity   :   at SoundManager.PlaySuccess1Sound () [0x00000] in <filename unknown>:0
Unity   :   at Game.OnVideoAdClose () [0x00000] in <filename unknown>:0
Unity   :   at AdManager.OnVideoAdClose (System.Object sender, System.EventArgs args) [0x00000] in <filename unknown>:0
Unity   :   at GoogleMobileAds.Api.RewardBasedVideoAd.<RewardBasedVideoAd>m__4 (System.Object sender, System.EventArgs args) [0x00000] in <filename unknown>:0
Unity   :   at (wrapper delegate-invoke)
System.EventHandler`1<System.EventArgs>:invoke_void__this___object_EventArgs (object,System.EventArgs)
Unity   :   at GoogleMobileAds.Android.RewardBasedVideoAdClient.onAdClosed () [0x00000] in <filename unknown>:0
Unity   :   at System.Reflection.MonoMethod.Invoke (System.Object obj, BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x00000] in <filename unknown>:0
Unity   : Rethrow as TargetInvocationException: GoogleMobileAds.Android.RewardBasedVideoAdClient.onAdClosed()
Unity   :   at UnityEngine.AndroidJavaPro

How is this possible that it's year 2017 and the most leading game engine's plugin is runnning it's callbacks without some sort of App.PostRunnableOnMainThread()?

Is there any workaround on this or we need to create an incredible pattern like:

update(){
    if(adFinished)
        //give rewards
    }

I'd be grateful for any tips! :)


texts: What is the code for panning a camera from touch input? (libGDX + scene2d)

texts:
I would like the user to pan around a game world by dragging their finger on a touch screen - just like Google Maps. I tried a few things but I'm not having much success thus far.

Here is where I'm up to.

public class Game extends ApplicationAdapter {
    Stage stage;

    @Override
    public void create () {

        stage = new Stage(new ScreenViewport());
        Gdx.input.setInputProcessor(stage);

        // Create world
        Planet planet = new Planet();
        stage.addActor(planet);

        stage.addListener(new ActorGestureListener() {

            public void pan(InputEvent event, float x, float y, float deltaX, float deltaY) {
                ((OrthographicCamera)stage.getCamera()).translate(deltaX, deltaY);
                stage.getCamera().update();
            }
        });

    }

    @Override
    public void render () {
        Gdx.gl.glClearColor(0, 0, 0, 1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

        stage.act(Gdx.graphics.getDeltaTime());
        stage.draw();
    }

}