texts: Parts of OpenGL rendering area missing/transparent until resize

texts:
I am having a weird transparency issue when running my game in windowed mode. Parts of the window, left and top parts in normal window mode, right and bottom when in maximised window, become transparent. It is full transparency not just an uncleared buffer as I can see movement from other windows behind. The size of the area that is transparent varies slightly between runs. I'm pretty sure it worked in January when I last worked on the game.

If I resize or iconify/restore the window either manually or programmatically with GLFW it fixes itself and renders the full window as expected.
glfwGetFramebufferSize, glfwGetWindowSize and glGetIntegerv(GL11.GL_VIEWPORT) all report the same correct values before and after a resize. Calling glViewport does not fix the issue. I am not getting any relevant openGL errors.
If I start the game window maximised on the displays connected to the old graphics card R9 290X I do not get this problem but window maximised on newer RX 5700 XT display still has the problem but in bottom right instead of top left. Full screen works fine on all displays.
Have not seen any problems with other games I have but I always run them in fullscreen and they are mostly DirectX or Vulcan.
Has anyone encountered this problem before? I would rather not have to programmatically modify the window size by 1 pixel each start as that is an ugly fix.
If anyone wants to test on their system to see if it is a code or driver error run either the full packaged jar (in sandbox preferably) or checkout minimal error example yourself and execute "./gradlew run".

Windows 7
GDX 1.9.11 (also tried 1.9.10)
LWJGL 3.2.3 (also tried 3.2.2)
Java AdoptOpenJDK 12.0.2
AMD driver 20.7.2


texts: What exactly does Unreal Engine 4's Class Wizard do?

texts: I know "it adds classes to your project" and "creates boiler plate code for you" but what does that actually mean? Does it do anything besides properly generate your .h and .cpp files for you?


texts:
I've been looking closely at how Animal Crossing (for GameCube) creates town maps, and as far as I can tell, it's something like this:

The town is made up of a 5x6 grid of acres. Each acre is 16x16 "tiles" in size.

That's the easier part. As for the actual map generation, it seems to use what I'll call "acre templates." That is, the acres seem to be selected somewhat randomly from a predefined list, with predefined layouts. So there are, for example 2 different layouts of what an acre containing the Museum will look like.

Or if an acre has a river running through it, top-to-bottom, there might be 3-4 different templates of how the river flows through that acre, with optional ponds nearby, etc.

The question is... What is a good suggestion or method for how to organize the data structure to handle all of this?

Another thing to keep in mind is that there's a "second layer" of objects on top of the basic terrain info, such as trees or rocks or inventory objects dropped/buried on/in the ground. How would I store that information in relation to the acre templates?


texts: Creating 2D billiard game with realistic movement

texts:
I'm new to XNA and game programming.

I'm creating a 2D billiard game and I want to add balls with realistic movement (like 3D). Is it possible to achieve this without using 3D models? I only want to use 2D. Please give me examples.


texts: Possible to pass pygame data to memory map block?

texts:
I am building a matrix out of addressable pixels and it will be run by a Pi (over the ethernet bus).  The matrix will be 75 pixels wide and 20 pixels tall.  As a side project, I thought it would be neat to run pong on it. I've seen some python based pong tutorials for Pi, but the problem is that they want to pass the data out to a screen via pygame.display function.

I have access to pass pixel information using a memory map block, so is there anyway to do that with pygame instead of passing it out the video port?

In case anyone is curious, this was the pong tutorial I was looking at: Pong Tutorial


texts: FPS Character Controller movement - Any value in reverse engineering movement formulas?

texts:
From what I know character movement in popular FPS games tend to be non-linear, but the easing curves change between games as each has its own signature formula.

Typically I imagine the physics engine would provide the feel by adding acceleration, deceleration and attrition.

Most basic games have a simple linear start-stop movement.

Is there any value in reverse engineering the "signature" formulas for these games, or are these openly known and available to everyone?

Also if these are well known where can I read upon the different implementations by these AAA FPS games?


texts: How to create a bounding box around a Sprite in C++?

texts:
Hello everyone, I am trying to create a bounding box around a Sprite in my simple Pong game. The bounding box needs to be a simple rectangle around the sprite so that it can act as a collision detector between the ball and paddle.

I have already tried to create the bounding box but it's not quite working as expected.

    float current_x = paddle_right->xPos();
    float current_y = paddle_right->yPos();
    float current_x2 = paddle_left->xPos();
    float current_y2 = paddle_left->yPos();

    float width_x = current_x + 16;
    float width_y = current_y + 150;
    float width_x2 = current_x2 + 16;
    float width_y2 = current_y2 + 150;

    if((x_pos > current_x && x_pos < width_x && y_pos > current_y && y_pos < width_y)||
        (x_pos > current_x2 && x_pos < width_x2 && y_pos > current_y2 && y_pos < width_y2))
    {
        dir_vector.setX(dir_vector.getX() * -1);
    }

The above code is the code I have used to create said bounding box, but like I said, it's simply not working correctly (As in the ball will sometimes go through the Sprite or have an abnormal reaction to it such as bouncing the wrong way).

I hope I have explained this well, if not please ask me which part to explain again. Basically, I just want do create a bounding box around a Sprite (in this case, the Paddle) to which then the ball can collide from.

For reference I am using the AwesomeSauce Game Engine.


texts: How can I launch the Unity Editor and open a specific project from C# code?

texts:
I created a very simple console application:

namespace ConsoleApplication4
{
    class Program
    {
        static void Main(string[] args)
        {
            // The project I want to open
            var arg = @"""-projectPath C:\Users\Administrator\Downloads\New Unity Project""";

            // Start Unity and open the project
            Process.Start(@"C:\Program Files\Unity\Editor\Unity.exe", arg);
        }
    }
}

But only the Unity Editor is launched; the specified project is not opened.

What do I need to modify to launch the project?


texts: Component systems: No inheritance hierarchy at all, or a basic one?

texts:
(I asked a similar question, but it had more questions inside it and I feel it wasn't clear enough, so I'm opening a new one).

Until recently I implemented all my games using an inheritance hierarchy. Those were simple games.

For example:

          Entity
          /    \
      Movable  Static
      /  \        /  \
    Orc  Mage   Tree  Wall

This worked for simple games.

However recently I read about 'entity component systems'. Using this approach, a class doesn't inherit from another class in order to receive functionality. Instead it is composed with it, which allows for more flexible designs.

My question is this:

I know that each component is a class (derived from a common base class).

However, there is one thing I don't understand: In the 'component system' approach, is there one class that all entities are instances of - and the only difference between entities is the components they contain?

For example: There is a class Entity. All entities in the game are instances of this class.

The only differences between them is that they are composed with different Component objects.

For example:

Component aiComponent = new AIComponent();
Component movementComponent = new MovementComponent();
Component physicsComponent = new PhysicsComponent();
Component rangedAttackComponent = new RangedAttackComponent();

Entity orc = new Entity();
orc.addComponent(aiComponent);
orc.addComponent(movementComponent);
orc.addComponent(physicsComponent);

Entity shootingCastle = new Entity();
orc.addComponent(aiComponent);
orc.addComponent(rangedAttackComponent);
orc.addComponent(physicsComponent);

As you can see, both orc and shootingCastle are instances of the Entity class. But they are composed with different components.

Is this how 'entity component systems' are supposed to be? No inheritance hierarchy at all? Or is there still a basic inheritance hierarchy, but most of the logic is inside components?


texts: Blocks / tiles aren't responding to clicks

texts:
I've recently finished a tutorial, UE4 Slide Puzzle by Nicholas Thompson. Halfway through the second tutorial, I found out that the blocks / tiles wouldn't respond to my clicks. For example, when I clicked on a tile, it wouldn't print out a Hello message.
I have watched the tutorial so many times already, I've searched it up, looked at my code thoroughly, and I can't find any problems. Here are my blueprints:

Event Graph
Get Move To (Function)

After some debugging, I found out that the problem occured at the start of the function, Mesh Clicked in the Event Graph.
Please help, it would be greatly appreciated. Thank you!


texts:
First time trying Unity and I'm having trouble with importing assets.

border_horizontal.png is fine, but I can't drag border_vertical.png onto my scene. It also doesn't have an arrow next to it in the asset menu. What is going on here?


texts: How do I save variables and load them in Unity with JavaScript?

texts: I made a game and i want to save the high score and load it back. I need to save 3 variables and load them when the game starts. How do i do it?


texts: ScreenToWorldPoint returning wrong position even when given Z plane

texts:
I have a NavMeshAgent placed on a character model. When I log agent.transform.position I get (4.5, 0.1, 4.5) which is correct (this is a 2.5d game and movement happens along the x and z axes).

I am trying to set up a script so that when I click a location on the screen, the character will turn to face that location.

The problem I'm facing is that the coordinates returned by Camera.ScreenToWorldPoint are not correct:

Vector3 mousePos = Input.mousePosition;
mousePos.z = Camera.main.nearClipPlane;
Vector3 targetPos = Camera.main.ScreenToWorldPoint(mousePos);

Debug.Log(agent.transform.position)
// Logs: (4.5, 0.1, 4.5)

Debug.Log(targetPos)
// Logs: (0.1, 16.7, 0.7)

In this example, I'm clicking on the same place as the agent but the targetPos is not nearly the same.

The y-axis  of targetPos is static (the same no matter where I click), which seems correct. However the values for x and z are not correct. How do I get the correct coordinates for a click?

edit I have this workaround, but I want to know how to solve the original question still:

RaycastHit hit;
if (Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out hit, 100, rotateTargets))
{
    Vector3 targetPos = hit.point;
    targetPos.y = agent.transform.position.y;
    Vector3 direction = (targetPos - agent.transform.position).normalized;
    Quaternion rotation = Quaternion.LookRotation(direction);
    agent.transform.rotation = rotation;
    agent.updateRotation = false;
    return true;
}


texts: Monogame Effect World Translation Z and alpha in objects not visible behind

texts:
I have an effect in each triangle and rectangle:

In the triangle class I have:

Effect.World = worldScaling * worldRotation * worldTranslation;
Effect.Alpha = Opacity;

triangle = new[]
{
    new VertexPositionColor(new Vector3(X0, Y0, 0), EFill),
    new VertexPositionColor(new Vector3(X2, Y2, 0), EFill),
    new VertexPositionColor(new Vector3(X1, Y1, 0), EFill),
};

where EFill is a solid Color.

In the Rectangle class the equivalent.

Now I set the example to the following:

background = new Quad(new Vector2(0, 0), new Vector2(1000, 1000), "Red", "White", 0, camera);
background.Opacity = 0.2f;
WindowPanel.Children.Add(background);

triangle = new Triangle(0, -50 + 90, 20, 0 + 90, -20, 0 + 90, "Black", "Red", 1);
triangle.Translation.X = 160;
triangle.Translation.Y = 160;
triangle.Translation.Z = -10;
triangle.Opacity = 0.5f;
WindowPanel.Children.Add(triangle0);

But I do not see the triangle when it is behind the rectangle. (If I exchange the Z to the rectangle, the triangle is like the image)

I am new in the '3D' Monogame environment and I read a lot of documentation that could be outdated about AlphaBlend, Depth, etc. and I do not know what exactly applies and what do not.

