texts: How to convert png images to True Type Font?

texts:
I'm doing a clone of Colonization and I'm trying to use the same font type as the original game. I'm able to get the pixels from the original font files (.ff) using the application from this thread https://forums.civfanatics.com/threads/colonization-picture-viewer.256665/page-2 but the outcome is a PNG file.

The question is how I can convert this PNG file to a True Type Font that I can load on my MonoGame application? Is there a way to do that? Do I have to consider using one texture per letter rather than a font type? If this has sense, how can I set different font sizes using textures?


texts:
I've have a problem with HTML5 canvas and using multiple layers.

I'm using 3 layers. The first layer is where the player and the collision base objects are. And the second and the third layer have the rest of that objects, and that are suppose to cover the character if is behind them. But I have this problem:

The tile in the upper layer than the character cover him, even if he is in front of that object.

And I have other problem:

When is a the back of the element, there's a part of the character that appears in the middle of the poster.

How can I resolve this? I don't know how exactly do this, and I think that use layers is not very convenient.

Here's how I render the map:

function drawMap () {

for (var rowCtr = 0; rowCtr < map.tileMap[0].length; rowCtr++) {

    for (var colCtr = 0; colCtr < map.tileMap[0][0].length; colCtr++){

        var tileId  = map.tileMap[0][rowCtr][colCtr] - 1;
        var sourceX = Math.floor(tileId % 8) * 32;
        var sourceY = Math.floor(tileId / 8) * 32;

        ctx.drawImage(map.sprite.img, sourceX, sourceY, 32, 32, colCtr * 32, rowCtr * 32, 32, 32);

    }

}

finn.movement(this.ctx, this.world);

if (map.tileMap.length > 1) {

    for (var capa = 1; capa < map.tileMap.length; capa++) {

        for (var rowCtr = 0; rowCtr < map.tileMap[0].length; rowCtr++) {

            for (var colCtr = 0; colCtr < map.tileMap[0][0].length; colCtr++){

                var tileId  = map.tileMap[capa][rowCtr][colCtr] - 1;
                var sourceX = Math.floor(tileId % 8) * 32;
                var sourceY = Math.floor(tileId / 8) * 32;

                ctx.drawImage(map.sprite.img, sourceX, sourceY, 32, 32, colCtr * 32, rowCtr * 32, 32, 32);

            }

        }

    }

  }

}

And here's an example of the map:

  `[
    [0, 0, 0, 0],
    [0, 0, 0, 0],
    [0, 0, 0, 0],
    [0, 1, 1, 0]
   ],
   [
    [0, 0, 0, 0],
    [0, 1, 1, 0],
    [0, 1, 1, 0],
    [0, 0, 0, 0]
   ]`

That's the array of the layers. The first is the first layer, where the character moves, and the second element is the layer where the part of the objects which cover are drew.

Is there any solution for this without using any external Engine, only using canvas and javascript?

Thanks advance!


texts: Black border all around simulation / viewport in iOS using Xamarin + CocosSharp

texts:
I'm just getting started with Xamarin and CocosSharp so it's possible I've missed something basic here.. but whatever it is I can't seem to figure it out.

I'm trying to get my app/game to be fullscreen (I would prefer to see the status bar with connection, battery, and time.. but for now I'll settle for just full screen.

I'm editing this line:

CCScene.SetDefaultDesignResolution(1080, 1920, CCSceneResolutionPolicy.ShowAll);

And I've tried a bunch of different resolutions, but no matter what I do I can't get it to use the entire screen. As you can see in the image below, even if I enter a very large value for the height, it still does not use up the free space.

How do I make it so the game uses the entire screen, and if possible shows the statusbar?

If it makes any difference the program is set to portrait only.


texts: Sprite Animation Using Multiple Images (XNA / C#)

texts:
all.

Right now I am currently working on a game with my Australian buddy and I just am having such a difficult time with the spriting process.  As the programmer of our game, it is my responsibility to get the sprites he models drawn and animated onscreen.  However, the sprites he's drawing are huge images and the animation sequences are always at least 20 images wide, which means they're too big for the FileOpen method to read...  Which brings me to my question: Is there a way to use a directory as the animation sequence?  Like instead of stringing all the images together in a chain and animating the sequence, can I make an animation from a collection of the images in a folder?

For this example, use Animation.png to represent the chain of images version and Image1, 2, and 3.png for individual images in a directory.

Thanks in advance!


texts: How do I constrain a specific area of an actor to mouse X and Y?

texts:
I recently watched this tutorial "Actor Constraints in GameSalad" detailing how to constrain the center of an actor to the mouse X and Y, but I would like to constrain the relative clicked pixel of the actor to the mouse X and Y, not the center of the actor.

In other words, I want to avoid the "jumping" nature of "constrain self.Position.X to game.Mouse.Position.X" when I click and drag.


texts: Should I tell the player they have no chance of completing the level?

texts:
Suppose a player has reached a point where they have absolutely no chance of completing the current level, and must restart it and try again.

Should I notify them that they will gain nothing by continuing the level and needs to restart? If so, how should I tell them that? Would a message box of some sort saying something like "No chance, start again" be good? Or should I let them continue to play and find out themselves?

Note that the levels are not huge, and mostly take about a minute each to complete. So for example, if the user missed the opportunity to level up after 30 seconds or so, should I stop the game and make them restart?


texts: OpenGL vs DirectX difference from Graphics card perspective?

texts: I want to know the difference in purely hardware level if there is any. For example the most simple question: Is there a chip for DirectX and another chip for OpenGL? What do hardware producers do to make their cards DirectX or OpenGL compliant?


texts: Why is my AABB vs AABB code returning false positives

texts:
I am trying to do AABB vs AABB collision and the code is never finding a collision.

    private static boolean checkFullCollision(Entity entity, Entity entity1) {
    float[] amin = entity.getMin();
    float[] amax = entity.getMax();

    float[] bmin = entity1.getMin();
    float[] bmax = entity1.getMax();
    return  (amin[0] <= bmax[0] && amax[0] >= bmin[0]) &&
            (amin[1] <= bmax[1] && amax[1] >= bmin[1]) &&
            (amin[2] <= bmax[2] && amax[2] >= bmin[2]);
}

where I calculate my min and max.

    public float[] getMax() {
    final float[] max = new float[3];
    max[0] = position.x + this.max.x;
    max[1] = position.y + this.max.y;
    max[2] = position.z + this.max.z;
    //System.out.println(position);
    return max;
}

public float[] getMin() {
    final float[] min = new float[3];
    min[0] = position.x - this.min.x;
    min[1] = position.y - this.min.y;
    min[2] = position.z - this.min.z;
    return min;
}

Can someone help me please.

Thanks in advance


texts: Does the older Xbox 360 Elite support XNA 4?

texts: Can I develop an XNA 4.0 game for the older Xbox 360 Elite? Or would I need a newer Slim model?


texts: Unity - Apply different Near/Far clip plane value for different layer

texts:
I am Lerping the Near value of my camera, from 0 to 38, and it gives this result:
change near clip plane effect

As you see, it gives a nice effect. But now I would like the effect to occur only for one specific layer. How can I do that?


texts: Importing World of Warcraft models into Unity

texts:
I'm following some tutorials to create a simple game with Unity in order to learn, and I would like to enhance my learning experience by adding World of Warcraft models. Don't worry, this is all just for learning and won't see public eyes in any way.
I downloaded a model viewer and I can export textures and animation from WoW with it, but when importing into Unity I'm having some problems.

Which extension should I export the model to, and what is the process I should follow in order to have an object with a model I just exported?

I'm really new to Unity, so any help would be great!


texts: How can I create a screen-space distortion effect?

texts:
I am trying to create a screen-space distortion effect using shaders. This image demonstrating the effect I'm after is from Nvidia:

Let's consider that I have access to the background texture. How can I create this kind of effect? What should I do in the vertex and fragment function?

It seems that I need to retrieve screen-space normals of my object, but how?


texts:
I know this question has been asked a lot, but I never found an answer suitable for me. I have a game with a fairly big logic system and the movement system I am currently using is calling SDL_GetTicks() and measuring the delta time between the frames. I multiply the delta with the speed and I get the pixel movement. The problem with this is that the CPU usage is quite high. I didn't really mind it until my friend started going on about how it was "the end of the world".

The question I really want an answer to is if I should cap the framerate, and if a high CPU usage is unwanted (or even dangerous!).


texts:
My active tilemap surface is 5x5 tiles, and I try to limit the player's movement inside this area with the following code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Assertions.Must;

public class Movement : MonoBehaviour
{
    Vector2 pos;         // For movement
    float speed = 3f;   // Speed of movement
    public GridLayout grid;

    Vector2[] leftUpBorder = {new Vector2(-1f, 1f), new Vector2(-1.5f, 0.8f),  new Vector2(-0.5f, 1.3f) };
    Vector2[] leftDownBorder = {new Vector2(-1f, 0f), new Vector2(-1.5f, 0.3f), new Vector2(-0.5f, -0.3f) };
    Vector2[] rightUpBorder = {new Vector2(1f, 1f), new Vector2(1.5f, 0.8f), new Vector2(0.5f, 1.3f) };
    Vector2[] rightDownBorder = {new Vector2(1f, 0f), new Vector2(1.5f, 0.3f), new Vector2(0.5f, -0.3f) };

    Vector2 up = new Vector2(0f, 1.5f);
    Vector2 down = new Vector2(0f, -0.5f);
    Vector2 left = new Vector2(-2f, 0.5f);
    Vector2 right = new Vector2(2f, 0.5f);

    Vector2 AsVector2(Vector3 v)
    {
        return new Vector2(v.x, v.y);
    }

    void CMLeft() //Check, Move Left
    {
        if (Input.GetKey(KeyCode.A) && AsVector2(transform.position) == pos)
        {        // Left
            //pos += Vector3.left;
            pos += new Vector2(-0.5f, 0.25f);
        }
    }

    void CMRight()
    {
        if (Input.GetKey(KeyCode.D) && AsVector2(transform.position) == pos)
        {        // Right
            //pos += Vector3.right;
            pos += new Vector2(0.5f, -0.25f); // miscare in diagonala
        }
    }

    void CMUP()
    {
        if (Input.GetKey(KeyCode.W) && AsVector2(transform.position) == pos)
        {        // Up
            //pos += Vector3.up;
            pos += new Vector2(0.5f, 0.25f);
        }
    }

    void CMDown()
    {
        if (Input.GetKey(KeyCode.S) && AsVector2(transform.position) == pos)
        {        // Down
            //pos += Vector3.down;
            pos += new Vector2(-0.5f, -0.25f);
        }
    }

    void GoodMove()
    {
        if(pos == leftUpBorder[0] || pos == leftUpBorder[1] || pos == leftUpBorder[2])
        {
            CMUP();
            CMDown();
            CMRight();
        }
        else if (pos == rightUpBorder[0] || pos == rightUpBorder[1] || pos == rightUpBorder[2])
        {
            CMLeft();
            CMRight();
            CMDown();
        }
        else if (pos == leftDownBorder[0] || pos == leftDownBorder[1] || pos == leftDownBorder[2])
        {
            CMLeft();
            CMRight();
            CMUP();
        }
        else if(pos == rightDownBorder[0] || pos == rightDownBorder[1] || pos == rightDownBorder[2])
        {
            CMUP();
            CMDown();
            CMLeft();
        }
        else if (pos == left)
        {
            CMRight();
            CMUP();
        }
        else if (pos == right)
        {
            CMLeft();
            CMDown();
        }
        else if (pos == up)
        {
            CMDown();
            CMRight();
        }
        else if (pos == down)
        {
            CMLeft();
            CMUP();
        }
        else
        {
            PlayerMove();
        }

    }

void HitCheck()
    {
        RaycastHit2D hit = Physics2D.Raycast(pos, Vector2.up);
        if (hit.collider != null)
        {
            Debug.Log("Hit");
        }
    }

    void Start()
    {
        transform.position = new Vector3(0, 0.5f);
        pos = transform.position;          // Take the initial position
    }

    void FixedUpdate()
    {
        //PlayerMove();
        GoodMove();
        HitCheck();
        Debug.Log(grid.WorldToLocal(pos));
    }

However, the player gets stuck while moving to any border tile, and is unable to move anymore.


texts: Implementing a game loop with interpolation

texts:
I am trying to implement the Game Loop interpolated found in this website http://www.gameprogblog.com/generic-game-loop/. Here is my implementation:

long frameRate = 50000000;
int maxUpdates = 3;
boolean yield = true;

private long time =0;

private long lastTime;
private long currentTime;

public static float interpolation;

public void gameLoop() {

    long nanoElapsed = tick();

    System.out.println(time + "\t Framerate: " + frameRate + "\t"
            + "Nanoelapsed: " + nanoElapsed + "\t Interpolation: "
            + interpolation);

    time += nanoElapsed;
    int updateCount = 0;

    while (time >= frameRate && updateCount < maxUpdates) {
        game.update();
        updateCount++;
        time -= frameRate;
    }

    interpolation = getInterpolation();
    game.render();

}

long tick() {
    lastTime = currentTime;
    currentTime = TimeUtils.nanoTime();
    return currentTime - lastTime;
}

float getInterpolation() {
    return (float) ((double) time / (double) frameRate);
}

However I cannot figure out the problem I am having. I am logging most of the variables and for some reason the time variable is very big and does not stay in an acceptable range. It also decreases over time. I have spent a long time trying to figure out why and I'm now stuck. Any suggestions and help would be appreciated. Thanks


texts:
I wish to draw a texture to the screen line by line (horizontal lines).
Can I do this in xna?

At first I wish to just start at the top of the texture, draw one single horizontal line of pixels and x no of milliseconds later draw the next line and so on until the texture is fully drawn.
In the future I may want to draw these horizontal lines in any order.

Any ideas how best to achieve this?


texts: DirectX 11, using Tessellation & Geometry shader in a single pass

texts:
Before all, sorry for my poor english !

With DirectX 11, i'm trying to create a random map full with GPU.

Using Hull shader stage, I'm managing LOD with tessellation.

Using Domain shader stage, I'm generating the map (based on perlin noise).

Now my goal, is to compute normals in the geometry shader (normal on vertex).
For that, I must use vertex adjency, like geometry is capable of.

But here is the problem... For tessellation, my primitives must be
D3D11_PRIMITIVE_TOPOLOGY_3_CONTROL_POINT_PATCHLIST.

But for geometry shader with 6 vertex (triangle primitive and adjency), I must use :
D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST_ADJ.

Think I'm missing something... It must be possible to tessellate and use the results in the geometry shader...
However, it's working with 3 points, but I cannot use the 3 others (they are 0.0, 0.0, 0.0)....

Thank you in advance for any help ;)


texts: Where does Unity save Inspector properties for objects in a scene?

texts:
If I add a collection of objects to my scene and configure Inspector properties on those objects (like name, layer, tag, transform parameters, attached Components and their parameters), where does the information about those Inspector properties get saved within my project?

Is it all saved within the scene's .unity file or are there other files I should look at?


texts: Best way to make a Side Panel UI with Libgdx? (Java)

texts:
Take this image for example, the game is called Realm of the mad god, and it has this side panel filling the whole screen height with the player info.
To reproduce it, Is there any way to make the game "view" smaller so I can fit the side panel to its right without literally overlaying the game, PROBABLY like this game did, or is the only way out to overlay the game?
(Tibia might also be an example of a game smaller then its UI)


texts: How to round/smooth the path of an object/sprite that orbits around another object?

texts:
Below is a code that defines the values that cause the sprite to start at the top of the object being orbited:
Create Event:
ballSin=1;
ballCos=0;

ballSinMode=true;
ballCosMode=false;

Below is a code that modifies the values started in the previous code so that the sprite starts to rotate / orbit the object in a counterclockwise direction:
Step Event:
if(ballSinMode){
    ballSin-=0.05;

    if(ballSin==-1){
        ballSinMode=false;
    }
}else{
    ballSin+=0.05;

    if(ballSin==1){
        ballSinMode=true;
    }
}

if(ballCosMode){
    ballCos+=0.05;

    if(ballCos==1){
        ballCosMode=false;
    }
}else{
    ballCos-=0.05;

    if(ballCos==-1){
        ballCosMode=true;
    }
}

Draw Event:
draw_sprite(Sprite7,0,x+(75*ballCos),y+(-75*ballSin));

The object/sprite moves correctly, but the movement occurs as follows:

The movement I would like the object/sprite to perform:

I don't know why the object makes a straight movement. For me it would tend to always keep the same distance from the reference point (position of the object in the center). Since the movement is not circular, it does not. I would like to know why and how to make him move in the desired way.

OBS - Using the program's "path" feature is out of the question.


texts: Detecting right/left collisions with a bounding box

texts:
I'm building a platformer in cocos2d, my first game project. I'm working on movement and collision detection. I'm using a tilemap with a "meta" layer of invisible blocks that are designated collidable.

Everything seems to work pretty well except for one minor detail: when the character jumps from above into a platform, he does not fall but clips through it. If he jumps from below, it recognizes it and resets his Y velocity accordingly. I know that it's because of how I'm  detecting the collisions, and just doing a simple comparison of the origin.y's, but I'm unsure of how to refactor this code better:

- (void) update: (ccTime) dt {
    CGPoint scaledVelocity = ccpMult(leftJoystick.velocity, 35.0f);
    CGPoint newPosition = ccp(player.position.x + scaledVelocity.x * dt, player.position.y);
    CGPoint oldPosition = [player position];

    float velocityX = player.Velocity.x + scaledVelocity.x * dt;
    float velocityY = player.Velocity.y;

    BOOL isCollision = NO;
    BOOL isCollisionBelow = NO;
    BOOL isCollisionRight = NO;
    BOOL isCollisionLeft = NO;

    NSMutableArray* collisionSprites = [[NSMutableArray alloc] init];

    if (oldPosition.x > newPosition.x) {
        player.flipX = YES;
    }
    else if (oldPosition.x < newPosition.x) {
        player.flipX = NO;
    }

    for (CCSprite* sprite in gameplayLayer.collidableTiles) {
        if (CGRectIntersectsRect(player.boundingBox, sprite.boundingBox)) {
            isCollision = YES;
            [collisionSprites addObject:sprite];
        }
    }

    // Figure out which direction collision is in
    if (isCollision) {
        for (CCSprite* collisionSprite in collisionSprites) {
            if (collisionSprite.boundingBox.origin.y < player.boundingBox.origin.y) {
                isCollisionBelow = YES;
            }
            if ((collisionSprite.boundingBox.origin.x > player.boundingBox.origin.x) && (collisionSprite.boundingBox.origin.y >= player.boundingBox.origin.y)) {
                isCollisionRight = YES;
            }
            if ((collisionSprite.boundingBox.origin.x < player.boundingBox.origin.x) && (collisionSprite.boundingBox.origin.y >= player.boundingBox.origin.y)) {
                isCollisionLeft = YES;
            }
        }
    }

    if (isCollisionLeft) {
        velocityX = 0.5f;
    }
    else if (isCollisionRight) {
        velocityX = -0.5f;
    }

    if (isCollision && !isCollisionBelow && player.characterState != kStateFalling) {
        velocityY = 0;
        velocityY -= 0.8f;
        [player setCharacterState:kStateFalling];
    }
    else if (!isCollisionBelow) {
        velocityY -= 0.7f;
    }
    else if (isCollisionBelow) {
        velocityY = 0;
        [player setCharacterState:kStateIdle];
    }

    if (rightButton.active) {
        if (player.characterState != kStateJumping) {
            velocityY += 15.0f;
            [player setCharacterState:kStateJumping];
        }
    }

    // Ground friction
    if (player.Velocity.x > 0) {
        if (player.Velocity.x < 0.5f) {
            velocityX = 0;
        }
        else {
            velocityX -= 0.5f;
        }
    }

    if (player.Velocity.x < 0) {
        velocityX += 0.5f;
    }

    [player setVelocity:ccp(velocityX, velocityY)];
    [player setPosition: ccp(player.position.x + player.Velocity.x, player.position.y + player.Velocity.y)];
    [gameplayLayer setViewpointCenter:newPosition];
    [player setOldPosition: player.position];
}

How can I refactor this code to work properly from all angles and reduce the complexity (I feel that there's too many booleans, and they all get a bit confusing).


texts: javascript game character mouse movement

texts:
When a mouse button is pressed, coordinates are stored and character begins to move towards that point.

I do a check each frame if my character reached the destination, but because of the nature of how it all works, it can never be perfectly accurate. When I normalize my vector and multiply it by speed, I will always end up around that point but never directly at it. The bigger the speed, the more distance is passed in one frame and the further I get from where I wanted to be.

let startX = 110;
let startY = 110;
let endX  = 400;
let endY = 200;
let speed = 5;

let dx = endX - startX;
let dy = endY - startY;

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

dx /= length;
dy /= length;

dx *= speed;
dy *= speed;

So this gives me a dx:4.775320684056187 and dy:1.4819960743622644, so that is the value that is added each frame, so in the end it gets to coords 399:191 next one is 404:193 etc. I have to pick a close one, or force object to move to the one I wanted, it never reaches exactly 400:200.

It becomes a problem when path finding and collision comes to play, because I can get 2 pixels on an obstacle etc.

How is this solved? What am I doing wrong?


texts:
I'm very VERY new into the game development world and I had just some slight trouble wrapping my head around something.  We were told between classes just to think about how scaling matrices can perform simple orthogonal projections on a cardinal axis or plane.

What I know is orthogonal projections are 3D objects minus the z-coordinates in most cases.  Scaling matrices are a matter of altering x,y,z coordinates to adjust the shape of an object.  So, the only way for scaling to actually make a orthogonal projection is for the x,y,or z to be scaled by a factor of zero.  Am I kinda getting it so far or is there still a lot going over my head?


texts: Managing multiple references of the same game entity in different places using IDs

texts:
I've seen great questions on similar topics, but none that addressed this particular method:

Given that I have multiple collections of game entities in my [XNA Game Studio] game, with many entities belonging to multiple lists, I'm considering ways I could keep track of whenever an entity is destroyed and remove it from the lists it belongs to.

A lot of potential methods seem sloppy/convoluted, but I'm reminded of a way I've seen before in which, instead of having multiple collections of game entities, you have collections of game entity IDs instead.  These IDs map to game entities via a central "database" (perhaps just a hash table).

So, whenever any bit of code wants to access a game entity's members, it first checks to see if it's even in the database still.  If not, it can react accordingly.

Is this a sound approach?  It seems that it would eliminate many of the risks/hassles of storing multiple lists, with the tradeoff being the cost of the lookup every time you want to access an object.


texts: "Line of sight" path across navigation mesh

texts:
I want to calculate the line of sight in a navigation mesh.

Consider the image below, the yellow line is the result of only A* and the red line is the result of a line of sight" algorithm that uses the yellow line as input. Now the unit can move directly without “zig-zagging”.

What is an algorithm to calculate that "line of sight"?


texts: G-rated word lists in various languages for programming children's games

texts: I'm programming a word guessing game that uses large lists of words (no definitions, just words). Word length is configurable. Parents could set the word length to be very short and let small children play the game. I'd like to make sure there are no obviously obscene words in the list. For American English, the closest I've found was a Scrabble-like dictionary file that uniformly labelled questionable words with "obscene" so I can easily filter them out. Does anyone know of a better list in English, and/or any lists in other languages?


texts: This is what it looks like no matter the settings I use when I try to use shadows in Unity. Changing the Bias or the Normal Bias does effect the shadows, but I cannot get the shadows to be smooth with any settings. Making the model bigger does fix this, but I would optimally not scale the model up, as it is already at 10.


texts: Does Unity have a map size limit and if there is what is the limit? Is there a way to work around it? I am making a open world zombie survival world and I want to make a really big map. Thanks!


texts:
Thanks to this post: Hexagonal tiles and finding their adjacent neighbours, I'm able to collect adjacent tiles to a given tile.
But I'm pretty much stuck on an algorithm that gives me only a "ring" of tiles specified by an offset. The algorithm given in that Stack Overflow post doesn't exactly care about the order in which it collects the tiles.

I know that with every offset 6 tiles are added.

Offset 1 gives you 6 tiles (the first adjacent tiles).
Offset 2 gives you 12.
Offset 3 gives you 18, etc.

There is a constant growth of 6 with each offset. So I assume there should be a rule which adapts to these offsets. I can't exactly figure this one out. Anyone?


texts: How to render texture into box2d objects from Tile Map? Libgdx

texts:
I have a problem, when i try to render textures. I read positions of gameObjects, for example coin and create box2d objects circle shape. I have wrote game logic and began make a graphic. But for some reason, textures drawing not in box2d objects, but they shifted to the right and up as mini-map in games.

Code

  batcher.begin();

  sprite = new Sprite(AssetsLoader.coin);

  sprite.setPosition((body.getPosition().x - sprite.getWidth()/2), ((body.getPosition().y - sprite.getHeight()/2)));

  sprite.draw(batcher);
  batcher.end();

This is what happened

As you can see above, sprite position like body position. And something else: when i move my mainHero all rendered coins moving with him. On the screen they save their position, but in world they are moving. So how i can render coin texture exactly into box2d body.

May be something wrang with camera?

cam = new OrthographicCamera();

cam.setToOrtho(false, 400, 600);

or with Batcher?

batcher = new SpriteBatch();

batcher.setProjectionMatrix(world.getCamera().combined);

I will not give all my code, because it is big and no one will try to understand it.I need an idea or just an advice or a hint. Sorry for my English, hello everyone from Belarus :) Where do I look and what a start? Thank you.


texts: Which toolkit to use for 3D MMO game development?

texts:
Lately i've been thinking about which path to follow for developing an 3D Online game.
I have googled a lot but i couldnt find a good article that covers both game development and online server & client development in same context.
This question has been in mind for about 2 weeks now.
So.. yesterday i started developing a game from scratch by using
Irrlicht.Net Wrapper to use Socket library of .NET which im already familiar.
But i found out .Net wrapper of Irrlicht is not totally finished yet and still have lacks from the original.
So i lost all my motives :/.

So i thought why not to ask the experts before i run into another dead end...

What Game Engine and Networking Library is best way to go for 3D MMO Development?

Here is some of my early conclusions:
Please let me know the ones im wrong.

C++:

Best Performance for 3D Graphics.
Most Game Engines has native C++ Libraries.
Lacks a Solid Socket Library
.NETC++ Lacks Intellisense Support.

C#:

Intellisense Support
NET Socket Library
Lacks 3D Graphics Performance
Lacks a native solid 3D Game Engine


texts: How to determine the angular velocity needed move an object to a given position

texts:
I am trying to move two lines joint to a fixed position sprite in a way similar to that of a pendulum. I would like the lines to swing from end to end each time. The image below shows what I want to achieve:

I'm moving the lines using angular velocity, but I'm not getting the pendulum/swinging effect (a cycle of the lines generally swinging faster as they move to the center and slowing down a bit when they change from one direction to another). I rather get some brisk movement then it slows down till the movement stops. Please see my SpriteKit code below:

extension Int {
  var degreesToRadians: Double { return Double(self) * .pi / 180 }
}
extension FloatingPoint {
  var degreesToRadians: Self { return self * .pi / 180 }
  var radiansToDegrees: Self { return self * 180 / .pi }
}

class GameScene: SKScene, SKPhysicsContactDelegate {

var anchorSprite = SKSpriteNode(imageNamed: "swingPin")
var armLeft = SKSpriteNode(imageNamed: "swingArm")
var armRight = SKSpriteNode(imageNamed: "swingArm")

override func didMove(to view: SKView) {

self.physicsWorld.gravity = CGVector(dx: 0, dy: -1.8)
self.physicsWorld.contactDelegate = self

var tealBg = SKSpriteNode(imageNamed: "tealBg")
tealBg.position = CGPoint(x: frame.midX, y: frame.midY)
tealBg.zPosition = 10
addChild(tealBg)

anchorSprite.position = CGPoint(x: frame.midX, y: frame.midY + frame.midY/2)
anchorSprite.zPosition = 20

anchorSprite.physicsBody = SKPhysicsBody(rectangleOf: anchorSprite.frame.size)
anchorSprite.physicsBody?.categoryBitMask = pinCategory
anchorSprite.physicsBody?.isDynamic = false
addChild(anchorSprite)

armRight.anchorPoint = CGPoint(x: 0.5, y: 1)
armRight.position = anchorSprite.position
armRight.zPosition = 20
armRight.physicsBody = SKPhysicsBody(rectangleOf: armRight.frame.size)
armRight.zRotation = CGFloat(Double(15).degreesToRadians)//CGFloat(Double.pi/6)
armRight.physicsBody!.isDynamic = true

addChild(armRight)

armLeft.anchorPoint = CGPoint(x: 0.5, y: 1)
armLeft.position = anchorSprite.position
armLeft.zPosition = 20
armLeft.physicsBody = SKPhysicsBody(rectangleOf: armRight.frame.size)
armLeft.zRotation = CGFloat(Double(-15).degreesToRadians)//CGFloat(-Double.pi/6)
armLeft.physicsBody!.isDynamic = true
addChild(armLeft)

// Create joint between two objects
//Pin joint
var pinAndRightArmJoint = SKPhysicsJointPin.joint(withBodyA: anchorSprite.physicsBody!, bodyB: armRight.physicsBody!, anchor: CGPoint(x: anchorSprite.position.x, y: self.armRight.frame.maxY))
self.physicsWorld.add(pinAndRightArmJoint)

var pinAndLeftArmJoint = SKPhysicsJointPin.joint(withBodyA: anchorSprite.physicsBody!, bodyB: armLeft.physicsBody!, anchor: CGPoint(x: anchorSprite.position.x, y: self.armLeft.frame.maxY))
self.physicsWorld.add(pinAndLeftArmJoint)

var fixArms = SKPhysicsJointFixed.joint(withBodyA: armLeft.physicsBody!, bodyB: armRight.physicsBody!, anchor: CGPoint.zero)
self.physicsWorld.add(fixArms)

pinAndRightArmJoint.shouldEnableLimits = true
pinAndRightArmJoint.lowerAngleLimit = CGFloat(Double(-60).degreesToRadians)
pinAndRightArmJoint.upperAngleLimit = CGFloat(Double(60).degreesToRadians)

}

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
armRight.physicsBody?.angularVelocity = -100.0

}

Please note that though I believe this is the most appropriate approach to my problem, I'm open to another approach that would help me achieve the same result.


texts: What is wrong with this character slope math?

texts:
I'm making a sidescrolling platformer and have implemented some code that should convert the characters speed to an X speed and Y speed based on the angle of the surface they are on. This actual math for this was taken from a web page and I don't know if it's right or not.

// xSpeed and ySpeed are derived from speed, based on the angle
    xSpeed = speed * Mathf.Cos(angle);
    ySpeed = (speed * -Mathf.Sin (angle)) - gravity;

The angle is found with this code:

RaycastHit ground;
    Physics.Raycast (transform.position, Vector3.down, out ground, 1.5f);
    Debug.DrawRay (transform.position, Vector3.down.normalized, Color.green, 2, false);
    if (ground.collider != null)
    {
        angle = Vector3.Angle (ground.normal, Vector3.up);
    }
    else
    {
        angle = 0;
    }

This works fine when walking on a flat surface, but freaks out when walking on a slope. I believe the problem lies with the angle itself.


texts:
I have 2 images that are .png and they mix together, The problem is that one overwrite the other. I know that the draw order matters, but In that case I should redraw the icons 2 times ( there is a lot of them)

the black is in fact transparent and drawing a star on top of the other "cuts" a part of the underlying one, In other words, it overwrites with transparency

How I see it now

How I want to see it

My blending code :

    GLES20.glActiveTexture(GLES20.GL_TEXTURE0);
    GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, mMarcaDataHandle);

    GLES20.glEnable(GLES20.GL_BLEND);
    GLES20.glBlendFunc(GLES20.GL_SRC_ALPHA, GLES20.GL_ONE_MINUS_SRC_ALPHA);

    Matrix.setIdentityM(mModelMatrix, 0);
    aplicarRotacion();
    Matrix.translateM(mModelMatrix, 0, marcador.posX, marcador.posY, marcador.posZ);

    drawMarca();

    GLES20.glDisable(GLES20.GL_BLEND);