So the triangle and the rectangle have alpha but are like independent of each  other when rendered.

Any idea how to solve this?


texts: Scale my pixel art files when designing them or when rendering?

texts:
If I create pixel art files that need to be scaled up on the screen later, so that a single pixel becomes a box of 4 pixels. Should I create my pixel art with 2x2 pixels or should I create it with 1x1 pixels so that I can I 1:2 scale it later in XNA to 2x2 pixels?

I tend to believe that 1:1 would result in too much detail rather than the pixel art effect, thus I want the end result in 2:1 style where a 1x1 pixel of my intended sprite will take 2x2 pixels on the screen.


texts:
In game design how should keyboard input be handled and why?
Do i
A: check the state of keys in the main loop each iteration?
B: Read key down and key up events from the event queue.

Im using allegro 5 and using the event queue model atm, but ive seen the other method in some samples..


texts: how to save Audio Volume to playerprefs to mute all scenes sounds

texts:
Please Explain me how to Save or Set Audiolistner or scene Audio to playerprefs to control game all scene sound by a simple Button On and Off ..

Please Give Me C sharp Script as a Example To Mute and UnMute Full Game All Scenes Sound from Scene 1.

Thanks ..Waiting


texts: Unity - Check if object is facing Vector3 coordinates

texts:
I am having a hard time figuring this out, I want to have objects that move around randomly, and when they get new coordinates to move towards, face them, and then move.

Here's explained:

Target moves towards point A.
Target reaches point A.
Get new coordinates.
Rotate towards the new coordinates WITHOUT moving
When facing the new target coordinates, start moving

I am trying it with Raycast, but it doesnt work, it tells me it always looks at them...

if (Physics.Raycast(transform.forward, randomTargetCoords, out hit)) {
    Debug.Log("spotted");
}

I want to project the ray from the front of the object to the target coordinates (Vector3), and if true, do any code inside the if method.

How can I do it?

EDIT: Here is the code for moving and rotating the object

transform.position = Vector3.MoveTowards(transform.position, targetCoords, moveSpeed * Time.deltaTime);
transform.rotation = Quaternion.RotateTowards(transform.rotation, targetRotation, rotationSpeed * Time.deltaTime);


texts: What data should I use to track the player position on a world at the same size of the earth in a multiplayer game?

texts:
I guess this kind of game or simulator already exist somewhere, but I'm not sure...

Let's imagine I'm making a game where the proportions of the planet earth and the humans beings on it are the same as in the reality. I can't only use longitude/latitude with float because when being far away from the origin, precision would be lost: when the float exponent gets too high, the digit at the right would be rounded and thus, not considered. Or to say it simpler, float are not precise enough to position an object on earth using longitude/latitude while keeping smooth movements.

Since there is a need to track each player's position in an homogenous way, I'm thinking about dividing the world map into indexed subparts (thus integers), and then precisely position the player using a float or double.

This would look like this:

struct position_on_earth
{
int sector_x, sector_y;
float pos_x; pos_y;
};

Is it potentially faster to use this kind of data instead of using doubles ?


texts: How to achieve lighting like this in Unity for 2D games?

texts:
How could I accomplish a lighting effect something similar to this game?:

I'm not talking about the shadows but about the glowing/lighting effect on the crystals and the torches.

Anyone got any clues?

More images from the games steam page


texts: SDL 1.3 on Windows 7. Better hardware,lower FPS

texts: I've just moved from one PC to another.I've been developing a game in SDL with SDL_image and SDL_ttf for about one year. On my old pc, I had about 90 FPS on my game, but now I have about 30, witch I find very strange. My Question is: Why do my FPS dropped from 90 when I used an inferior PC (on windows xp) to 30 when I have a way better PC (on windows 7).


texts: How to use OpenGL blend mode/functions to brighten/darken a texture.

texts:
Tried this code, but the texture didnot get any lighter.

    try {
        texture = TextureLoader.getTexture("png",
           Game.class.getResourceAsStream("/brick.png"), true, GL_NEAREST);
    } catch (IOException e) {
        e.printStackTrace();
    }

    GL11.glBindTexture(GL11.GL_TEXTURE_2D, texture.getTextureID());

    glEnable(GL_BLEND);
    glBlendFunc(GL_CONSTANT_ALPHA, GL_CONSTANT_ALPHA);
    GL14.glBlendColor(1.0f, 1.0f, 1.0f, 0.5f);

    glColor4f(1, 1, 1, 0.5f);
    GL11.glBegin(GL11.GL_QUADS);          // Start Drawing Quads
    // Front Face
    GL11.glNormal3f(0.0f, 0.0f, 1.0f);    // Normal Pointing Towards Viewer
    GL11.glTexCoord2f(0.0f, 0.0f);
    GL11.glVertex3f(-1.0f, -1.0f, 1.0f);  // Point 1 (Front)
    GL11.glTexCoord2f(1.0f, 0.0f);
    GL11.glVertex3f(1.0f, -1.0f, 1.0f);   // Point 2 (Front)
    GL11.glTexCoord2f(1.0f, 1.0f);
    GL11.glVertex3f(1.0f, 1.0f, 1.0f);    // Point 3 (Front)
    GL11.glTexCoord2f(0.0f, 1.0f);
    GL11.glVertex3f(-1.0f, 1.0f, 1.0f);   // Point 4 (Front)
    glEnd();


texts: Revolve FlxSprites Around a Central FlxSprite in Flash Game made with Flixel

texts:
I have been working on a Flash game made in Flash Builder using the Flixel library. I have been trying to dynamically create a group of FlxSprites , and revolve them around a player controlled class that extends FlxSprite when the player uses a power up.

My thought on how to approach this, was to create a circle, use points on that circle to instantiate the sprites, and then somehow update those sprites to points along that circle during the game's update step. But I am not sure what would be the best way to hold information about a circle, or circular path's in ActionScript 3. I assumed that As3Math  provided some of the means to do this, and I tried to add one sprite to a circle like this:

package
{
    import As3Math.*;
    import As3Math.geo2d.amBoundCircle2d;
    import org.flixel.FlxGroup;
    import org.flixel.FlxState;

    public class ButterflyRing extends FlxGroup
    {
        [Embed(source="../Content/Images/spritesheet_butterfly_32x8.png")] var butterflySprite:Class;
        public function ButterflyRing(playState:FlxState,X:Number,Y:Number)
        {
            //add to super class
            super();

            //create a circle motion path at coordinates x:150, y:150 with a radius of 100
            var butterflyCircle:Math.amBoundCircle2d = new Math.amBoundCircle2d(150,50);

            var circDiameter:Number = butterflyCircle.radius/2;
            var pX:Number = butterflyCircle.center.x + circDiameter
            var pY:Number = butterflyCircle.center.y;

            var butterfly:SpriteButterfly = new SpriteButterfly(pX,pY);
            add(butterfly);

        }

        override public function update():void
        {
            super.update();
        }
    }
}

I realize now this is not the correct way to use As3Math, that it is accessible by default and you call it like Math.pi. My question is, Does ActionsScript 3 have the means to do this in its code base, or do you have to define your own classes to hold information for a circle, or do you use Math.pi to build circles from scratch? What is a good approach for this? Or does Flixel provide something good for this?


texts: How can I create an extending chain like the hookshot in Zelda in Unity?

texts:
In the Zelda games, there is an item called the hookshot. It is a small mechanical apparatus held in one hand that acts similar to, but not the same as the gun. When it is triggered, the hook at the tip of the item springs forward and an extending chain follows behind it. This chain is spawned when the hookshot is triggered and disappears when the hook is retracted. The chain is not visible beforehand, i.e, it is not spooled around any kind of cylinder and unspooled when shot.There are also other games where characters use grappling apparatus that can be made shorter or longer when a character is hanging from a specific point or pivot. Similarly, this grappling tether is created or hidden as needed to support whether the player wants to shorten or lengthen it.

My question is, how could one create an extending chain whose links are only visible when triggered and when retracted disappear from view? This chain does not need to necessarily interact with physics. I've thought of a couple of ways someone could create an effect like this, but I would rather see if there is a better known solution or implementation of this or a similiar effect before I dive in. Potential solutions could include:

A particle effect between the base of the hook and the tip of the gun. This might be far better suited for displaying a non-physical, energy tether, but I am not as familiar with the particle system in Unity and I am curious to see if a chain link could be faked with a particle.
Creating a chain link by link or section by section procedurally based upon the direction the hook was firing in and the distance between the positions of the gun tip and hook base. This seems like a more direct solution, but could have higher processing cost as the links are created on the fly and in rapid succession.
Creating a chain that is hidden when not fired and is made to slowly appear when fired as the hook leaves the hookshot apparatus. This seems like the most likely solution, but I have little to no idea as to how it could be implemented.

I would not be surprised at all if there is a better solution that I didn't mention. I look forward to seeing what people suggest. Thank you.


texts: Animator animation does not show in game after gameobject is disabled and re-enabled

texts: I'm trying to understand why an animator stops working in-game after a gameobject is disabled and then re-enabled. The animator pane shows the animation is still going on, but the character is no longer animated in the game/scene.


texts:
I am finding strange behaviour while rendering TextureRegions in my game, only when pausing it. I am making a game for Android, in Java with LibGdx.

When I comment out the line "drawLevelPaused()" everything seems to work fine, both running and paused. When it's not commented, everything works fine until I pause the screen, then it draws those two rectangles, but maybe ships are not shown, and if I comment out drawShips() and drawTarget() (just trying) maybe one of the planets disappears, or if I change the order, other things disappear and those that disappeared before now are rendered again. I can't find the way to fix this behaviour

I beg your help, and I hope it's my mistake and not a LibGdx issue. I use OpenGL ES 2.0, stated in AndroidManifest.xml, if it is of any help. Thank you in advance.

My Screen render method(game loop) is as follows:

@Override
public void render(float delta)
{
    Gdx.gl.glClearColor(0.1f, 0.1f, 0.1f, 1);
    Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);

    controller.update(delta);
    renderer.render();
}

When world state is PAUSED  controller.update does nothing at all, there is a switch in it. And renderer.render() is as follows:

public void render()
{
    int worldState=this.world.getWorldState();

    updateCamera();
    spriteBatch.begin();
    drawPlanets();
    drawTarget();
    drawShips();

    if(worldState==World.PAUSED)
    {
        drawLevelPaused();
    }
    else if(worldState==World.LEVEL_WON)
    {
        drawLevelWin();
    }
    spriteBatch.end();
}

And those methods are:

private void updateCamera()
{
    this.offset=world.getCameraOffset();
}

private void drawPlanets()
{
    for(Planet planet : this.world.getPlanets())
    {
        this.spriteBatch.draw(this.textures.getTexture(planet.getTexture()), (planet.getPosition().x - this.offset[0]) * ppuX, (planet.getPosition().y - this.offset[1]) * ppuY);
    }
}

private void drawTarget()
{
    Target target=this.world.getTarget();
    this.spriteBatch.draw(this.textures.getTexture(target.getTexture()), (target.getPosition().x - this.offset[0]) * ppuX, (target.getPosition().y - this.offset[1]) * ppuY);
}