private void drawMarca()
{
    coordinate.drawMarca(mPositionHandle, mNormalHandle, mTextureCoordinateHandle);

    // This multiplies the view matrix by the model matrix, and stores the
    // result in the MVP matrix
    // (which currently contains model * view).
    Matrix.multiplyMM(mMVMatrix, 0, mViewMatrix, 0, mModelMatrix, 0);

    GLES20.glUniformMatrix4fv(mMVMatrixHandle, 1, false, mMVMatrix, 0);

    Matrix.multiplyMM(mMVPMatrix, 0, mProjectionMatrix, 0, mMVMatrix, 0);

    GLES20.glUniformMatrix4fv(mMVPMatrixHandle, 1, false, mMVPMatrix, 0);

    GLES20.glDrawArrays(GLES20.GL_TRIANGLES, 0, 6);
}


texts: Is storing all game objects in a single list an acceptable design?

texts:
For every game I've made, I just end up placing all my game objects (bullets, cars, players) in a single array list, which I loop through to draw and update. The update code for each entity is stored within it's class.

I've been wondering, is this the right way to go about things, or is a faster more efficient way?


texts: NullReferenceException in save game function

texts:
I was making save system to save position of player.

I get an exception:

  NullReferenceException: Object reference not set to an instance of an object

It comes from this line: FloatPos[0] = DataG.transform.position.x;

Here is my Save Manager:

[System.Serializable]
public class SaveManger
{
    public float[] Player, Top, Ground, ET, ED;
    public int PN, PCN;

    public SaveManger(SaveGame SaveGame)
    {
        PosMath(Player, SaveGame.PlayerPos);
        PosMath(Top, SaveGame.TopPos);
        PosMath(Ground, SaveGame.GroundPos);
        PosMath(ET, SaveGame.EfTop);
        PosMath(ED, SaveGame.EFDown);

        PN = SaveGame.TransformMover.GetComponent<TransformMover>().PuzzleNumper;
        PCN = SaveGame.TopPos.GetComponent<PuzzleSetUp>().PuzzleCloneNumper;
    }

    public void PosMath(float[] FloatPos, GameObject DataG)
    {
        FloatPos[0] = DataG.transform.position.x;
        FloatPos[1] = DataG.transform.position.y;
        FloatPos[2] = DataG.transform.position.z;
    }
}

Here is my saved game component:

public class SaveGame : MonoBehaviour
{

    public GameObject PlayerPos,TopPos,GroundPos,EfTop,EFDown,TransformMover;

    public void Start()
    {
        string path = Application.persistentDataPath + "/GSave.GSF";
        if(File.Exists(path))
        {
            LoadButton();
        }
        else
        {

        }
    }

    public void SaveButton()
    {
        SAVESYSTEM.VoidSaver(this);

    }

    public void LoadButton()
    {
        SaveManger Data = SAVESYSTEM.LoadSave();

        TransformMover.GetComponent<TransformMover>().PuzzleNumper = Data.PN;
        TopPos.GetComponent<PuzzleSetUp>().PuzzleCloneNumper = Data.PCN;
    }
}


texts: How do I spawn an enemy at one of many spawn points in Unity?

texts:
I have a spawn script that so far only creates one Enemy spawn point and enemy trigger while only spawning one enemy.

Instead, I want it to create multiple spawns and triggers, but keep it such that only one enemy spawns at a time, at a random on of the spawn points.

How can I do this?

Here's the relevant code at the moment:

public class SpawnManager : MonoBehaviour {

    public GameObject Enemy; // the enemy prefab
    public float mytimer; // the time to wait before spawn

    private GameObject _spawndEnemy; // the enemy that was spawnd

    void SpawnEnemy()
    {
        var enemySpawnPoint =  GameObject.Find("FFEnemySpawn1").transform;
        _spawndEnemy = Instantiate(Enemy, enemySpawnPoint.position, enemySpawnPoint.rotation) as GameObject;
    }

    void OnTriggerEnter(Collider other)
    {
        if (other.gameObject.name == "FFMirror1") {
            mytimer = Random.Range(0,15);
            Destroy(_spawndEnemy);
            Invoke("SpawnEnemy", mytimer);
            Debug.Log("Spawn Normal");
        }

    }
}


texts: Interfacing with bill/note acceptors in unity

texts: What ways are there to interface a unity game with a bill acceptor/validator? Usually this type of devices are connecting to a computer using a serial port and communicate over ccTalk protocol. But what ways exist of incorporating this type of devices in Unity?


texts: OpenGL ES 1.1 - How to batch draw particles with different translations?

texts:
Assuming that I've combined all of my vertex data for many particles into a single array, how would I batch draw all of those particles in a manner that preserves their unique translations?

Any code examples would be greatly appreciated.


texts: What are the benefits of using an entity ID system?

texts:
I'm currently reading the book Programming Game AI By Example.

The book mentions assigning unique ID numbers to each entity in the game. Often when entity A needs to contact entity B, A gets a reference to B by sending B's ID number to an EntityDatabase class. This class recieves ID numbers and returns references to the entities.

The ID numbers of some entities could also be fetched from a file containing the IDs of some of the entities (the main game characters).

My question is: Why would I do this? Why can't I work directly with references? Is it sometimes difficult to get a direct reference? Is using an ID system a common approach? Are there games that don't use IDs?

I'm new to game development. Please explain the benefits of working with an entity ID system. The advantages and disadvantages. Concrete examples would be great. Thanks


texts:
I have no idea what the title of this question should be so bare with me.

My game has turns. On a turn a player does something and this can result in a random number of explosions that occur at different times. I know when the explosions are done. I need to know when ALL are done and then do some other action. Also, each explosion is the same amount of time, say 3 seconds..

Right now I'm thinking of using a counter to hold how many explosions are happening. Then once the explosion is finished decrement this counter. Once the counter is zero, do my action. This idea is inspired by objective-c memory management btw. Anyways, does this sound like a good approach or would there be another way.

An alternative might be to figure out the explosion who happened last and let it be responsible for calling this subsequent action.

I'm asking mostly, because I haven't done this before and am trying to figure out if there are bugs that may occur that I'm not foreseeing.


texts: about register reserved word or sementic in HLSL

texts:
I'm studying HLSL cookbook. In that sample code, author used a lot of register sementic.

like this

cbuffer cbPointLightDomain : register( b0 )
{
    float4x4 LightProjection : packoffset( c0 );
}

cbuffer cbPointLightPixel : register( b1 )
{
    float3 PointLightPos : packoffset( c0 );
    float PointLightRangeRcp : packoffset( c0.w );
    float3 PointColor : packoffset( c1 );
    float2 LightPerspectiveValues : packoffset( c2 );
}

what is benefit of this?

actually I erased every register keywords and ran program.

the result is completely fine.


texts: Mythbuster: Mirror Operation with Quaternion

texts:
Mirror operation : all vertex positions must be reflected by a specific plane (here YZ).Synonyms: FlipHorizontal, SymmetryX, MirrorX,

What implementations I already know that work:
1) Multiplying by -1 scale.
Unfortunately that is not allowed in unity because it messes with physics and lighting.
2) Vertex Manipulation. Yes, it works!!!

And now here comes the "Myth" from mr. evil person...
Mirror operation can be implemented if you get a "lucky" quaternion rotation. He says that:
a) if "euler rotation" suffers from Gimbal Lock, and Quaternion doesnt.
b) Then If quaternion (Matrix 4x4) cannot represent mirror operation, then increasing the #dimensions to Pentaternion (Matrix 5x5), Or Hexaternion (Matrix 6x6) is sure to solve the problem.

Note: I am not looking for "Reverse" operation (15 degree rotation converted to (360-15) degree rotation at that axis). I am looking for a way to "free" my model from those rotation limiting axes... I tried everything but couldn't achieve "Red" projection with a quaternion, maybe I miss something...

Is he right ? Or a quaternion cannot implement reflection and that myth is Busted?

Unity allows me to use all transform operations (Translation, Rotation, Instancing) but not scaling (messes up physics and lighting).


texts: Building 2D Assets for a Game Targeting Multiple Framerates

texts:
To make a real-world example, lets assume I want to build an animated sprite for an explosion. The duration of the animation should last ~1 second, and we'll say exactly one second to make the math a bit more simple. And lets assume I'm using XNA and my goal is to target both XBox (60fps), PC (60fps), and Windows Phone 7 (30fps).

My question is this, how should I build the sprite animations so that my programming is as simple as possible without simply using a timer to calculate which frame I should be on (which I feel would make the animation "choppy")?


texts: Game Maker 8 high score table pixel size

texts: How big is the high score table in Game Maker 8? I wanted to make a background image for the table but each time I do the background is either too big or too small and makes it blurry.


texts:
Is it possible to automacicaly random rotate pefab during placement in editor in unity 4.5.3?

I can make it autorotate in game(at start) but I want it to be visible in editor and at fixed rotation after placement.


texts:
I've had this issue many a time, unfortunately anything I've used to fix it before doesn't work. So, if I build and run the app, it will run the app for about 5 seconds, before crashing. If I install the apk and try and run it, it will crash immediately.
I cannot for the life of me figure out what's wrong, this is an app I've built with no issues a hundred times, I am pretty certain I never changed any player settings since then, I did, however, reinstall the unity version as I had an issue with the android SDK because it didn't install properly.
I ran logcat in the Android Studio, and the only errors of note I could find are invalid vkGetInstanceProcAdd and Connecting to host time out, player connection will be disabled?
However, it does seem to initialize the app through Android studio.
Here is a pastebin of my logcat, filtered to only include unity related issues.
https://pastebin.com/buRGfjXa
Thanks in advance.


texts:
I followed the official step-by-step "Visual Studio Code and Unity" guide, but it seems I messed up something, because Intellisense doesn't see any Unity related stuff.

Like the MonoBehaviour class and its members (like .transform), or the Unity callbacks, like Start or Update.


texts:
How to add shortcut key to add new empty already with a box/circle collider ?

If possible, it would be nice that empties are enumerated.


texts:
My question is simple: how much memory on GPU does one floating point value takes? I guess it is 4 bytes, but I'm not sure.
So for example is it true that vec4, which holds 4 floats, each 4 bytes takes 16 bytes in sum.

I know this is very basic, maybe I've missed some point.

Thank you in advice.


texts: Causing Update loop with Coroutine Unity

texts:
Total Noob Alert! < 7 days with C# and Unity

My Win Game screen becomes SetActive and my Player is SetActive false when you are standing in a trigger and crouch. That all works fine except you cant see the crouch animation because he is IMMEDIATELY SetActive false.

I tried to delay this by creating a coroutine. The problem with that is this is all happening in the Update function (or whatever it's called) because of the getkeydown for crouch. That gets called once per frame so my coroutine is trying to go off once per frame.

I tried creating a bool called isCoroutineStarted and set it to false and then set it to true in the Coroutine to break the loop but that didn't work either.

Don't know what to do so I reverted it back to before where it doesn't show my crouch animation.

Here's my script (It's attached to a Game Object with the trigger):

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

public class xxxxxx : MonoBehaviour {

    public bool xxx = false;

    [SerializeField]
    private GameObject youWinUI;

    [SerializeField]
    private GameObject player;

    // Determines whether or not the player is standing on the xxxxx
    void OnTriggerEnter2D (Collider2D other)
    {
        xxx = true;
    }

    void OnTriggerExit2D (Collider2D other)
    {
        xxx = false;
    }

    //Turns on Win screen and makes player disappear when crouch on xxx
    void Update ()
    {
        if (Input.GetKeyDown (KeyCode.S) && xxx == true) {
            youWinUI.SetActive (true);
            player.SetActive (false);
        }
    }
}

P.S. ignore the x's no stealsies lol. Also this piece of script works as intended I just want a delay so you can see the crouch animation.


texts: How do you remove a tile from a scene in stencyl?

texts: I have added tiles to a scene in stencyl. Now I have changed my mind and I can't seem to remove them! What do I click? I don't see the instructions in here.


texts: Why does my MonoGame mesh throw an unhandled exception when trying to draw?