private void drawShips()
{
    for(Ship ship : this.world.getShips())
    {
        this.spriteBatch.draw(this.textures.getTexture(ship.getTexture()), (ship.getPosition().x - this.offset[0]) * ppuX, (ship.getPosition().y - this.offset[1]) * ppuY, ship.getBounds().width*ppuX/2, ship.getBounds().height*ppuY/2, ship.getBounds().width*ppuX, ship.getBounds().height*ppuY, 1.0f, 1.0f, ship.getAngle()-90.0f);
    }

    if(this.world.getStillShipVisibility())
    {
        Ship ship=this.world.getStillShip();
        Arrow arrow=this.world.getArrow();
        this.spriteBatch.draw(this.textures.getTexture(ship.getTexture()), (ship.getPosition().x - this.offset[0]) * ppuX, (ship.getPosition().y - this.offset[1]) * ppuY, ship.getBounds().width*ppuX/2, ship.getBounds().height*ppuY/2, ship.getBounds().width*ppuX, ship.getBounds().height*ppuY, 1f, 1f, ship.getAngle() - 90f);
        this.spriteBatch.draw(this.textures.getTexture(arrow.getTexture()), (ship.getCenter().x - this.offset[0] - arrow.getBounds().width/2) * ppuX, (ship.getCenter().y - this.offset[1]) * ppuY, arrow.getBounds().width*ppuX/2, 0, arrow.getBounds().width*ppuX, arrow.getBounds().height*ppuY, 1f, arrow.getRate(), ship.getAngle() - 90f);

    }
}

private void drawLevelPaused()
{
    this.shapeRenderer.begin(ShapeType.FilledRectangle);
    this.shapeRenderer.setColor(0f, 0f, 0f, 0.8f);

    this.shapeRenderer.filledRect(0, 0, this.width/this.ppuX, PAUSE_MARGIN_HEIGHT/this.ppuY);
    this.shapeRenderer.filledRect(0, (this.height-PAUSE_MARGIN_HEIGHT)/this.ppuY, this.width/this.ppuX, PAUSE_MARGIN_HEIGHT/this.ppuY);

    this.shapeRenderer.end();

    for(Button button : this.world.getPauseButtons())
    {
        this.spriteBatch.draw(this.textures.getTexture(button.getTexture()), (button.getPosition().x - this.offset[0]) * this.ppuX, (button.getPosition().y - this.offset[1]) * this.ppuY);
    }

}


texts: How to implement a physical with perspective effect on Android?