texts:
I am using the '3D Models' chapter of Learning XNA 4.0 to further understand 3D implementation in XNA, but I am running into an unhandled exception, when I try to draw each mesh.
Here is my basic Draw() function. It determines the amount of mesh transforms inside my model, and proceeds to draw each one, using a default BasicEffect.
public virtual void Draw(Camera camera)
{
    Matrix[] transforms = new Matrix[model.Bones.Count];
    model.CopyAbsoluteBoneTransformsTo(transforms);

    foreach (ModelMesh mesh in model.Meshes)
    {
        foreach (BasicEffect effect in mesh.Effects)
        {
            effect.EnableDefaultLighting();
            effect.Projection = camera.projectionMatrix;
            effect.View = camera.viewMatrix;
            effect.World = GetWorld() * mesh.ParentBone.Transform;
        }

        mesh.Draw();
    }
}

When I attempt to run, I get stopped at mesh.Draw();, with the error

An unhandled exception of type 'System.InvalidOperationException' occurred in MonoGame.Framework.dll
Additional information: An error occurred while preparing to draw. This is probably because the current vertex declaration does not include all the elements required by the current vertex shader. The current vertex declaration includes these elements: SV_Position0, TEXCOORD0, COLOR0.

The model was provided by our lecturer. I have confirmed that the model shouldn't have any problems drawing. I have also found a similar issue to the one I am having, on the MonoGame forums, however the user reported having a current vertex declaration that includes "SVPOSITION0, TEXCOORD0, COLOR0", and the solution appeared to be changing "SVPOSITION0" to "SV_Position0".
While I am unsure how to directly change the vertex declaration, it appears I should already have the correct vertex declaration.
Why won't my mesh draw?
If I remove the effect.EnableDefaultLighting() line, it works, no problem. However, I then do not have light, and everything comes up as black. If I replace my ground.x model with the spaceship.x model supplied by Microsoft, it works with lighting. I presume my issue is with my model, however, I can not access spaceship.x to read in plain english, as I can with my ground.x.
Ground.x
xof 0303txt 0032
template Vector
{
    <3d82ab5e-62da-11cf-ab39-0020af71e433>
    FLOAT x;
    FLOAT y;
    FLOAT z;
}

template MeshFace
{
    <3d82ab5f-62da-11cf-ab39-0020af71e433>
    DWORD nFaceVertexIndices;
    array DWORD faceVertexIndices[nFaceVertexIndices];
}

template Mesh
{
    <3d82ab44-62da-11cf-ab39-0020af71e433>
    DWORD nVertices;
    array Vector vertices[nVertices];
    DWORD nFaces;
    array MeshFace faces[nFaces];
    [...]
}

template Coords2d
{
    <f6f23f44-7686-11cf-8f52-0040333594a3>
    FLOAT u;
    FLOAT v;
}

template MeshTextureCoords
{
    <f6f23f40-7686-11cf-8f52-0040333594a3>
    DWORD nTextureCoords;
    array Coords2d;
    textureCoords[nTextureCoords];
}

Mesh
{
     4;
     65536.00000;0.000000;-65536.00000;,
     -65536.00000;0.000000;-65536.00000;,
     -65536.00000;0.000000;65536.00000;,
     65536.00000;0.000000;65536.00000;;
     2;
     3;0,1,2;,
     3;0,2,3;;

    MeshTextureCoords
    {
         4;
         0.000000;0.000000;,
         0.000000;1024.000000;,
         1024.000000;1024.000000;,
         1024.000000;0.000000;;
    }

    MeshMaterialList
    {
        1;
        2;
        0,
        0;

        Material
        {
            0.800000;0.800000;0.800000;1.000000;;
            0.000000;
            0.000000;0.000000;0.000000;;
            0.000000;0.000000;0.000000;;

            TextureFilename{"sanddf.png";}
        }
    }
}


texts: Say i have 10 towns in my world map. the world map right now is just a very large Tilemap. I'm curious as to what the standard is. I think it would be much more efficent to have a Tilemap for each town. If i want to walk from one town to another in the large tilemap I dont have an issue, but how can i do this if i had a Tilemap for each town? when is it best to load the upcoming Towns Tilemap?


texts:
Currently i'm using Unity3D, and i want to make one variable blink along time in a fragment shader. Now i have code like this:

    half4 frag(v2f i) : COLOR{
        float4 r = _OutlineColor;
        r.a = r.a * _SinTime ;
        return r;
        }

But this blinking is too slow and not suit me, any ideas ?


texts:
I'm currently a (happily employed) automated software tester that's curious about game testing/QA. Do game companies hire dedicated testers for pay? If yes, then what are the job prospects like? If no, then how does becoming a game tester work (volunteers? mixed roles? crowdsourcing?). Obviously game companies have full-time devs, artists, designers, managers, etc. but what does QA look like?

NOTE: I'm curious about how QA works in a game dev setting, but I'm not really looking for job tips or "Do this if you want to get into game QA".


texts: What is a "tick" in the context of game development?

texts: Ok so this is a very beginner level question but I need to know this, what does the term "tick" refer to in the context of game development? Is it the same thing as FPS? Thanks!


texts: Does triangle-plane clipping in 3D always produce a triangle?

texts: When you clip a triangle against a plane, will you always get a triangle out? Are there perhaps cases where you don't get a triangle out of clipping it against a plane?


texts: Collision detection with XNA and TiledLib

texts:
I recently started learning XNA and after getting annoyed with creating individuals rectangles each time I wanted to add something I went with TiledLib so I could more easily create levels using the Tiled map editor. My problem is, though, I have no idea how to check for collision using TiledLib. There is very little documentation on it and where people have solved the problem it seems like the code they provide is outdated.

For those who do not know TiledLib: https://bitbucket.org/nickgravelyn/tiledlib

I'm using mostly the code that comes in the demo (such as Map.cs/MapProcessor.cs) because I don't know too much how it works, but it does the job.

I've heard to detect for collision I should use a seperate layer that contains all the tiles I want to collide with, but aside from updating the map to accomdate that I don't know how to actually check for that in my code and make those tiles collide with things. Also, attempting to add a layer to my tile map and then running my game provides this error:

Error   1   Building content threw ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
   at System.ThrowHelper.ThrowArgumentOutOfRangeException()
   at System.Collections.Generic.List`1.get_Item(Int32 index)
   at PlatformerContentPipeline.MapProcessor.Process(MapContent input, ContentProcessorContext context) in e:\Platformer\Platformer\PlatformerContentPipeline\MapProcessor.cs:line 94
   at Microsoft.Xna.Framework.Content.Pipeline.ContentProcessor`2.Microsoft.Xna.Framework.Content.Pipeline.IContentProcessor.Process(Object input, ContentProcessorContext context)
   at Microsoft.Xna.Framework.Content.Pipeline.BuildCoordinator.BuildAssetWorker(BuildItem item)
   at Microsoft.Xna.Framework.Content.Pipeline.BuildCoordinator.BuildAsset(BuildItem item)
   at Microsoft.Xna.Framework.Content.Pipeline.BuildCoordinator.RunTheBuild()
   at Microsoft.Xna.Framework.Content.Pipeline.Tasks.BuildContent.RemoteProxy.RunTheBuild(BuildCoordinatorSettings settings, TimestampCache timestampCache, ITaskItem[] sourceAssets, String[]& outputContent, String[]& rebuiltContent, String[]& intermediates, Dictionary`2& dependencyTimestamps, KeyValuePair`2[]& warnings)   e:\Platformer\Platformer\Platformer\PlatformerContent\level1.tmx    Platformer

I'm at a loss at what to do. If anyone could help me with this, or perhaps let me know of a more updated and more well documented 2D engine for C#/XNA, that would be great.


texts: How to make inventory pause screens in Gamemaker?

texts: I'm making a game in Game Maker, and I want to know how to make it so you can pause into an inventory screen and then go back to the same position you were in (also the same room) after you press a back button. It would also be great if all the dead enemies were dead and the alive ones were at the same position also.


texts:
I'm an experienced programmer that recently got into iOS development by working through the big nerd ranch book by Aaron Hillegass and Joe Conway. I loved the way the book was structured in terms of typing in the code and doing the challenges.

I'm interested in learning more about iOS gaming and cocos2d, but am a complete newbie in terms of game development/design. There are a number of books on amazon on cocos2d, can anyone recommend one in particular?


texts: How can I check if the text string is not equal and then to do something?

texts:
using UnityEngine;

public class DrawLines : MonoBehaviour
{
    public LineRenderer lineRenderer;
    public string text;

    private Vector3[] positions;
    private string oldText;

    private void Start()
    {
        if (lineRenderer == null)
        {
            lineRenderer = GetComponent<LineRenderer>();

            lineRenderer.startWidth = 0.3f;
            lineRenderer.endWidth = 0.3f;
        }

        // 0,  0, 0
        // 5,  0, 0
        // 5, -5, 0
        // 0, -5, 0

        positions = new Vector3[5] { new Vector3(0, 0, 0), new Vector3(5, 0, 0),
            new Vector3(5, -5, 0), new Vector3(0, -5, 0), new Vector3(0, 0, 0)};
        DrawLine(positions, Color.red, 0.2f);
    }

    void DrawLine(Vector3[] positions, Color color, float duration = 0.2f)
    {
        GameObject myLine = new GameObject();

        myLine.transform.position = positions[0];
        myLine.AddComponent<LineRenderer>();
        LineRenderer lr = myLine.GetComponent<LineRenderer>();
        lr.positionCount = positions.Length;
        lr.startColor = color;
        lr.endColor = color;
        lr.startWidth = 0.1f;
        lr.endWidth = 0.1f;
        lr.useWorldSpace = false;
        lr.SetPositions(positions);
    }

    void DrawText()
    {
        for (int i = 0; i < positions.Length; i++)
        {
            if (oldText != text)
            {
                var pos = Camera.main.WorldToScreenPoint(positions[i]);
                text = positions[i].ToString();
                var textSize = GUI.skin.label.CalcSize(new GUIContent(text));
                GUI.contentColor = Color.red;
                GUI.Label(new Rect(pos.x, Screen.height - pos.y, textSize.x, textSize.y), text);
                GUI.contentColor = Color.green;
                GUI.Label(new Rect(pos.x, Screen.height - pos.y - 20, textSize.x, textSize.y), i.ToString());
            }
        }
    }

    private void OnGUI()
    {
        if (positions != null)
        {
            if (positions.Length > 0)
            {
                DrawText();
            }
        }
    }
}

I added oldText variable but not sure how use it more then I did so far.
I want that if the text is the same in the loop then don't show this text not in red not in green.
Each time show the text once if it's not equal.

When the square is closed :


texts: Unity : Android Button : Select (Highlight) by touch, before clicking

texts:
I have a multiplatform game with dozens of buttons in many menus.

I used the animated buttons setup to have a normal state and highlight state. Highlight will most of the time resize the button with a nice anim AS WELL as make a dedicated text box appear with extra information. So far so good. Everything works perfectly on PC.

However, as I am testing my build on android, I cannot find how to access the "highlight" state since touching the screen = click and it execute the on click () associated.

What I need is a way to select a button when it is first touched, since selected = highlight (somewhat) then if it is touched (clicked) a second time while selected then to do the on click ( ) function.

I have a few theory on how to do it, but it would require recreating every of my 80 or so buttons as well as changing everything from using the Unity GUI system to make my own C# version which would take weeks.