texts:
I'm working on a project that looks like PaperToss. Instead of tossing a page, you toss a coin. Suppose that I have a coin put in three-dimensional that have coordinates at A(x,y,z). I throw that point ahead, after 1/100 second, that coin move from A(x,y,z) to A'(x',y',z'). By this way, I  have two problems need to solve.

Where will be the coin at time t?
How can I display this on a screen?

For 2., I thought about using Orthographic projection & Perspective projection. I'm told that OpenGL can help me, but I don't know how.

How can I solve 1. and 2.?


texts: How can I add an impulse to specific rigid bodies at rest?

texts:
Scenario

Rocks falling down a rocky slope, with a flat surface at the bottom.
When they land on the surface, the rocks move slightly before coming to a rest.

GLESDebugDraw shows the bright orange outline turning to a slightly darker orange once a rock comes to a rest, until the rock is agitated by another falling rock.

Question: I would like to add an impulse to the rock once it reaches the rest state. How would I implement that?


texts: Help with NPC following the player in a sidescroller

texts:
I'm a beginner with C# and am having a bit of trouble coding an NPC that follows the player in a 2D sidescroller. The player has two speeds, a walk and a sprint. I have a very basic companion follow script but it's only set on one speed, and if I increase the speed so that the NPC will keep up when the player sprints, the NPC jitters when it follows the walking player, which makes sense. I'm just wondering if there's a way in which the NPC can dynamically follow the player in the exact same speed as the player so that this issue doesn't arise. I figure this would inquire an entirely new script, but that's fine. Again, I'm still new to all this, so any help would be greatly appreciated! Thanks!

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CompanionFollow : MonoBehaviour
{
public float speed;
public float stoppingDistance;

private Transform target;

// Start is called before the first frame update
void Start()
{
    target = GameObject.FindGameObjectWithTag("Player").GetComponent<Transform>();
}

// Update is called once per frame
void Update()
{
    if(Vector2.Distance(transform.position, target.position) > stoppingDistance)
    {
        transform.position = Vector2.MoveTowards(transform.position, target.position, speed * Time.deltaTime);
    }
}

}


texts: Unity: Is it possible to copy a rig from one model to another

texts: Lets say I have a model with a ready humanoid rig and a humanoid model with no rig. Can I somehow copy the bones from the rig to the model with no rig in unity?


texts: File format for static and animated 3D models

texts:
I'm currently writing a 3D game in C++ with OpenGL and I'm coming to the part where to load 3D models in. Therefore I'm looking for popular file formats and techniques to

display static meshs and
render animated meshs.

I've already found quite a large number of possible formats and techniques, like keyframe animations, skeletal animation, MD2 up to MD5, 3DS, X, Collada etc. pp.

For simplicity I'd like to use a format (and technique) that allows both, namely static and animated meshs. So my question is if one format is suitable for that task and which one you'd suggest. And to clarify a bit: I don't need super-smooth animations or brandnew features.

Sidenote: Because I'm a blender fan (but not an expert ;-)) it'd be helpful if it can be used with that -- but of course that shouldn't be the show stopper, here.


texts:
I want to create a terrain/world map for my 3d game.

I want a huge map. For example, ill make it in Blender or generate from a heightmap. Then I plan to divide it in chunks so I can load/unload and show/hide them when needed in the game.

If I want to remake the map, then I will have to divide it in chunks again, and again spend time on placing world objects on the terrain. I'm not sure that is the best way.

What approach is optimal here?


texts: Locking on to enemy, player can only move towards enemy, not away?

texts:
I'm working on a lock on function and so far I can lock on to the nearest enemy, but my player can't move around the enemy, i can only move towards it. I have my project setup so that the camera is always at a fixed position/rotation, and the player moves independently of the camera.

Here's my move function:

public void Move(float h, float v) {
    if (!lockPlayerMovement) {
        Speed = 0;
        MoveDirection.y -= Gravity * Time.deltaTime;
        if (Mathf.Abs(v) > ThumbStickDeadZone || (Mathf.Abs(h) > ThumbStickDeadZone)) {
            var lookRotation = new Vector3();
            lookRotation.Set(h, 0, v);
            lookRotation = lookRotation.normalized;

            var rotation = Quaternion.LookRotation(lookRotation, Vector3.up);
            if (lookRotation.magnitude > ThumbStickDeadZone) {
                Speed = RunSpeed;
                transform.rotation = Quaternion.Slerp(Transform.rotation, rotation, Time.deltaTime * TurnSpeed);
            }
        }
        if (Controller.isGrounded) {
            MoveDirection = Transform.TransformDirection(Vector3.forward).normalized;
            MoveDirection *= Speed * Time.deltaTime;
            //if (Input.GetButton("Fire1"))
            //      MovementProperties.MoveDirection.y = JumpSpeed;
        }
        Controller.Move(MoveDirection);
    }
}

Lock On Function:

void Update () {
    playerPosition = transform;

    if (enemyLockedOn && enemyTarget != null) {
        transform.LookAt(enemyTarget.transform);
    }
}

void ScanForEnemies() {
    int numOfEnemies = 0;

    float distanceFromPlayer;
    GameObject closestEnemy;

    List<GameObject> enemies = new List<GameObject>();

    Collider[] cols = Physics.OverlapSphere(transform.position, radius);

    foreach (Collider col in cols) {
        if (col && col.tag == "Enemy") {
            ++numOfEnemies;
            enemies.Add(col.gameObject);
            //print(Vector3.Distance(playerPosition.position, col.transform.position));
        }
    }

    if (enemies.Count > 0) {
        distanceFromPlayer = Vector3.Distance(playerPosition.position, enemies[0].transform.position);
        closestEnemy = enemies[0];
        for (int i = 0; i < enemies.Count; i++) {
            if (Vector3.Distance(playerPosition.position, enemies[i].transform.position) < distanceFromPlayer) {
                distanceFromPlayer = Vector3.Distance(playerPosition.position, enemies[i].transform.position);
                closestEnemy = enemies[i];
            }
        }

        /* Set closest enemy as the player target and lock player to that enemy (while in range -- or scan pressed again) */
        enemyTarget = closestEnemy;

        if (enemyTarget != null) enemyLockedOn = true;

        print("Closest Enemy : " + closestEnemy + " | Distance From Player : " + distanceFromPlayer);
        print("Number of nearest enemies : " + numOfEnemies);

    }
}


texts: Instantiate objects that share same variable

texts:
I'm just wondering how to instantiate the same objects that all share the same variables, except their positions.

I'm basically working on the scene of my HTML5 game, and I've build a streetlamp post that turns on and off. All the lamps will have the same variables, such as Image, Size, on/off function. The only thing that will be different will be the position x and y.

I've built my lamp within a variable function (I think they're called that var = {), and within my actual game DrawFunction, I'm calling LampPost.draw();.

Is it possible to do something like this?

LampPost(0,0);
LampPost(100, 0);
LampPost(200, 0);

etc ... and then possibly place each instantiate Lamp within an array?

This is a snippet code for the lamp:

var LampPost = {

    lamp_xsprite : 0,
    lamp_ysprite : 0,

    light_xsprite : 0,
    lightysprite : 0,

    x : 440,
    y : 320,

    //Flicker effects
    lightFlicker : 0,
    seconds_Off : 0,
    seconds_On : 0,

    randomLength_Off : 500,
    randomLength_On : 150,

    draw: function(x, y) {

        this.x = x;
        this.y = y;

        ctxPropsOver.setTransform(1, 0, 0, 1, -Map.x + gameWidth/2, -Map.y + gameHeight/2);
        ctxPropsOver.rotate(Math.PI / -25);
        ctxPropsOver.clearRect(0, 0, 1000, 1000);

        ctxPropsOver.globalAlpha = this.lightFlicker;
        ctxPropsOver.drawImage(imgLights, 0, 36, 500, 463, -60 + this.x, -190 + this.y, 500, 463);
        ctxPropsOver.globalAlpha = 1;
        ctxPropsOver.drawImage(imgLights, 0, 0, 210, 36, 0 + this.x, 0 + this.y, 210, 36);

----- UPDATE -----

Okay, So I've converted it into an instance of object, this is what I have so far:

LampPost = function(lx, ly, la){

    x = lx; //500;
    y = ly; //335;

    centrex = 12;
    centrey = 17;

    rotate = la; //-8;

}

LampPost.prototype.draw = function (){

    ctxPropsOver.setTransform(1, 0, 0, 1, (-Map.x + gameWidth/2), (-Map.y + gameHeight/2) );

    ctxPropsOver.clearRect(0, 0, 1000, 1000);

    ctxPropsOver.save();
        ctxPropsOver.translate(this.x, this.y);
        ctxPropsOver.rotate(this.rotate*Math.PI/180);
        ctxPropsOver.translate(-this.centrex, -this.centrey);
        ctxPropsOver.globalAlpha = this.lightFlicker;
        ctxPropsOver.drawImage(imgLights, 0, 36, 500, 463, -60, -190, 500, 463);
        ctxPropsOver.globalAlpha = 1;
        ctxPropsOver.drawImage(imgLights, 0, 0, 210, 36, 0, 0, 210, 36);
    ctxPropsOver.restore();
};


texts: with XNA 4.0, How can I combine 2 models to make one?

texts:
I want to animate Model1 (an aicraft) and I want an object, Model2 (a sphere), to follow it in translation and rotation, as it is a part of this aircraft.

With the following code (I use one or two tutorials to write it) everything seems good when you just change just one angle at the time. The sphere gently follows the aircraft, but if you change more than one angle at the same time, everything goes wrong.

I wonder if it's not a gimbal lock problem? But I use quaternions? Or maybe I haven't understood all this stuff?

My code is below:

protected override void Update(GameTime gameTime)
    {
        // Allows the game to exit
        if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
            this.Exit();

    // Command input to airplane
        float yokeUpDown = 0.0f;
        float yokeRightLeft = 0.0f;
        float RollRotation = 0.01f;

      //make quaternion rotation matrix of airplane
        Quaternion additionalAircraftRotation = Quaternion.CreateFromAxisAngle(new Vector3(0, 0, 1), yokeUpDown) * Quaternion.CreateFromAxisAngle(new Vector3(0, 1, 0), yokeRightLeft) *Quaternion.CreateFromAxisAngle(new Vector3(1, 0, 0), RollRotation);

    //increase or decrease aircraft rotation
        spacecraftRotation = spacecraftRotation * additionalAircraftRotation;

    // make vector3 sphere angle rotation
        sphereAngle.X = sphereAngle.X + yokeUpDown;
        sphereAngle.Y = sphereAngle.Y + yokeRightLeft;
        sphereAngle.Z = sphereAngle.Z + RollRotation;

    // make rotation quaternion for sphere
        Quaternion additionalSphereRotation = Quaternion.CreateFromAxisAngle(new Vector3(0, 0, 1), sphereAngle.X) * Quaternion.CreateFromAxisAngle(new Vector3(0, 1, 0), sphereAngle.Y) * Quaternion.CreateFromAxisAngle(new Vector3(1,0, 0), sphereAngle.Z);

    //relative position of the sphere to the aircraft
        Vector3 translationSphere = new Vector3(-distance_Aircraft_Sphere, 0,0);

        translationSphere = Vector3.Transform(translationSphere, additionalSphereRotation);

        sphereposition = aircraftposition + translationSphere;

        // “VectorToAdd” = direction of the airplane
        Vector3 rotatedAircraftVector = Vector3.Transform(vectorToAdd, spacecraftRotation);

        aircraftposition += moveSpeedAircraft * rotatedAircraftVector;

        sphereposition += moveSpeedAircraft * rotatedAircraftVector;

}
enter code here


texts:
I'm working on a Worms-styled game and want to generate some terrain procedurally. I've previously done a lot of terrain generation using perlin noise, and this is what I started out using for this game. The only problem with it is that it's too simple and boring, giving me some hills but not the complexity I want. I'd like to have features like caves and hanging mountains and I don't mind floating islands and such. Something like this, but even crazier would be ok:

I thought of first generating the terrain using classic perlin noise, then just removing parts to create caves and what not, but I'm having trouble guiding the removal of those parts. Are there any alternatives to generating such a terrain?


texts: How to detect when client state drifts from server state?

texts:
I'm obviously talking about an authoritative server to which client sends commands and gets state updates.

My question is when I get a position update and know how many milliseconds ago it was generated on the server how do I detect and fix the drift?

I'm currently just blocking the client from going too far away from the last update position by smoothly moving him towards that position. Which works fine on connections with low ping, but wont work with 200+ ping.


texts: Creating an in-game time system only works with real time

texts:
I'm trying to create an in-game time system. Thus far it only works properly if you use 1440 minutes to the day (realtime), but I would like to be able to alter the day length to something like 10 minutes for example.

When adjusting it to 10, 20, etc, the clock starts to increment extremely rapidly to the point that an entire week passes in less than a second if you set it to one minute, or a day passes in about 12 seconds at around 10 realtime minutes to the day.

public float DayLengthInMinutes = 1440;// How long a day is in real world minutes
public int HoursToTheDay = 24;       // How many hours there are in a day
public int MinutesToTheHour = 60;    // How many minutes there are in an hour
public int SecondsToTheMinute = 60;  // How many seconds there are in a minute

public float _dayLength;                // Day length in seconds
public float _hourLength;               // Hour length in seconds
public float _minuteLength;             // Minute length in seconds
public float _secondLength;             // Seconds length in seconds
private float timer;                    // Timer that will be tracking game time

void Initialize () {
    timeSinceStart = Time.realtimeSinceStartup;
    _dayLength = _dayLengthInMinutes * 60;  //get seconds to the day
    _hourLength = _dayLength / HoursToTheDay; //determines how long an hour is
    _minuteLength = _hourLength / MinutesToTheHour; //determines how long a minute is
    _secondLength = _minuteLength / SecondsToTheMinute; //determines how long a second is
}
void CalculateTime () {
    if (timer >= _secondLength) {
        currentSecond++;
        timer = 0;
    }
    if (currentSecond >= _minuteLength) {
        currentMinute++;
        currentSecond = 0;
    }
    if (currentMinute >= _hourLength) {
        currentHour++;
        currentMinute = 0;
    }
    if (currentHour >= HoursToTheDay) {
        currentDay++;
        currentHour = 0;
        currentMinute = 0;
        currentSecond = 0;
        dayOrNight = "AM";
    }
}

EDIT: I'm actually basically finished with the while thing, it just isn't very user friendly yet. If people are interested I can answer with the two scripts it is currently running as. I haven't managed to get it into one without Unity crying and I'm not certain why.


texts: How to learn game development when i understand the concepts but don`t know how to implement?

texts:
I have a basic level of programming knowledge, gained trough high-school classes and personal interest and also understand certain game design patterns like game loops, collision detection etc.

My problem is, i don`t understand how to get started with making games without falling in a gap, between tutorials that just cover the basics, that i already know and understand and tutorials that are to complicated for me.

For example, today i got a little gameloop and implemented a graphical output. Than, when i tried to implement a buffer i failed, because i simply didn`t understood where to put it in my existing system.

What would you recommend someone in my situation ? Should i start from zero or are there other certain techniques for learning ?


texts: Destroying Unity GameObject when it goes out of camera during runtime

texts:
I have this GameObject instanciated in unity -

void Start () {

         GameObject myRoadInstance =
            Instantiate(Resources.Load("car"),
                        new Vector3(5, 5, 5),
                        Quaternion.identity) as GameObject;

    }

On running the game, I want this instance removed when it is no longer visible.

How do I do this ?


texts: Moving lights or scene objects in Unity seems to cause a second point light to shrink or dim

texts: Moving a Point Light in 2d space seems to be dimming lights around it. What is this and how can I solve it?


texts: Where would I find C# flocking tutorials?

texts:
Been looking for a while now and finding it difficult to find a good tutorial...

Where would I find a good tutorial on how to implement flocking in a C# XNA game? Something easy to understand .. for beginners!

Cheers!


texts: XNA4 - Trouble updating part of a Texture2D

texts:
I have a big Color[] ColorMap in memory (1280x720), and I have a Texture2D that I've uploaded this ColorMap to.
I update parts of the in-memory ColorMap, and want to upload those changed parts to the texture. I'd rather not re-upload the entire texture every time, so I'd like to use

public void SetData<T> (
     int level,
     Nullable<Rectangle> rect,
     T[] data,
     int startIndex,
     int elementCount
)

As far as I can see, I can not use this directly to upload just a part of my in-memory map to the texture since I can't specify a stride in the SetData method.

So say I'd like to update the area specified by DirtyRect, I'd first need to create a temporary in-memory buffer

Color[] tempBuffer = new Color[DirtyRect.Width*DirtyRect.Height];

then copy the wanted data from my ColorMap to the tempBuffer, and then upload the tempBuffer to my Texture2D like

Text.SetData<Color>(0, DirtyRect, tempBuffer, 0, DirtyRect.Width*DirtyRect.Height);

This seems to work - sometimes... But sometimes it appears in the wrong place ?!

If I get rid of the rectangle code and reupload the entire texture every time using

Tex.SetData(ColorMap);

it works fine, so apparently I must be doing something wrong.

Anyone got any idea? Or is there any code-example of updating only parts of a texture that I can have a look at (XNA 4)?


texts: Import updated scripts into unity (Holotoolkit)

texts:
So I've got the following problem : Developing for the Hololens means that you in most cases need this code in your project : https://github.com/Microsoft/HoloToolkit-Unity
But this code is also updating from time to time. I tried to just replace the old code with the new one which breaks all prefabs in my scenes. So is there a possibility to replace the old HoloToolkitwith the new one without breaking my scenes?


texts:
Yaw is the object turning as if it is spinning on a lazy suzan (one of those spinning plate things you get in chinese restaurants), pitch is pointing the nose up or down, and roll is as if the object is doing a barrel roll.

My question is, do these directly relate to the x, y and z axes? as in, is yaw x, pitch y and roll z? Because If I orient a 3D plane forward using the direct x coordinate system (where z is forward, x is right and y is up) yaw pitch and roll would correspond to the y, x and z axes respectively.

Are they always defined by the axes or are they coordinate system specific?


texts: How to use a decal / logo / tatoo texture on a object or character?

texts:
It appears I've misunderstood the purpose of Standard Shader's "Secondary Texture" options.

If I wish to map temporary details to an object, what is the Unity-appropriate way to do this? I am referring to effects like the following:

Tatoos
Blood Spatters
Logos
Decals
etc...

I'm aware that I could have two materials, but this is render-inefficient, and I avoid hackish workarounds when I can.

Standard practice?

EDIT:

Per the comment below, I will elaborate slightly:

In my specific case I'd like to have one of two scenerios:

1: Areas where a logo can be inserted (player created), pre-uv assigned.
2: Drag/drop logo placement, similarly, but without constraints. This would mean of course passing UV boundaries.


texts: Where can I find an accurate map of Earth for a real-time third-person game?

texts:
I want to create a game that will allow the player to move to any place on Earth. The game will not be first-person, but it will be possible to zoom in quite close nonetheless. What I am lacking is an accurate height-map of the planet. Textures such as albedo, specular or normal would also be very helpful.

I don't know if such textures exist, but an "accurate" height-map should have a resolution of at most a few meters.

The textures do not have to be 100% real. Some parts can be procedurally generated, as long as they look "realistic".


texts:
I'm looking for some IRC channel to talk about game development.

Anyone know some?


texts:
I'm reading the Love2D Development book, which i think i will stop reading because is outdated and very instable, sometimes i got a lot of troubles. Backing to the question, i made a tileset map with Tiled and saved in .tmx with Base64 ( uncompressed ) then i used Advanced-Tiled-Loader and used the code from the book:

-- This is the main.lua file --

local loader = require ("Advanced-Tiled-Loader-master/Loader")

---the path to our .tmx files and sprites

loader.path = "map/"

local map = loader.load("tilemap.tmx")

function love.load()

    love.graphics.setBackgroundColor(255, 153, 0)

    --- load the level and bind the variable map

    loader.path = "map/"

    local map = loader.load("tilemap.tmx")
end

function love.draw()

    map:draw()

end

When i tested the game, the result was this:

http://i.imgur.com/JM8EYrv.png

The result was suposted to be like this:

http://i.imgur.com/W26XFjE.png

So what it could be?


texts:
In a 2D scrolling platformer, what is the most efficient way or knowing which things with parallax depth should be drawn?

The approach below describes trying to know which things are nearby so they can be udpated/drawn. The problem with working out which parallax items are nearby is that you don't know where any of them are until you calculate where they are!

Original Post

I have a 2D array Set<Thing>[][] that I use to store Things that appear on each screen in a scrolling 2D platformer. I use this to look up only Things that a near the current location being rendered, so that I don't bother updating irrelevant objects.

I translate the world coordinates, divide them by the screen size (rounding down), and can then look up all the items on that screen. For instance if screens are 320x240px, and I look up world coordinates 400,50 then 400/320 = 1 and 50/240 = 0, so I look up things[1][0] and update all the things in that entry. If any object can move, they store themselves in the right slot after moving.

Is there any way to use this same system when Things have parallax depth? IE, something with a parallax depth of 1 is infinitely far away (and so always appears at the same location in screen coordinates) and something with parallax depth of 0 is pinned to the foreground.

I'm guessing this isn't possible, as something further away than the foreground will be in more than one screen.

What other approaches are there? I've seen an experienced game developer use a 'scroll rate' instead of a parallax depth, and he moved scenery by the inverse of the distance the camera moved multiplied by this rate. In this model I could treat scenery as per any other moving item and have it store itself in adjacent entries in the 2D array when it moves, but how does it get into the 'right' array slot in the first place? IE, if it's very distant, it could be approach from either the left or the right, and I'm not to know that in advance.

I'm very confused!


texts:
My friend and I would like to program a 2D game. We were discussing about tools needed, so while I am working on the tools, he will work on game logic and stuff.
Probably I will put our tools into the open source circuit once finished, so in your experience what kinds of tools are really needed, but don't already exist for free? I was thinking about what to work on first, so far my list is:

Texture generator
Path editor
Path finder
Grid visibility calculator (sort of PVS but for 2D)


texts:
When animating sprites I am taking the delta difference between frames and locking the rendering frame rate of the sprite animation to the delta time.

float delay = 1000.0f / FPS;
float now = SDL_GetTicks();
if(now - sprite->last_update > delay) {
    render sprite frame
}

This is causing flickering because the background is being drawn faster than the sprite. (my guess) If I draw as fast as the frame rate the flickering goes away. If I slow down the background rendering then the background flickers. By slow down I mean set the FPS to 30.  I want to be able to slow down the animation for a single sprite.
 I need a better way to lock the frame rate for individual sprites.  I can slow the entire frame rate down by delaying in the game loop but I want to be able to slow down a single sprite.  Is this possible?


texts: How to detect which edges of a rectange touch when they collide in iOS

texts:
I'm creating a basic "game" in iOS 4.1. The premise is simple, there is a green rectangle ("disk") that moves/bounces around the screen, and red rectangle ("bump") that is stationary. The user can move the red "bump" by touching another coordinate on the screen, but that's irrelevant to this question.

Each rectangle is a UIImageView (I will replace them with some kind of image/icon once I get the mechanics down). I've gotten as far as detecting when the rectangles collide, and I'm able to reverse the direction of the green "disk" on the Y axis if they do. This works well when the green "disk" approaches the red "bump" from top or bottom, it bounces off in the other direction. But when it approaches from the side, the bounce is incorrect; I need to reverse the X direction instead.

Here's the timer I setup:

- (void)viewDidLoad {
    xSpeed =  3;
    ySpeed = -3;
    gameTimer = [NSTimer scheduledTimerWithTimeInterval:0.05 target:self selector:@selector(mainGameLoop:) userInfo:nil repeats:YES];
    [super viewDidLoad];
}

Here's the main game loop:

- (void) mainGameLoop:(NSTimer *)theTimer {
    disk.center = CGPointMake(disk.center.x + xSpeed, disk.center.y + ySpeed);

    // make sure the disk does not travel off the edges of the screen
    // magic number values based on size of disk's frame
    // startAnimating causes the image to "pulse"
    if (disk.center.x < 55 || disk.center.x > 265) {
        xSpeed = xSpeed * -1;
        [disk startAnimating];
    }
    if (disk.center.y < 55 || disk.center.y > 360) {
        ySpeed = ySpeed * -1;
        [disk startAnimating];
    }

    // check to see if the disk collides with the bump
    if (CGRectIntersectsRect(disk.frame, bump.frame)) {
        NSLog(@"Collision detected...");
        if (! [disk isAnimating]) {
            ySpeed = ySpeed * -1;
            [disk startAnimating];
        }
    }
}

So my question is: how can I detect whether I need to flip the X speed or the Y speed? ie: how can I calculate which edge of the bump was collided with?


texts: How can I snap a game object's position to a grid?

texts:
I'm making a game that involves "falling block" gameplay elements. The problem is, I'm not quite sure how to make it so that the blocks will snap to some kind of grid, in other words, I'm not sure how it will pick the closest cell to its position.

The blocks are not continuously snapping to a grid (i.e. they are subject to gravity). Any tips?


texts: How should I calculate world and projection matrices in this scenario?

texts:
I'm trying to understand transformation matrices. Suppose I use the camera from this StackOverflow answer, this is how my view matrix would look:

Matrix.Identity *
Matrix.CreateTranslation(-Position.X, -Position.Y, 0) *
Matrix.CreateRotationZ(Rotation) *
Matrix.CreateTranslation(Scale, Scale, 0) *
Matrix.CreateScale(new Vector3(Scale, Scale, Scale));

How'd I calculate my World and Projection matrices then?


texts: How to make 3D snake with procedural mesh in Unity

texts:
Im currently learning Unity3D and I would like to recreate the old Nokia game "Snakes" (example video: https://www.youtube.com/watch?v=FXg3jVG-tXs&ab_channel=aantv, play it at 1:30 and notice the movement and even the animations when the snake is turning to the sides).
The game movement is grid based as you can see, so the snake can turn only, when the head is in the center of each floor slab. I have done this by using Coroutine and I am interpolating the position of the head between the distance of each 2 slabs. (example video: https://www.youtube.com/watch?v=_LWYQE1UC68&ab_channel=Chlebikpastika).
My question is, how to design and implement the solution using procedural mesh? My idea is to update the vertices of corresponding snake body part with the values of vertices of previous snake body part. I could have Body class, which could have the buffer of vertex positions of previous body, and after each update, the vertices would be updated with currently poped values from buffer. I dont know if this is good design, do you have any ideas how I could achieve the movement of vertices of the snake?


texts: How can i keep the spawned cubes to be inside the given area?

texts:
In this case the 4 walls and objects I spawn inside the 'wall area' are all cubes. This situation could change to where the walls will be spheres and the other objects can be cylinders or cubes (its not limited to cubes only).

What I'm trying to do is to spawn the objects in random positions but within the 'wall area'. The problem is when some cubes (objects) are spawning too close to the walls, part of the cubes will inside the area and some will be outside.

In the screenshot example on the right, a cube is going out of the wall area.
In this case the walls area is sized according to the terrain (500x500) but it could be any size like 45x23 or 100x100.

In the script below I'm getting the 4 walls objects in array.

walls = GameObject.FindGameObjectsWithTag("Wall");

Now I wonder how can I use a ray cast to detect if each cube is spawning too close to one of the walls and if so then re-position the cube randomly, over and over again until it's inside the walls area. I'm not sure if using ray cast is the best way but that's what I had in mind.

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

public class SpawnObjects : MonoBehaviour
{
    public int numberOfObjects;
    public GameObject objectToPlace;
    public Vector3 newObjectsSize;
    public float spawnSpeed = 0.1f;

    private int wallsLengthX;
    private int wallsLengthZ;
    private int wallsPosX;
    private int wallsPosZ;
    private int currentObjects;
    private GameObject[] walls;
    private List<GameObject> objects = new List<GameObject>();
    private GameObject spawnedObjects;

    void Start()
    {
        var wi = GetComponent<Walls>();
        wallsLengthX = (int)wi.lengthX;
        wallsLengthZ = (int)wi.lengthZ;
        wallsPosX = (int)wi.wallsStartPosition.x;
        wallsPosZ = (int)wi.wallsStartPosition.z;

        walls = GameObject.FindGameObjectsWithTag("Wall");
        spawnedObjects = GameObject.Find("Spawned Objects");

        StartCoroutine(Spawn());
    }

    IEnumerator Spawn()
    {
        for (int i = 0; i < numberOfObjects; i++)
        {
            GameObject newObject = (GameObject)Instantiate(objectToPlace);
            newObject.transform.localScale = GenerateRandomScale(newObject);
            newObject.transform.localPosition = new Vector3(GenerateRandomPositions(newObject).x , GenerateRandomPositions(newObject).y + newObject.transform.localScale.y / 2.0f, GenerateRandomPositions(newObject).z);
            newObject.name = "Spawned Object";
            newObject.tag = "Spawned Object";
            newObject.transform.parent = spawnedObjects.transform;

            objects.Add(newObject);
            yield return new WaitForSeconds(spawnSpeed);
            currentObjects += 1;
        }

        var wp = GetComponent<WayPoints>();
        wp.FindMyObjects();
    }

    private Vector3 GenerateRandomScale(GameObject newObject)
    {
        Vector3 newScale = new Vector3(UnityEngine.Random.Range(5, 100), UnityEngine.Random.Range(5, 100), UnityEngine.Random.Range(5, 10));

        return newScale;
    }

    private Vector3 GenerateRandomPositions(GameObject newObject)
    {
        float paddingX = Mathf.Clamp(newObject.transform.localScale.x, 0, wallsLengthX) / 2f;
        float paddingZ = Mathf.Clamp(newObject.transform.localScale.z, 0, wallsLengthZ) / 2f;
        float originX = wallsPosX + paddingX - wallsLengthX / 2f;
        float originZ = wallsPosZ + paddingZ - wallsLengthZ / 2f;
        float posx = UnityEngine.Random.Range(originX, originX + wallsLengthX - paddingX);
        float posz = UnityEngine.Random.Range(originZ, originZ + wallsLengthZ - paddingZ);
        float posy = Terrain.activeTerrain.SampleHeight(new Vector3(posx, 0, posz));

        return new Vector3(posx, posy, posz);
    }
}


texts: I'm developing a platformer game and have implemented jumping for the player. The player is able to jump, but holding the up arrow causes the player to continuously jump. What would be the best way to add a small delay between jumps so that once the player lands on the ground; there is a small delay before the next jump is initiated.


texts: GLSL Lighting with attenuation; how to add a fade-out color?

texts:
I am using the GLSL shader from this link, slightly modified and i got it working.
The shader code is the following:

VS:

  vPosition = uMVMatrix * vec4(aVertexPosition, 1.0);
  vTransformedNormal = uNMatrix * aVertexNormal;
  gl_Position = uPMatrix * vPosition;

FS:

  float minLight = 0.01f;
  float radius = sqrt(1.0 / (uAttenuationFactor * minLight));
  float lightAdd = 0.0f;
  float dist = distance(vPosition.xyz, (uMat4Identity * vec4(uLightPosition, 1.0)).xyz);
  float att = clamp(1.0 - dist/radius, 0.0, 1.0);
  vec3 surf2light = normalize((uMat4Identity * vec4(uLightPosition, 1.0)).xyz - vPosition.xyz);
  vec3 norm = normalize(vTransformedNormal);
  float diffuseCoefficient = max(0.0, dot(norm, surf2light));
  lightAdd += att * (diffuseCoefficient + uSourceIntensity);
  vec4 textureColor = texture2D(uTex0, vec2(vTextureCoord.s, vTextureCoord.t));
  vec3 torch_output = lightAdd * uColorLight;
  vec4 final_color = (vec4(torch_output, 1.0f) * textureColor) * vVertexColor;
  gl_FragColor = final_color;

The shader computes point lighting with attenuation and give very satisfactory results. Look at the pic:

I give uAttenuationFactor = 0.4f and uSourceIntensity = 0.2f to get this result and it satisfies me. However, besides setting the light color, how i could modify the shader to fade-out to another color than black?? Anything i tried it just modifies the visible parts of the screen i.e. walls but the black remains unchanged. I would had liked to be able to set a grey color for rain or whitish for fog effect etc.

Thanx.


texts:
I have a problem with AABB collision.

I am making a top down rougelike in SFML and my collision algorithm does't quite work properly.

HERE IS A GIF OF THE PROBLEM.

It mostly works, except for when you're against the corner of the block and hold the direction towards the block for a second. For some reason, after about a second, the player is clipped through the block to the adjacent side.

I think the problem is caused when, for example, the x axis needs to be resolved as the player is approaching the object from the left, but the y penetration ends up being more than the x and thus the collision is resolved incorrectly.

This is my collision code:

sf::FloatRect collisionRect;
std::vector<Entity*> activeEntities;
for each (Entity* e in entities)
    if (e->otype == Dynamic)
        activeEntities.push_back(e);
for each (Entity* dynamicEntity in activeEntities)
{
    for each (Entity* target in entities)
    {
        if (dynamicEntity->sprite.getGlobalBounds().intersects(target->sprite.getGlobalBounds(), collisionRect) && dynamicEntity != target)
        {
            dynamicEntity->velocity = sf::Vector2f(0, 0);
            if (collisionRect.width > collisionRect.height)
            {
                if (collisionRect.contains(collisionRect.left, dynamicEntity->sprite.getPosition().y))
                    dynamicEntity->sprite.setPosition(dynamicEntity->sprite.getPosition().x, dynamicEntity->sprite.getPosition().y + collisionRect.height);
                else
                    dynamicEntity->sprite.setPosition(dynamicEntity->sprite.getPosition().x, dynamicEntity->sprite.getPosition().y - collisionRect.height);
            }
            else if (collisionRect.height > collisionRect.width)
            {
                if (collisionRect.contains(dynamicEntity->sprite.getPosition().x + dynamicEntity->sprite.getGlobalBounds().width - 1.f, collisionRect.top + 1.f ))
                    dynamicEntity->sprite.setPosition(dynamicEntity->sprite.getPosition().x - collisionRect.width, dynamicEntity->sprite.getPosition().y);
                else
                    dynamicEntity->sprite.setPosition(dynamicEntity->sprite.getPosition().x + collisionRect.width, dynamicEntity->sprite.getPosition().y);
            }
        }
    }
}

EDIT: I have tried making only one call to getPosition() getSprite() etc., and that only makes it glitchier.

EDIT2: I made a gfy of the problem. Sorry for the low res.


texts:
I'm having trouble with the Unity / OUYA plugin.

I'm using Unity 4 with the latest update on a Windows 7 machine.

When I open the starter kit and try to compile the plugin I get the following error:

  Picked up _JAVA_OPTIONS: -Xmx512M

And if I try to Build and Run I get this error:

  Error building Player: ArgumentException: Illegal characters in path.

I'm stumped, I've gone through lots of forum posts here and on stackoverflow and I can't seem to resolve it.

My environment variables look like this:

PATH - C:\Users\dave\Documents\adt-bundle-windows-x86_64-20130219\sdk\tools;
       C:\Users\dave\Documents\adt-bundle-windows-x86_64-20130219\sdk\platform-tools\

JAVA_HOME - C:\Program Files (x86)\Java\jdk1.6.0_45\

Everything in the OUYA Panel is white

Any ideas?


texts: What is the technical term for animation of a dead body?

texts:
In some 3D games when a 3D model of a person is shot to death (or suddenly dead) his body falls to the ground and every limb, the head and the body move free.
What is this particular way of handling dead bodies called?
Is it possible with UDK?

If you didn't understand, I meant like in this video: see how the corpse falls.


texts: Unity Mysql fail to connect only Android

texts:
I have issue that my android phone can't connect to the Mysql database. While on the editor or Windows build. Everything works fine, the game is able to connect. I get no erros when i build it, so i have no idea why it will not work on the Android phone. I have not tested on IPhone, since i have no Iphone to test on.

04-11 16:00:31.482 18162 18206 E Unity   : PlatformNotSupportedException: Operation is not supported on this platform.
04-11 16:00:31.482 18162 18206 E Unity   :   at MySql.Data.MySqlClient.MySqlConfiguration..cctor () [0x00000] in <2c8fc0407a5848dfa91f594842a803e7>:0
04-11 16:00:31.482 18162 18206 E Unity   : Rethrow as TypeInitializationException: The type initializer for 'MySql.Data.MySqlClient.MySqlConfiguration' threw an exception.
04-11 16:00:31.482 18162 18206 E Unity   :   at MySql.Data.MySqlClient.Replication.ReplicationManager..cctor () [0x0001e] in <2c8fc0407a5848dfa91f594842a803e7>:0
04-11 16:00:31.482 18162 18206 E Unity   : Rethrow as TypeInitializationException: The type initializer for 'MySql.Data.MySqlClient.Replication.ReplicationManager' threw an exception.
04-11 16:00:31.482 18162 18206 E Unity   :   at MySql.Data.MySqlClient.MySqlConnection.Open () [0x0016c] in <2c8fc0407a5848dfa91f594842a803e7>:0
04-11 16:00:31.482 18162 18206 E Unity   :   at DatabaseManager.CreateConnection () [0x00058] in <c2f1e2460e294aa39099177282cd5712>:0
04-11 16:00:31.482 18162 18206 E Unity   :   at GameManager.Start () [0x00017] in <c2f1e2460e294aa39099177282cd5712>:0


texts: Shadows are choppy on Android, but look fine in Unity Editor on my PC

texts:
Here is a gif of what I'm seeing with my shadows on my Android device:

https://gfycat.com/VapidTestyFrigatebird

That shadow looks perfectly fine from any angle / distance in my Unity editor, however.  I don't know much about shadows in Unity yet, but here's a bit more info about my settings:

Directional Light Settings

Shadow Quality Settings

Has anyone experienced an issue similar to this before?  How do I fix this shadow choppiness?


texts: Generate plane with script missing triangles

texts:
I am trying to do a simple script to generate a plane from a script by creating a new mesh. After trying it, it seems like some of the triangles aren't showing up. I checked if they were in the list by making it publci and they are in it, so I dont understand why the last triangles aren't showing while the others are.
int size = 4;
Mesh meshy;
public List<Vector3> vert = new List<Vector3>();
public List<Vector2> uv = new List<Vector2>();
public List<int> tri = new List<int>();
void Start()
{
    vert = new List<Vector3>();
    tri = new List<int>();
    meshy = new Mesh();
    for (int x = 0; x < size; x++)
    {
        for(int z = 0; z < size; z++)
        {
            vert.Add(new Vector3(x, 0, z));
        }
    }
    meshy.vertices = vert.ToArray();
    for (int i = 0; i < ((size-1)*(size-1));i++)
    {
        tri.Add(i);
        tri.Add(i+1);
        tri.Add(i+size);
        tri.Add(i + size +1);
        tri.Add(i + 1 +(size - 1));
        tri.Add(i + 1);
    }
    meshy.triangles = tri.ToArray();
    for(int i = 0; i < ((size - 1) * (size - 1)); i++)
    {
        uv.Add(new Vector2(0, 0));
        uv.Add(new Vector2(1, 0));
        uv.Add(new Vector2(0, 1));
        uv.Add(new Vector2(1, 1));
    }
    meshy.uv = uv.ToArray();
    GetComponent<MeshFilter>().mesh = meshy;
}


texts: Unity 2D - Pixel perfect movement using physics

texts:
I'm trying to make a game in the style of many NES games and I'd like object movement to do two things:

I want to move an exact number of pixels per update.
I want, for lack of a better term, absolute movement.  The object should move or not move, I don't want a ramp up or down in speed.

I'm trying to do this with physics because I would like to use Unity's hitbox collision detection.  Moving objects using the translation property does not allow for this, at least that is my understanding.

Any help is appreciated and if my thought process is off, I'd like any suggestions or pointers in the right direction, thanks.

Here is my move method that gets called on Update.  I expect to movement to be in whole pixels, however, when I test the x and y are always fractional.

private void Move()
{
    VerticalMovement = 0;
    HorizontalMovement = 0;

    if (Input.GetKey(KeyCode.W))
        VerticalMovement = 1;

    if (Input.GetKey(KeyCode.S))
        VerticalMovement = -1;

    if (Input.GetKey(KeyCode.A))
        HorizontalMovement = -1;

    if (Input.GetKey(KeyCode.D))
        HorizontalMovement = 1;

    this.GetComponent<Rigidbody2D>().velocity = new Vector2(HorizontalMovement * Speed, VerticalMovement * Speed);
}


texts: How do I efficiently sort objects by draw order when rendering a 2D game?

texts:
I need to render a "tile" game with objects that overlap, because they are taller than the tile they stand on, like the games in these screenshots:

I don't know how to render them in the correct order. I intend to perform a sorting operation before every rendering, depending on the object's Y position. However, I'm worried it'll be too expensive, especially since very few objects change their Y positions.

Is sorting the most performant way? Is there any other way? What algorithm or data structure should I use?


texts: Client projectile ignores camera Y-axis in multiplayer shooter

texts:
I'm able to spawn the bullet and make it move. But the problem is, only the host can shoot the bullet in the way the camera is facing(takes both X-axis and Y-axis correctly). The client takes only the X-axis of the camera and keeps the Y-axis at zero.

Here's the code for spawning and applying velocity:

[Command]
void CmdFire()
{
    GameObject fb = Instantiate(fireBall, spawnPoint.position, spawnPoint.rotation);
    fb.GetComponent<Rigidbody>().velocity = gameObject.GetComponentInChildren<Camera>().transform.forward * fireSpeed;
    NetworkServer.Spawn(fb);
}

And the code for the camera attached to the player:

void Update()
{

    mouseX = Input.GetAxis("Mouse X") * mouseSensitivity * Time.deltaTime;
    mouseY = Input.GetAxis("Mouse Y") * mouseSensitivity * Time.deltaTime;

    //Horizontal Looking
    playerBody.Rotate(Vector3.up * mouseX);

    //Vertical Looking
    xRotation = xRotation - mouseY;
    xRotation = Mathf.Clamp(xRotation, -90f, 90f);
    transform.localRotation = Quaternion.Euler(xRotation, 0f, 0f);

}


texts: How to license free assets but prevent asset flipping?

texts:
I'm a hobbyist prop artist and give away everything I make for free, even for commercial use. At the moment I use the CC BY 4.0 license which is great except for the fact that someone would be able to download my assets and sell unmodified for a profit.

Ideally, I would like a license where you are free to download and use my assets for free but can only be used for commercial purposes where the assets are not the primary focus of the product e.g. included as part of a game.

Does anyone have any experience here about how best to achieve this?


texts: Minecraft : Mod-making (MCreator) : Redstone Result Event

texts:
I am currently using a Mod-making Tool called "MCreator" made by Pylo.

I am currently making a Block Element and creating an event when The block is right clicked by a Prismarine Shard, then The block will power redstone.

I did this by doing the following:

Event : On block rightclicked
Condition : itemInPlayersHand[] == Items.prismarine_shard
Event parameters (Redstone Power; State of power) : true
I also checked "Can provide power?" In Advanced properties

The problem is that when I test the mod in a client environment and click the block, it will not power any redstone around it.

I tried to change when the event happens to Print a text and when I tested and clicked on it with a prismarine shard, it printed the text to the console.

So is there something wrong with the Redstone Power event result or am I doing something wrong.

Thanks in Advanced,
Bryan


texts: Most efficient way to remove a Rectangle ? Monogame/XNA

texts:
I have a project in which I'm trying to remove the "collision box" (Rectangle class) of one of my enemy.
My game logic basically is:

foreach (Enemy e in Enemy.enemiesOnScreen) {
            if (e._isDead) {
                e._collisionBox = new Rectangle(0, 0, 0, 0);
            }
            else {
                e.Update(gameTime);
            }
        }

What I wrote works perfectly, but wouldn't that be subject to memory overflow (for a much higher number of instances) or bad optimization in a real game project ?


texts: applyAngularVelocity causes error when called right after object instantiation

texts:
I'm trying to make a physicsBody rotate as soon as it is instantiated.

CCNode* ball = [CCBReader load:@"Ball"];
[ball.physicsBody applyForce:force];
[ball.physicsBody applyAngularImpulse:arc4random_uniform(360) - 180];

Applying force works fine, the last line however throws an error in cpBody.c line 123:
cpAssertHard(body->w == body->w && cpfabs(body->w) != INFINITY, "Body's angular velocity is invalid.");

When I don't apply force and merely rotate the problem persists. If I send applyAngularImpulse at some later point (in this case on a touch) it does work. Is this function not supposed to be called right after instantiation, or is this a bug?


texts: Determine arc-length of a Catmull-Rom spline to move at a constant speed

texts:
I have a path that is defined by a concatenation of Catmull-Rom splines. I use the static method Vector2.CatmullRom in XNA that allows for interpolation between points with a value going from 0 to 1.

Not every spline in this path has the same length. This causes speed differences if I let the weight go at a constant speed for every spline while proceeding along the path. I can remedy this by letting the speed of the weight be dependent on the length of the spline. How can I determine the length of such a spline? Should I just approximate by cutting the spline into 10 straight lines and sum their lengths?

I'm using this for dynamic texture mapping on a generated mesh defined by splines.


texts: AndEngine Scoreloop - java.lang.IllegalStateException: you are not calling from the main thread context

texts:
I am a very novice android developer but also created a game using andEngine successfully. Now I want to integrate Scoreloop and everything is fine with Leaderboard view and TOS view, except I am having hard time submitting scores from a game scene. I implemented OnScoreSubmitObserver in the main BaseGameActivity (GameActivity). I used the following line inside the onCreateEngineOptions method:

ScoreloopManagerSingleton.get().setOnScoreSubmitObserver(this);

I also declared the override method perfectly inside GameActivity as mentioned in the scoreloop tutorial:

@Override
public void onScoreSubmit(int status, Exception error) {
    // TODO Auto-generated method stub
    //Calls the ShowResultOverlayActivity. Make sure you have modified the
    //AndroidManifest.xml to reference this overlay class.
    startActivity(new Intent(this, ShowResultOverlayActivity.class));
}

Now I want to submit score from inside a scene using the following line:

ScoreloopManagerSingleton.get().onGamePlayEnded(score, null);

But this shows the following error:

java.lang.IllegalStateException: you are not calling from the main thread context

I also tried implementing OnScoreSubmitObserver on the scene class and tried calling each line mentioned above inside the scene class using "activity" instead of "this", as "activity" is an instance of the GameActivity. but it also shows the same error. Please help.


texts: how to set the length of a control point without changing its direction

texts: Considering the image above, I want to manually increase the length of a bezier curve control point (C3 to newC3) by a certain value (say 0.5f) while preserving it’s original direction. How can I do this?


texts: Create a stack driven coroutine based state machine for Unity

texts:
I am working on a game where I am using a coroutine based state machine which is mostly a multi class implementation of this link. I am using it because it allows me to create multi frame sequences.

I wanted to know how would I go about making a stack based machine, so that I can overlay game states such as when I want to pause the game to show a menu i can run a pause menu state pausing the running game state, while still allowing the state objects to be rendered in the background

Here is the code I am using for a state:

public abstract class State {

[Inject]
MonoBehaviour gameObject;

[Inject]
public EventSystem eventSystem;

StateMachine parent;

public State(StateMachine p)
{
    parent = p;
}

public abstract IEnumerator Enter();

public abstract IEnumerator Exit();

public abstract IEnumerator Update();

public IEnumerator Run()
{
    yield return gameObject.StartCoroutine(Enter());
    while(parent.CurrentState.GetType() == GetType())
    {
        yield return gameObject.StartCoroutine (Update ());
    }
    yield return gameObject.StartCoroutine (Exit());
}
}

State machine run function

 State Current //The current state , the one at the top of the stack
 while(Current!=null)
        {
            yield return Component.StartCoroutine(Current.run());
        }

The problem with this approach is as soon as the state machine's current state changes (That is when i push it down the stack adding a new state on top) , the while loop in the Base state class's run method will end and will call the exit coroutine causing the state to end which is undesirable as according to the stack pattern the state should be paused

Moreover as coroutines work in unity, the yield return statement(in the state-machine) wont return until the previous started coroutine exits , which is currently as of now responsible for starting the states .

My question is how do i alter this code so as to pause the previous state (that will be pushed into the stack) instead of exiting it and starting anew state

this implementation works fine if there is to be only a single state in the memory


texts:
I'd like to create a system in Unreal Engine 4 with glob-like fluids which interact with the environment, like the gel in Portal 2. Here's a GIF of the gel from that:

(search that I used to bring up similar images)
I was wondering how it might be possible to do something like this? An in-depth guide would be nice as I have a mostly basic understanding of blueprints in UE4, although I know it's a lot to ask for. If you know how I can achieve this, please let me know. Thank you! :)
P.S: The "fluid" stains don't need to give effects such as speed like you saw in the GIF, but I would still like the liquids to stain wherever they hit. :)


texts: Do I need to initialize a public List variable in Unity?

texts:
I want to create a list of horses and print the name of the Horses that are stored in the list. Although I got the answer correct as I desired, there's one thing that is puzzling me when I declare a list variable.

I declared it as:

public List<string> myFavouriteHorses;

and in an example I have seen it's declared like this:

public List<string> myFavouriteHorses = new List<string> ();

Despite this difference, both of them worked. What's the difference between these two approaches? Does it matter which one I use?

Here's the entire code which i tried:

using UnityEngine;
using System.Collections.Generic;

public class LearningScript : MonoBehaviour {

    public List<string> myFavouriteHorses = new List<string> ();

    void Start(){
        myHorses ();
        }

    void Update(){
        if (Input.GetKeyDown (KeyCode.Return)) {
            Print ();

        }

    }

    void myHorses(){

        myFavouriteHorses.Add ("Grey Horse");
        myFavouriteHorses.Add ("Black Horse");
        myFavouriteHorses.Add ("Rudolph Horse");
        myFavouriteHorses.Add ("Biting Horse");
    }

    void Print(){
        Debug.Log ("This list has " + myFavouriteHorses.Count + " horses");

        Debug.Log ("The horse at index 1 is " + myFavouriteHorses [1]);
        Debug.Log ("The horse at index 2 is " + myFavouriteHorses [2]);
        Debug.Log ("The horse at index 3 is" + myFavouriteHorses [3]);

    }

}

Here's the output

Why doesn't it make a difference whether or not I initialize the List with new before using it?


texts: Game (X-Plane) boot/startup time / performance

texts:
I use X-Plane for my question but it also concerns probably every other flight-simulator or simulation game in general. When developing a plugin what bothers me most is the startup-time of the application to test my plugin functionality so I was wondering how I can improve the startup speed of the simulator.

First I removed all additional scenery and reduced the loaded files to a minimum which gave me a startup time of 34 seconds which is quite fast already.
To improve the time even further I thought it would make sense to run the whole application from memory and I installed ubuntu 64-bit and created a 2GB tempfs filesystem in memory (ram-disk).

When starting x-plane from this memory file system it still takes 30 seconds. Can anyone explain what the application does during startup which needs so much processing time?

I assume that the graphic bitmaps for the object and the environment are compressed on disk and therefore they have to be decompressed in memory first before they can be used in opengl. This would explain the time spent on startup.

If it is true that the bitmaps need to be decompressed first would it be possible to improve the time by using multiple cores? If the application is multithreaded and there are four cores would the time be divided by four or does this processing happen on the GPU?

Any explanation which helps me to better understand the startup-process of a computer game is really appreciated because I'm interested in improving the overall performance of the system and therefore I need a better understanding of the bottlenecks (RAM, CPU, GPU, Disks (SSD/Raid), OS, libraries, ...).


texts: What timeframe is used to compute ARPDAU for monetization purposes?

texts:
I search this for a while now but could't find the answer. ARPDAU - the 'average revenue per daily active user' is a metric for the financial performance of a game/app. But what timeframe is the value measured in?

For example, some statistics that can be found online mention an ARPDAU of $0.05 to $0.1 for casual games and up to $0.8 for hard-core (targeted at hard-core gamers) games. But what's the timeframe over which this is computed? One day? One month? The lifetime of the game?

The acronym itself would suggest it's lifetime revenue divided by DAU (otherwise it should be named ARPDAUPD or ARPDAUPM shouldn't it?), but then these numbers seem incredibly low.
Let's say I have a casual game that performs averagely and has (on average, or let's say constantly) 10,000 daily active users. Does that mean I could expect from such a game to generate $500-$1000 over it's entire lifetime? Seems like nothing. Or is that rather $500-$1000 per day?


texts: Unity: Instantiate an object respecting the prefab's default rotation

texts:
Simple question, I hope.

I've built a variety of prefabs for an isometric shooter game (hazards, enemies, health indicator bars, popup texts, shots, explosions).  All of these prefabs were constructed with default rotations appropriate for the gameplay.

My problem is that Instantiate() will overwrite the default rotation of the prefab with whatever is specified as the rotation parameter.  So I'm left with hard-coded rotations in my Instantiate() calls to get things oriented correctly in the X-Z plane. (0,180,0) and (90,0,0) are common ones.  I'd much prefer to Instantiate prefab gameObjects consistently with "no change to their default rotation," but I'm not sure how to accomplish this.

Thanks for the help,
Mike.


texts: OpenGL Parallax Displacement Mapping Not Working

texts:
I am attempting to implement parallax displacement mapping into my OpenGL code but it is not working as it should.

https://imgur.com/a/9yIQL

As I move around, double-lines moves around and if I am looking and positioned at just the right angle, the extra lines disappears and it looks like a normal texture, but without any displacement mapping.

I have tried various texture/displacement mapping combos and all of them have the same issue, so it is not my textures.

VS Code:

#version 330 core

layout (location = 0) in vec3 position;
layout (location = 1) in vec2 uvCoordinates;
layout (location = 2) in vec3 normal;
layout (location = 3) in vec3 tangent;

out Vertex
{

    vec3 position;
    vec2 uvCoordinates;
    vec3 normal;
    mat3 tbnMatrix;

} vertex;

uniform mat4 projection;
uniform mat4 view;
uniform mat4 model;

void main()
{

    gl_Position = projection * view * model * vec4(position, 1.0);

    vertex.position = (model * vec4(position, 1.0)).xyz;
    vertex.uvCoordinates = uvCoordinates;
    vertex.normal = normalize((model * vec4(normal, 0.0)).xyz);

    vec3 n = normalize((model * vec4(normal, 0.0)).xyz);
    vec3 t = normalize((model * vec4(tangent, 0.0)).xyz);

    t = normalize(t - dot(t, n) * n);

    vec3 b = cross(t, n);

    vertex.tbnMatrix = mat3(t, b, n);

}

FS Code:

#version 330 core

layout (location = 0) out vec4 color;

in Vertex
{

    vec3 position;
    vec2 uvCoordinates;
    vec3 normal;
    mat3 tbnMatrix;

} vertex;

struct Material
{

    vec3 ambientLight;
    vec3 diffuseLight;
    vec3 specularLight;
    float transparency;
    float shininess;
    int useDiffuse;
    int useSpecular;
    int useNormal;
    int useDisplacement;
    sampler2D diffuse;
    sampler2D specular;
    sampler2D normal;
    sampler2D displacement;

};

uniform vec3 ambientLight;

uniform vec3 eyePosition;

uniform Material material;

uniform float displacementScale;
uniform float displacementBias;

vec2 calculateTextureCoordinates(vec3 eyeDirection, vec2 uvCoordinates, mat3 tbnMatrix, sampler2D displacement)
{

  return uvCoordinates + (eyeDirection * tbnMatrix).xy * (texture(displacement, uvCoordinates).r * displacementScale + displacementBias);

}

void main()
{

    color = vec4(ambientLight * material.ambientLight, material.transparency);

    if(material.useDiffuse == 1)
    {

        vec2 uvCoordinates;

        if(material.useDisplacement == 1)
        {

            uvCoordinates = calculateTextureCoordinates(normalize(eyePosition - vertex.position), vertex.uvCoordinates, vertex.tbnMatrix, material.displacement);

        }
        else
        {

            uvCoordinates = vertex.uvCoordinates;

        }

        color *= texture(material.diffuse, uvCoordinates);

    }

}

I also have other lighting shaders that use the exact same tbn matrix to calculate normal mapping, which works just fine.  This leads me to believe that both my tangent calculations and tbn matrix are working just fine.  This scene is using no lighting, so lighting should have no impact on this code.

The displacementScale uniform is set to 0.04 and my displacementBias is set to -0.02.  Increasing the scale causes the lines to become even more and more disoriented and decreasing it causes less of the disoriented effect but does not provide any displacement whatsoever.

I've also checked to make sure I have binded all my textures to the correct sampler2D and they are correct.  I've been working on this for awhile now and I am completely stuck.  Any help would be immensely appreciated.


texts: Are web browser games like Travian/Tribal Wars based on asynchronous responses?

texts:
I'm coding in Python. Currently, with some group of people, we are making a decision about server-side language choice for our web-browser-based strategy game. I have some questions:

Are games like Travian based on asynchronous requests or it's all normal synchronous?
WSGI for Python web apps is synchronous. Does it mean only one request is processed in the moment? If I have 10000 requests, I must wait for each one?
For this type of game, requests based on RESTful or GET/POST methods are most suitable? No need of sockets (I hope so)?


texts: Shader compile log depending on hardware

texts:
I'm done with the core of my graphics engine and I'm testing it on every platform I can get my hands on. Now, what I noticed is that different drivers return different shader and program compile log content.

For example, on my friend's laptop if you successfuly compile a shader then the log is simply empty. However on my PC I get some useful information along with it.

So if I compile a vertex shader, I'll get:

  Vertex shader was successfully compiled to run on hardware.

Which isn't that impressive, but is what happens when I compile a program. On my friend's computer the log is empty, since the program compiles. However on my own computer I get:

  Vertex shader(s) linked, fragment shader(s) linked.

Which is awesome, because I'm attaching a geometry shader with 0 (I have a geometry shader file with trash, so it doesn't compile and the pointer is set to 0), and the compiler just tells me which shaders linked.

Now it got me thinking, if I was going to buy a graphics card, is there a way for me to get the information about whether or not I'll get this "extended" compile information? Maybe it's vendor specific? Now I don't expect an answer TBH, this seems a bit obscure, but maybe somebody has any experience with this and could post it.


texts: Unity3d iOS build - where are the textures?

texts:
First time building and running my Unity3D app on my iPhone and it appears that all the textures are missing.  Everything is just a solid block of whatever color I made it.  When running in Unity I see everything correctly.  See images below.

To complicate things I'm using custom shaders, and all the objects are custom procedural meshes.  Quads that I build in script.  If I switch the paper backplate shader to a built in shader I still only see white on the iPhone.

So I suspect that somehow the textures just aren't making it to the iOS project.  When I look in the iOS project I can't find any textures.  Where would they be in the iOS project?  For example in Xcode under Build Phases > Copy Bundle Resources the only thing there is the Images.xcassets, which only contains the splash screens and icons.

Surely I'm missing something simple.

I tried renaming the folder where I keep my textures to "Textures".  Also my textures are not built in to the shader but added programmatically like this:

void Awake ()
{
    meshFilterComponent = GetComponent<MeshFilter>();
    Material material = GetComponent<MeshRenderer>().material;
    material.SetTexture(0, paperTexture);
    material.color = new Vector4(1f, 1f, 1f, 1f);
}

Where paperTexture is set up in the GameObject to point to the correct texture.  Is there any way to force a texture to be part of a build?  Let's say that you swap out textures in code, like swapping themes, how would you make sure they're all there to be loaded as needed?

Running On iPhone:

Running In Unity3D:


texts: Unity blue sprite always showing on top regardless of order

texts:
I have 3 SpriteRenderer

SpriteRenderer - Green Sprite
SpriteRenderer - Blue Sprite
SpriteRenderer - Brown Sprite

The problem is that the blue sprite always shows on top of the others. I even tried to keep the SpriteRenderer in the same order and change the images but no matter which SpriteRenderer I put the blue image into it always shows on top.

I have the sorting layer set to 0 for all 3 and I cannot change them because I will have to change so many other objects in the game.


texts: How to change the alpha of an uneditable LineEdit to 1?

texts:
I noticed that Godot changes the alpha of the LineEdit text when editable = false. I want the alpha to stay 1.
What I'm trying to do here is let the user input a name and then when they press enter it saves it in some dict etc (not important) and still shows as normal text (they can't edit it again)


texts: Can't get the logic behind my AABB collision

texts:
This is my collision detection function in the maze game im working at. I never made a game before and I dont have that much programming experience.

The question I keep asking me continously is why this isn't working. The Solids are instances of the class Solids with rectangular shape(X(Top-left-corner),Y(Top-left-corner),width,height) which are stored in a List< T >. The function below iterates through the List and calls the second function below. checkForCollision is called every FrameUpdate.

Can somebody please help me. I'm becoming desperate :)

private void checkForCollision()
        {
            foreach (Solids wall in level1.WallObjects)
            {
                if (IsCollidedSolids(ref Pl1, wall))
                {
                    Pl1.OnCollision();
                    break;
                }
            }
        }

public bool IsCollidedSolids(ref Player Pl ,Solids act)
        {
            if (Pl.X+Pl.width >= act.X && Pl.Y >= act.Y - act.height)
                return true;
            if (Pl.X + Pl.width >= act.X && Pl.Y -Pl.height <= act.Y)
                return true;
            if (Pl.X <= act.X + act.width && Pl.Y - Pl.height <= act.Y)
                return true;
            if (Pl.X <= act.X + act.width && Pl.Y >= act.Y - act.height)
                return true;
            else
                return false;
        }


texts: How do I save data to the iPhone properly and securely?

texts:
I'm creating a game using Cocos2D (objective-c) and it has come to the point where I have to save data to local storage, like high scores and similar stuff.

I know that NSUserDefaults is not a good option because it isn't encrypted. I would like to know what is or what are the best/simple methods of saving data with security to the iPhone to avoid a casual hacker from changing the score.


texts: How to keep server-client clocks in-sync for precision networked games like Quake 3?

texts:
I'm working on a 2D top-down-shooter and doing my best to copy concepts used in networked games like Quake 3.

I have an authoritative server.
The server sends snapshots to clients.
Snapshots contain a timestamp and entity positions.
Entities are interpolated between snapshot positions so movement looks smooth.
By necessity, entity interpolation occurs slightly "in the past" so that we have multiple snapshots in which to interpolate between.

The problem I'm facing is "clock synchronization".

For simplicity-sake, let's just pretend for a moment that there is zero latency when transferring packets to and from the server.
If the server clock is 60 seconds ahead of the client clock, then a snapshot timestamp will be 60000ms ahead of the client local timestamp.
Therefore, entity snapshots will collect and sit for about 60 seconds before the client sees any given entity make his moves, because it takes that long for the client clock to catch up.

I've managed to overcome this by calculating the difference between the server and client clock each time a snapshot is received.

// For simplicity, don't worry about latency for now...
client_server_clock_delta = snapshot.server_timestamp - client_timestamp;

When determining how far along into the interpolation the entity is, I simply add the difference to the client's current time.
The problem with this however, is that it will cause jerkiness because the difference between the two clocks will abruptly fluctuate due to snapshots arriving quicker/slower than others.

How can I synchronize the clocks closely enough that the only perceivable delay is that which is hard-coded for interpolation, and that which is caused by ordinary network latency?

In other words, how can I prevent interpolation from starting too late or too soon when clocks are significantly desynchronized, without introducing jerkiness?

Edit: According to Wikipedia, NTP can be used to synchronize clocks over the internet to within a matter of a few milliseconds. However, the protocol seems complicated, and perhaps overkill for use in games?