I am also trying a few other way to achieve the same thing. One of which is using the "button.select()" to select the button on its first click. That works. problem is I cannot seem to write a way to do:
"if (thisbutton.IsSelected == true)" that just refuses to work.


texts: Getting proper shadows in my Disolve shader

texts:
So I wipped up this shader that disolves an object. The problem is that the shadow of the object is unaffected from the alpha value. How do I fix this. Full code :

Shader "Custom/SwordDistortion" {
    Properties {
        _Color("Color", Color) = (1,1,1,1)
        _MainTex("Albedo (RGB)", 2D) = "white" {}
        _DissolveScale("Dissolve Progression", Range(0.0, 1.0)) = 0.0
        _DissolveTex("Dissolve Texture", 2D) = "white" {}
        _GlowIntensity("Glow Intensity", Range(0.0, 5.0)) = 0.05
        _GlowScale("Glow Size", Range(0.0, 5.0)) = 1.0
        _Glow("Glow Color", Color) = (1, 1, 1, 1)
        _GlowEnd("Glow End Color", Color) = (1, 1, 1, 1)
        _GlowColFac("Glow Colorshift", Range(0.01, 2.0)) = 0.75
        _DissolveStart("Dissolve Start Point", Vector) = (1, 1, 1, 1)
        _DissolveEnd("Dissolve End Point", Vector) = (0, 0, 0, 1)
        _DissolveBand("Dissolve Band Size", Float) = 0.25
    }
    SubShader {
        Tags {
        "Queue" = "Transparent"
        "RenderType" = "TransparentCutout"
    }

        CGPROGRAM
        // Physically based Standard lighting model, and enable shadows on all light types
        #pragma surface surf Standard addshadow alpha:fade
        #pragma vertex vert
        // using shader model 4.6 for even nicer lighting
        #pragma target 4.6

        sampler2D _MainTex ;
        sampler2D _DissolveTex ;
        float _DissolveScale;
        float3 _DissolveStart;
        float3 _DissolveEnd;
        float _DissolveBand;
        float _GlowIntensity;
        float _GlowScale;
        float _GlowColFac;
        fixed4 _Color;
        fixed4 _Glow;
        fixed4 _GlowEnd;
        struct Input {
            float2 uv_MainTex;
            float3 dGeometry;
        };

        //Precompute dissolve direction.
            static float3 dDir = normalize(_DissolveEnd - _DissolveStart);

        //Precompute gradient start position.
        static float3 dissolveStartConverted = _DissolveStart - _DissolveBand * dDir;

        //Precompute reciprocal of band size.
        static float dBandFactor = 1.0f / _DissolveBand;

        void vert(inout appdata_full v, out Input o)
        {
            UNITY_INITIALIZE_OUTPUT(Input, o);

            //Calculate geometry-based dissolve coefficient.
            //Compute top of dissolution gradient according to dissolve progression.
            float3 dPoint = lerp(dissolveStartConverted, _DissolveEnd, _DissolveScale);

            //Project vector between current vertex and top of gradient onto dissolve direction.
            //Scale coefficient by band (gradient) size.
            o.dGeometry = dot(v.vertex - dPoint, dDir) * dBandFactor;
        }

        void surf (Input IN, inout SurfaceOutputStandard o) {
            fixed4 c = tex2D(_MainTex, IN.uv_MainTex) * _Color;
            half dBase = -2.0f * _DissolveScale;
            fixed4 dTex = tex2D(_DissolveTex, IN.uv_MainTex);
            half dTexRead = dTex.r + dBase;
            half dFinal = dTexRead + IN.dGeometry;
            half alpha = clamp(dFinal, 0.0f, 1.0f);
            //Shift the computed raw alpha value based on the scale factor of the glow.
            //Scale the shifted value based on effect intensity.
            half dPredict = (_GlowScale - dFinal) * _GlowIntensity;
            //Change colour interpolation by adding in another factor controlling the gradient.
            half dPredictCol = (_GlowScale * _GlowColFac - dFinal) * _GlowIntensity;

            //Calculate and clamp glow colour.
            fixed4 glowCol = dPredict * lerp(_Glow, _GlowEnd, clamp(dPredictCol, 0.0f, 1.0f));
            glowCol = clamp(glowCol, 0.0f, 1.0f);
            o.Albedo = c.rgb;
            o.Alpha = alpha;

            o.Emission = glowCol;
        }
        ENDCG
    }
    FallBack "Diffuse"
}


texts: What's wrong with this OpenGL model picking code?

texts:
I am making simple model viewer using OpenGL. When I want to pick an object OpenGL returns nothing or an object that is in another place.

This is my code:

GLuint buff[1024] = {0};
GLint hits,view[4];

glSelectBuffer(1024,buff);
glGetIntegerv(GL_VIEWPORT, view);

glMatrixMode(GL_PROJECTION);
glPushMatrix();
glLoadIdentity();
gluPickMatrix(x,y,1.0,1.0,view);
gluPerspective(45,(float)view[2]/(float)view[4],1.0,1500.0);

glMatrixMode(GL_MODELVIEW);
glRenderMode(GL_SELECT);

glLoadIdentity();
//I make the same transformations for normal render
glTranslatef(0, 0, -zoom);
glMultMatrixf(transform.M);
glInitNames();
glPushName(-1);
for(int j=0;j<allNodes.size();j++)
{
    glLoadName(allNodes.at(j)->id);
    allNodes.at(j)->Draw(textures);
}
glPopName();
glMatrixMode(GL_PROJECTION);
glPopMatrix();
hits = glRenderMode(GL_RENDER);


texts:
I'm trying to implement a collision system using oriented bounding boxes, using a center for the box, it's extents as a 3D Vector and a rotation matrix, which is all stuff I picked up online and seem to be somewhat the standard.

Detecting the center is no problem so I'm gonna leave these out here.

My problem however is importing the data from a 3D file. Say I've placed a box with 2 units length on each side aligned to the world axis. The logic results here are extents of 1,1,1 and I use an identity matrix for rotation - easy.

However I'm stuck when I rotate the box in the 3D program, say 30 degrees each axis. How would I parse the box? I only have these 8 vertices as information, and I guess what I would need to do is to find out the rotation of said box, apply it to the vertices so they are aligned to world axes and then calculate the extents out of that.

How do I get the rotation of the box when I only have the vertex information of the box available?


texts:
I want to make a game that depends on the phone orientation (changing shoot direction with tilt), however I need to test this on PC. So is there any tool I can use to simulate the orientation of the phone with mouse or keyboard of my PC? Something like joysticks on the screen.

Thanks for any help!

Edit :

Thanks to @jhocking for his suggestion of Unity Remote. I, however still can accept a solution with using only PC, since I'm afraid of shortening my phone's battery life, for some reason.


texts: Unity - using Colliders with custom objects

texts:
Hi so I'm quite new to Unity and currently experiencing issues with colliders, a quick summary of what I have.
Player >
Object = Capsule ( Directly created through Unity )
Components = CharacterController, CapsuleCollider & a PlayerController script

Basic Tile >
Object = Rectangle ( Imported from blender )
Components = BoxCollider

this combination works well, no issues. However when I get to slightly more complex objects, such as elevated terrain I can't apply a box collider because the surface isn't flat. So my next thought was to add a Mesh Collider but unfortunately it doesn't seem to do anything effective ( my player falls through ) I don't know whether that's because Mesh Colliders are only relevant to RigidBodies? Unfortunately though I can't switch from a CharacterController to a RigidBody.
So I'm not sure what to do, maybe MeshColliders are reponsive to a CharacterController and my settings aren't adjusted correctly?


texts:
About 8 months ago, I asked this question, and received a lot of valuable information from the community.

I have switched to nodejs, since then, and am finishing up my game. I am deeply concerned about networking issues pertaining to the usage of WebSocket data being sent through my current architecture; especially since my game uses an authoritarian server, and doesn't utilize peer to peer.

My game is a Diablo 2 inspired action RPG. As we know, for action RPGs, players utilize a lot of skills, and if games are instanced based, all players in the game need to be notified.

I am worried about scalability. Here is an example:

Shooting a fireball has a 0.5 second cool-down. This is how the data is sent:

Client [Skill id, Skill rotation] -> Server
Server [Checks cooldown, notify's players skill is being used]
Client [If fireball hits monster, send attack signal] -> Server
Server [Checks cooldown, player's range to mob, calculates damage, etc & spits out damage numbers to all players]

All this happens in less than 1 second. The WebSocket server is not even sending out the Monster AI update packets to do damage to the player, nor the monster's fireballs. So now, basically double the amount of data is being sent through the WebSocket and to all player's in a game. It gets worse; imagine if 20 players are online attacking monsters. My nodejs server will be on fire.

This method is not even 100% cheat proof, as I'm waiting for the fireball to hit the monster on the client-side to send the attack signal, instead of doing all that on the server. The problem is, I would have to be running a physics engine on the server, which would bog down nodejs's event loop even more. I'm using the P2 Physics engine from Phaser, and not simple AABB; otherwise, I could just check for collisions server-side.

To close, when a player moves around the map, the server notifys everyone else in the same game. The same goes for when a player drops an item, or when loot is generated from a monster. I just feel like I'm clogging my WebSocket server up, and am doing something wrong with all this data being sent across the pipe.

So with all this said,

Am I worrying too much about the amount of data being sent across
WebSockets?
Is this data being sent normal for a games that utilizes an authoritarian server?
Would a Redis Pub Sub system be an ideal solution to my problems?


texts: Collision detection - formula for getting intersection point

texts:
I need help with collision detection algorithm from this paper: http://www.peroxide.dk/papers/collision/collision.pdf

I assume I am colliding with sphere of radius 1, just to make everything not important easier...I am concerned with formula, which finds intersection point with plane (page 14):

planeIntersectionPoint = basePoint - planeNormal + t0 * velocity

where:
basePoint = center of Sphere

planeNormal = normalized normal vector to colliding plane

t0 = number from [0,1] interval, first moment from this interval during which collision happens, assuming we are moving with velocity vector

velocity = velocity vector

I think that this formula doesn't work... Assuming that I am already intersecting with plane at t0 = 0, I just get:

planeIntersectionPoint = basePoint - planeNormal

What gives me point which doesn't even belong to plane, what fails further parts of the algorithm, when I check if intersection point is in triangle...

I will be grateful for every answer... Is the algorithm wrong, or that's me misunderstanding something?...


texts: UE4 C++ - Add generated source code folders to Visual Studio solution?

texts:
In Unreal Engine 4, using a Visual Studio solution and projects generated from the Editor using the First Person Template, the layout of the Solution looks something like the following:

I am not a fan of this flat horizontal folder structure. What I would like to do is put some new classes into a nested folder here.
I will be generating a new GameState subclass, and putting the sources into the Source\GameState folder that will also be created on the fly, using the UE4 editor:

Notice that the "Create New Folder" option is disabled.

Here I have appended the "GameState" folder to the normal source path.
However, the folder structure in the Solution Folder has not changed, and nothing I try to do is working. The things I have tried to do so far include:

Drag the folder into the solution from the file explorer
Right Click > Add > Existing Item... (Which just results in the files appearing horizontally to the other files without the new folder I have created, also add as link is not an available option)
Create a "Filter" (what the other folders appear to be) within Visual Studio. This results in the layout I desire, but I have to add the source code files to the filter manually which just copies them to the .vcxproj file directory. I end up not modifying the actual files I added.

How can I add this folder and it's files while keeping up with the original copies?


texts: Using a Vertex Buffer and DrawUserIndexedPrimitives?

texts:
Let's say I have a large but static world and only a single moving object on said world.

To increase performance I wish to use a vertex and index buffer for the static part of the world.

I set them up and they work fine however if I throw in another draw call to DrawUserIndexedPrimitives (to draw my one single moving object) after the call to DrawIndexedPrimitives, it will error out saying a valid vertex buffer must be set.

I can only assume the DrawUserIndexedPrimitive call destroyed/replaced the vertex buffer I set. In order to get around this I must call device.SetVertexBuffer(vertexBuffer) every frame. Something tells me that isn't correct as that kind of defeats the point of a buffer?

To shed some light, the large vertex buffer is the final merged mesh of many repeated cubes (think Minecraft) which I manually create to reduce the amount of vertices/indexes needed (for example two connected cubes become one cuboid, the connecting faces are cut out), and also the amount of matrix translations (as it would suck to do one per cube). The moving objects would be other items in the world which are dynamic and not fixed to the block grid, so things like the NPCs who move constantly.

How do I go about handling the large static world but also allowing objects to freely move about?


texts:
Hello it seems like it should be easy and i am missing something but i really couldn't find a solution as i am fairly new to programming.
So basically i want to rotate a object faster when its closer to another object. My code is below and i want the rotationSpeed to be a higher value when its closer.

rotationSpeed = Mathf.Sqrt(
        Mathf.Pow(sphere.center.X - playerSphere.center.X, 2)
        + Mathf.Pow(sphere.center.Y - playerSphere.center.Y, 2)
        + Mathf.Pow(sphere.center.Z - playerSphere.center.Z, 2));

eg: 10 * x = 50,
    5  * x = 100


texts: Distorted LookAt When Looking Up or Down?

texts:
I have a weird problem and I have no idea what's going on with it.

Recently started doing some OpenGL programming, going pretty well, hit some rough spots but worked my way through them and otherwise pretty happy! But I've hit a roadblock with something that has me confused as hell.

I'm doing an OpenGL 4 based rendering system, it's early days and I've got some basic stuff like 3D model importer happening, but I've been having some problem with the maths involved in creating my own "LookAt" function like present in OpenGL 2. I've created my own Matrix & Vector class, I think most of the functions are right but the LookAt does something weird when looking at different angles.

For a simple test to show what happens, I created a slowly moving focus point for the lookat that starts off a few units ahead of the camera, then slowly moves closer and closer till it's 1 unit below the camera. As the focus point comes closer to the point of looking straight down, for some reason it's like the field of view is narrowing?

It eventually zooms in so close that all you can see is one solid colour covering the entire screen, whatever pixel just happens to be on the ground directly below the camera as it zooms in with a field of view of basically 0 degrees.

It may be nothing to do with field of view at all but I don't know and hence why I'm here. Here is some related code to the problem, forgive me if these implementations are not perfect, again I'm just starting out and I don't know the best methods yet, still learning:

My function for calculating a lookAt:

public static Transformation lookAt(Vector position, Vector target, Vector updirection) {
        Transformation lookAt = new Transformation();

        Vector vz = position.clone();
        vz.subtract(target);
        vz.normalise();

        Vector vx = Vector.xProduct(updirection, vz);
        vx.normalise();

        Vector vy = Vector.xProduct(vz, vx);

        lookAt.m[0] = vx.x; lookAt.m[1] = vy.x; lookAt.m[2] = vz.x; lookAt.m[3] = position.x;
        lookAt.m[4] = vx.y; lookAt.m[5] = vy.y; lookAt.m[6] = vz.y; lookAt.m[7] = position.y;
        lookAt.m[8] = vx.z; lookAt.m[9] = vy.z; lookAt.m[10] = vz.z; lookAt.m[11] = position.z;
        lookAt.m[12] = 0; lookAt.m[13] = 0; lookAt.m[14] = 0; lookAt.m[15] = 1;

        return lookAt.inverse();
    }

My function for calculating perspective:

public static Transformation perspective(double FoV, double aspectRatio, double nearClip, double farClip) {
    Transformation proj = new Transformation();
    double FoVR = Math.toRadians(FoV);
    proj.m[0] = FoVR/aspectRatio;
    proj.m[5] = FoVR;
    proj.m[10] = (farClip + nearClip)/(nearClip - farClip);
    proj.m[11] = 2*(farClip*nearClip)/(nearClip-farClip);
    proj.m[14] = -1;
    proj.m[15] = 0;
    return proj;
}

I use the function later on when generating a matrix to apply to the 3D letter G in the scene, like so:

Transformation MVP = new Transformation();

Transformation proj = Transformation.perspective(FoV, (double)canvas.getWidth()/(double)canvas.getHeight(), near, far);
MVP.multiply(proj);

Transformation view = Transformation.lookAt(cameraPosition, cameraFocus, cameraUp);
MVP.multiply(view);

Transformation model = Transformation.scaleRotateTranslate(objectScale, objectRotation, objectTranslation);
MVP.multiply(model);

And the MVP is simply sent to the shader and used as you'd expect to multiple against all the verticies/normals.

What do you think I'm doing wrong? What should I check first? Is there a better way of doing what I'm trying to do? Any help/answers at all is greatly appreciated, I just don't know what to go after first. The perspective/lookAt seems like it's almost working but something must be broken?


texts: Does Direct3D 11 enable Z-clipping/discard by default?

texts:
I'm rendering simple 2D figures in DirectX 11.1 and I cannot get Z-values to be rendered; all pixels with Z != 0 get discarded. I'm doing proper world transform as far as I know. X/Y translations work. Rotation over Z works.

Do I need to setup a depth/stencil buffer to avoid DirectX to discard all primitives with Z coordinates?

Thanks, I'll supply any additional information ,code or screens if required.

EDIT:

I've fixed D3D11_VIEWPORT minDepth and MaxDepth members to 0.0/1.0 (I was clearing both to zero). Now pixels with 1.0 < z < 0.0 are discarded.

EDIT 2:

My platform is Windows Runtime App (Win8.1 / WinPhone 8.1).

EDIT 3:
Example screenshots.

Rotated triangle over the Y-axis (pixels with Z>1 discarded)

Triangle Vertex at (x=-0.5,y=-0.5) with z=2. Clipped and hidden.


texts: Move parent according to child axis in Unity?

texts:
Can I ask my parent to move according to the child axis? This means if I turn right, then right again, the parent has to be at 180° from its original position, and not only at 90° (because "Right" would mean : "stay on the right axis from the parent axis", and what I want is : "move the parent according to the child axis").

The parent has a script to move, and the child has the script to rotate, so I would need to use the new rotation from the child, and not the rotation from the parent.

My attempt so far is this one : in "MoveBody()", oldTr = transform.position works without a bug, but it is using the parent axis. With oldTr = this_objW;, there is a bug, the parent goes somewhere in the scene and move its "z" axis in an odd way :

this_obj = GameObject.Find("this_obj").transform;//the child to rotate
this_objW = this_obj.TransformDirection(this_obj.forward);//world

//...

MoveBody( new Vector3( 3.0f, 0, 0 ) );

//...

private void MoveBody( Vector3 vec ){

      Debug.Log("transform.position : "+transform.position+" / this_objW : "+this_objW); //same value here: Vector3(0,0,1);
      oldTr = this_objW; //transform.position;
      newTr = this_objW;//transform.position;
      newTr += vec;
      transform.position = Vector3.MoveTowards(oldTr, newTr, sideSpeed * Time.deltaTime);
}

Is it possible to do it this way? Or should I translate each axis by hand?

Thanks


texts: How can I create my own GameTime for timing things in my game?

texts:
I have a Game class and a GameComponent class. I want to perform operations inside the GameComponent class which depend on calling gameTime.ElapsedGameTime.TotalSeconds, but I've noticed that that value is always 0.

At the moment I am initializing gameTime inside the GameComponent class by doing new GameTime();

I had the thought that somehow I should take the gameTime variable of my Game class, but I was not able to find a way to do so. I had always used Update(Gametime gameTime) and Draw(Gametime gameTime) methods in the past, which automatically gave me a game time object.

Now, that I need to deal directly with gameTime to run my own timing information, I see that it is a little tricky because I don't understand how it works properly. How can I create a timer for my own use?


texts: How to instantiate GameObject on client without network?

texts:
When I NetworkServer.Spawn(ob) a gameobject and make it a child of a transform.parent after it spawns on both the server and client it usually lags, meaning it takes some secs to align with the transform.parent which is the player

Example : Instantiating a GameObject containing a ParticleSystem which gives the parent somewhat an effect, smoke or something in that direction, in the host client every object usually has a smooth movement where as in the connected client it goes very rough and slow, like every gameobject having a low fps except the main client player prefab

So i was thinking spawning the same effect on both clients so it wouldn't have to sync from the server to the client which uses it instead it only would have to sync inside the clients game, it might not have the same particle movements but it wouldn't make a difference

Here's the child's prefab network identity and transform :


texts:
How can I prepare for feature creep during preproduction?

Feature creep is when you are in the production phase and decide "It would be cool if this were a feature!" That adds n hours to the development time which were not accounted for, and unless you are Blizzard, do not have the time for. You cannot anticipate it being a cool feature during preproduction, because the feature is only discovered during production.

What can I do during preproduction to account for or prevent or prepare for feature creep?

Should I allow feature creep and cut less desired features? Or will this create a problems since the architecture is not designed for the new features? Should I say no features unless they fit into the existing architecture?

I know this is a broad question, but I hope it doesn't get closed as such. This is a major issue in game development, and should be considered.


texts: Direction between objects (shortest distance around sphere)

texts:
I have two objects rotating around a sphere. One is controlled by the user (object A), another is simulating a user but controlled by the computer (object B). At random intervals of time I'd like object B to start moving towards object A.

I can get this to work using this formula to determine the movement direction between two points:

public Vector3 DirectionTowards(Vector3 from, Vector3 to)
{
    return (to - from).normalized;
}

This gives me a normalized direction vector to update the x/y movement with. Since this is momentum based, if the objects need to move in an opposite direction I update their movement direction vector like so: (notice the "+=" instead of just "=" to give the effect of momentum/acceleration, more on this below)

// This code runs when  I need to move object B toward object A
var newDirection = DirectionTowards(transform.position, target.transform.position);
xMove = newDirection.x;
yMove = newDirection.y;

...

// This code runs in my update method
_moveVector.x += xMove * _acceleration;
_moveVector.y += yMove * _acceleration;

The problem I'm having is that when the objects are at opposite sides of the sphere, sometimes object B will start moving in the direction that is not the shortest distance to object A. Is there a way I can determine the direction in a similar way, but force it to choose the shortest distance around the sphere?

Also, to go along with this. By using "+=" vs "=" when I update the _moveVector sometimes that causes the direction to get changed slightly because it does an arc as it slows down its momentum before moving in the new direction. Does anyone know why that might be, or if I'm doing that incorrectly? Basically object B will start moving "almost" in the right direction due to this, but eventually after a while the whole things gets screwed up. If I use "=" only, this works perfectly every time except for the issue of shortest distance as I mentioned above.

Thanks! Let me know if any other information is needed.


texts:
I am new at XNA, i have started it about a week earlier but i have 3d experience in WPF.

Scenario:
I have a room in which i have a object(for now it is a cube). The objects are generated in Max 2011 in the designers computer which i import into mine using fbx importer.

Problem:
1. The model are not positioned as per the max files, and also there are losses in the models.

In Max: http://i.imgur.com/iNJGTh.png
In XNA: http://i.imgur.com/ZXoU8.png

Could anyone suggest me how to resolve this problem?

Is there a dynamic way to get the camera position information from the "FBX" file that i exported from 3Ds Max?


texts:
I am willing to change emission level through code without affecting its color.
(i.e., changing the brightness number shown in the box at the right side of the inspector, while keeping the emission color unchanged)
I have tried this so far, but I don't know how to use my value variable to update the material:
public class EmissionColourChange : MonoBehaviour {

    Material thisMat;
    Color c;
    public float value;

    void Start () {
        thisMat = GetComponent<Renderer>().material;
        c = GetComponent<Renderer>().material.color;
        thisMat.EnableKeyword("_EMISSION");
        value = c.r;
    }

    void Update () {
        thisMat.SetColor("_EmissionColor", new Color(c.r,c.g,c.b));
    }
}


texts: Do I need to use a game engine to make a simple game function on other platforms?

texts: I'm a complete beginner really enjoying learning how to code (currently in Python) and my first games will be very simple, mostly text based, but I'd like them to run on friends' phones and computers on various platforms, including windows, linux, mac and android. Is this easy to do without using a game engine, or should I use, say, Unity? If I use Unity will I still be learning to program in code, or is it silly to use a game engine for a game that is simple, like a 'choose your own adventure' game or, later, an ascii roguelike? Thanks.


texts: How can I gradually increase the speed of my game?

texts:
I recently made a replica of (Dino run) game in Unity2d.

But I'm stuck on how can I speed up my game gradually.
Should the game speed be increased or should I increase the speed of the camera.

Here is my spawn obstacles script.

public class SpawnObstacles : Monobehaviour

{
    public GameObject [] obstacles;
    private GameObject obj;
    private float XPos = 0;
    private int number = 0;

    private float randomPosition = 0;

    // Start is called before the first frame update
    void Start()
    {
        InvokeRepeating("Spawn", 1.5f, 1.6f);
    }

   private void Spawn()
    {
        if (GameObject.Find ("Cube").GetComponent<Cube> ().isDead == false)
        {
            number = Random.Range(0, 12);
            randomPosition = Random.Range(19, 29);

            XPos = transform.position.x + randomPosition;
            obj = obstacles[number] as GameObject;

            Instantiate(obj, new Vector2(XPos, obj.transform.position.y), Quaternion.identity);

        }
    }
}


texts: How to invisible first window on click unity3d

texts:
I have a window called "red window" on scene1. When i click on the hello world button it should displays another window called green window and the first window should invisible. How it possible.

using UnityEngine;
using System.Collections;![alt text][3]

 public class window : MonoBehaviour {
 private bool render = false;
 public Rect windowRect0 = new Rect(20, 20, 120, 50);
 public Rect windowRect1 = new Rect(20, 100, 120, 50);
 void OnGUI() {
     GUI.color = Color.red;
     windowRect0 = GUI.Window(0, windowRect0, DoMyWindow, "Red Window");
     GUI.color = Color.green;
    windowRect1 = GUI.Window(1, windowRect1, DoMyWindow1, "Green Window");
 }
 void DoMyWindow(int windowID) {
     if (GUI.Button (new Rect (10, 20, 100, 20), "Hello World")) {
         }

       //GUI.DragWindow(new Rect(0, 0, 10000, 10000));
   }
  void DoMyWindow1(int windowID) {
 if (GUI.Button(new Rect(10, 20, 100, 20), "Hello World"))
     print("Got a click in window with color2222222222 " + GUI.color);
 //GUI.DragWindow(new Rect(0, 0, 10000, 10000));
 }


texts: How to collect objects from map in blueprints

texts: I have a plate with trigger(TriggerVolume) on it. When it overlapped cubes from map deleting. I've manually created references on cubes in blueprint to delete them but it seems very hard-coded. Is there any way to collect all references with "for loop"? And for more clarity - I'm using FPS template for this project.


texts: unity3d - Instantiate and fire bullet realtive to player rotation in 3D

texts:
This is a top-down view but in 3D coordinates, I would like to instantiate and fire a bullet from the player's gun. This script is on a spawner object at the end of the barrel. Also tried putting the script on the player itself but also didn't work.

GameObject projectile =  Instantiate (bullet, transform.position, transform.rotation) as GameObject;

 projectile.GetComponent().AddForce(transform.forward * speed);

The problem is the bullets doesn't behave as intended, instead they don't appear relative to the player rotation and they just go in a very different direction. Shouldn't "Transform.Forward" mean forward in the Z position regarding the object's transform ?


texts: AssetBundles with shaders that contain #include to cg/hlsl

texts:
I have a shader that contains some #includes to other cg/hlsl scripts. If i put that shader into an AssetBundle, how am i suppose to handle the cg/hlsl scripts?

Are they not necessary anymore because they are compiled into the shader during the AssetBundle build process? Unity version is 5.6.6f2

Or do i have to put the cg/hlsl scripts into the AssetBundle too? If that is the case, how do I load them during runtime such that the Shader finds them?

Someone suggested me to inline them, but I would like to avoid it if possible.


texts: Why do my sprites jitter when moving diagonally?

texts:
I am working on an low resolution, isometric, pixel game in which several objects move from tile to tile. I do this with this simple interpolation:

let percent = elapsedTime / SPEED

vec.x = start.x + ( (dest.x - start.x) * percent )
vec.y = start.y + ( (dest.y - start.y) * percent )

This seems to work fine except when moving diagonally. It starts to jiggle pretty heavy. Is there a way to smooth this out?

I am using a 32x16 tile size.

edit: added video for better understanding: (video deleted)

edit: for anyone interested. I've solved it using this:

let
percent = elapsedTime / SPEED,
num = Math.round( (dest.x - start.x) * percent )

vec.x = start.x + num
vec.y = start.y + Math.floor(num / 2)

This works only for diagonal movement with 1:2 ratio tiles. I also added some stuff to make it work for all 4 diagonal directions.


texts: Are there any open source projects for car engine sound simulation?

texts:
I have been thinking how to create realistic sound for a car. The main sound is the engine, then all kind of wind, road and suspension sounds.

Are there any open source projects for the engine sound simulation? Simply pitching up the sample does not sound too great. The ideal would be to something that allows me to pick type of the engine (i.e. inline-4 vs v-8), add extras like turbo/supercharger whine and finally set the load and rpm.

Edit: Something like http://www.sonory.org/examples.html


texts: Detecting a Collision Between Two Bodies Undergoing Multiple Transformations

texts:
I have been searching for an answer to this for a really long time and I have not found any definitive answers as of yet.  What I am trying to do is determine if and when two bodies collided between the times t0 and t1.  Calculating this is much more straight forward if each body is only either translating or rotating (about center or any point), but when adding multiple transformations on top of each other, things become a bit more messy.  I made this animation to illustrate the problem.

As you can see, at times t0 and t1 there are no collisions, but between there are multiple collisions occurring.

One way I thought of for tackling this problem was to reduce the size of the time intervals.  So, between t0 and t1 there would be a total of n updates to check for collisions.  This works, but the only way I found that I could guarantee no false negatives, i.e. not finding a collision that happened, was to integrate over extremely small time-steps.  As you can imagine, this is very costly because it resulted in the tens to hundreds of time-steps per body per update cycle.  I am not saying this idea has no merit (it makes calculating the collision response much easier since I know the exact points of contact), but I would need to find a way to calculate the minimum number of time-steps rather than uniformly moving each body forward one unit of distance/rotation until they reach the desired position and orientation.

So, my question is two parts:

Is there a better way of determining if and when a collision occurs?
If not, is it possible to calculate the minimum number of time-steps?

P.S.

I think the maximum translation per time-step can be the shortest distance between any two points in the body.  This would not allow it to hop over anything.  When it comes to rotation about the center or orbiting a point I do not know how to determine the minimum angle.  It probably has to do with the arc length, but what should that maximum distance be?

EDIT: this is not right. For a triangle, the base would be the shortest distance between two of its points, but the top could pass through something that is less wide than the triangle base.


texts: Game has noticeable frame drops but when through a profiler it always runs smooth

texts:
I'm trying to optimize my PC game but I can find the bottleneck since every time I run it through a profiler (gDEBugger) it runs smooths. When running outside gDEBugger I get these annoying hiccups. It's not just the graphics, the sound also gets choppy. The drops are inconsistent across runs, i.e, sometimes I run the same scenario and get no drops at all, sometimes I get a few drops, and others the game is consistently slow. The only constant is: when running through gDEBugger I ALWAYS get a smooth run.

I'm suspecting something outside my game is interfering and causing these drops, but what in the hell does gDEBugger do that nullifies these drops? A higher process priority? Any ideas?

Thanks in advance.


texts: How can I find the opposite angle and position of the camera?

texts:
In this project I have a character and a camera that follows it.

The camera has a position relative to the character that was defined as (x = 0, y = 0, z = 0) and also its rotation:

I found a value close to its position and opposite angulation, but not really the correct value:

By pressing the Q key, the camera shifts to the position and angulation that I have discovered. Releasing the Q key, the camera returns to its initial position:

IN GAME:

As you can see, the inversion is not 100% correct.

One of the ways I thought, is a way where I take this relative value from the camera (x = 0, y = 0, z = 0) and with that:

I put the character's mesh at the location (x = 0, y = 0, z = 0) at the level and so, as the camera will be (for example) x = -250, y = 0, z = 300, it's just I invert the value of x. The angulation is simpler to deduce, but it would be interesting for me to also derive its relative value (0, 0, 0).

EDIT 1 (Attempt that I did and that almost worked out)

By clicking the down arrow to the left of the values, you can select whether you want the variable to be Relative or World (I did not know that):

Before it was all 0, it now has a value:

Taking the minus sign, I was able to figure out the opposite position:

New position:

It happens that at the time of changing the angulation from relative to absolute, a conversion is not made:

I can not get absolute value equivalent to relative. What happens is that the value 0, 0, 0 is also defined for the absolute rotation. In the image below the camera was exactly in the same position as the VR camera:

I discovered by trial and error the equivalent angulation between relative and absolute:

BLUEPRINT:

The code works correctly, but I feel that again I did not get exactly the position and opposite angles.

Here are some screenshots of the game:

Local X with NORMAL CAMERA:

Local X with OPPOSITE CAMERA:

Local Y with NORMAL CAMERA:

Local Y with OPPOSITE CAMERA:

Note that in the opposite camera you can see the end of the world (sky) from wherever you are, which is not the case with the normal camera. I noticed this, and so, I think once again I did something wrong.


texts: How do I create and animate simple polygons directly from code in Unity?

texts:
I'm a beginner with Unity, but I know how to code.  I'm open to tutorials, of course.

Ideally, I would like to code spacial vertices and connect them into a simple polygon. The polygon would then be animated by changing the vertices over time.