texts:
I've taken the A* Algorithm from this example XNA Pathfinder Example so that it will be able to plot a path for a moving goal.

The issue I'm having is that it will go in the right general direction but it will keep going back and forth in a line. I've changed the method so that it calculates a new path every half a second, clear out the previous points from the list and adds the new points to and from what I have debugged I can't find any issue with the points being added to the queue, to be honest I don't have the foggiest idea what is going wrong :/

This is the field where the waypoints are being held for the character

private Queue<Vector2> waypoints = new Queue<Vector2>();

This section is in the update loop and deals with the plotting a new path and laying out the new one onto the list mentioned above.

            timer += gameTime.ElapsedGameTime;

            if (timer.Seconds >= 0.5)
            {
                timer = TimeSpan.Zero;
                pathFinder.NewPath(position);
            }

            if (pathFinder.SearchStatus == SearchStatus.PathFound)
            {
                waypoints.Clear();
                foreach (Point point in pathFinder.FinalPath())
                {
                    Waypoints.Enqueue(level.MapToWorld(point, true));
                }
                moving = true;
            }

This section is where the waypoints are either taken off or used to set the new position of the character.

                if (moving)
                {
                    // If we have any waypoints, the first one on the list is where
                    // we want to go
                    if (waypoints.Count >= 1)
                    {
                        destination = waypoints.Peek();
                    }

                    // If we’re at the destination and there is at least one waypoint in
                    // the list, get rid of the first one since we’re there now
                    if (AtDestination && waypoints.Count >= 1)
                    {
                        waypoints.Dequeue();
                    }
                    if (!AtDestination)
                    {
                        direction = -(position - destination);
                        //This scales the vector to 1, we'll use move Speed and elapsed Time
                        //to find the how far the tank moves
                        direction.Normalize();
                        position = position + (direction * MoveSpeed * elapsedTime);
                    }
                 }


texts: Is this normal behaviour that Unity continues to run after a condition in a Debug.Assert statement was NOT met when I launch the game within the Editor? I can see the assertion in the console output, but still would expect it to stop the game. Development build and Script Debugging are turned on in my player settings.


texts: Java Slick2d - How to translate mouse coordinates to world coordinates

texts:
I am translating in my main class render. How do I get the mouse position where my mouse actually is after I scroll the screen

public void render(GameContainer gc, Graphics g) throws SlickException
{
    float centerX = 800/2;
    float centerY = 600/2;
    g.translate(centerX, centerY);
    g.translate(-player.playerX, -player.playerY);
    gen.render(g);
    player.render(g);
}

playerX = 800 /2 - sprite.getWidth();
playerY = 600 /2 - sprite.getHeight();

Image to help with explanation

I tried implementing a camera but it seems no matter what I can't get the mouse position.
I was told to do this worldX = mouseX + camX; but it didn't work the mouse was still off.

Here is my Camera class if that helps:

public class Camera {
public float camX;
public float camY;

Player player;

public void init() {
    player = new Player();
}

public void update(GameContainer gc, int delta) {
    Input input = gc.getInput();

    if(input.isKeyDown(Input.KEY_W)) {
        camY -= player.speed * delta;
    }
    if(input.isKeyDown(Input.KEY_S)) {
        camY += player.speed * delta;
    }
    if(input.isKeyDown(Input.KEY_A)) {
        camX -= player.speed * delta;
    }
    if(input.isKeyDown(Input.KEY_D)) {
        camX += player.speed * delta;
    }
}

Code used to convert mouse

worldX = (int) (mouseX + cam.camX);
worldY = (int) (mouseY + cam.camY);

Tile class

public class TileGen {
Block block;
public Block[] tiles = new Block[2];
public int width, height;
public int[][] index;
int mouseX, mouseY;
int worldX, worldY;
boolean selected;

Image dirt, grass, selection;
SpriteSheet tileSheet;

int startX, startY, stopX, stopY;

Camera cam;
Player player;

public void init() throws SlickException {
    tileSheet = new SpriteSheet("assets/tiles/tileSheet.png", 64, 64);

    grass = tileSheet.getSprite(0,0);
    dirt = tileSheet.getSprite(1,0);
    selection = tileSheet.getSprite(2,0);

    tiles[0] = new Block(BlockType.Grass, new Vector2f(0,0), grass, true);
    tiles[1] = new Block(BlockType.Dirt, new Vector2f(0,0), dirt, true);

    width = 50;
    height = 50;

    index = new int[width][height];

    cam = new Camera();
    player = new Player();

    Random rand = new Random();
    for (int x = 0; x < width; x++) {
        for (int y = 0; y < height; y++) {
            index[x][y] = rand.nextInt(2);
        }
    }
}

public void update(GameContainer gc) {
    Input input = gc.getInput();
    mouseX = input.getMouseX();
    mouseY = input.getMouseY();

    worldX = (int) (mouseX - player.playerX);
    worldY = (int) (mouseY - player.playerY);

    if(input.isMousePressed(Input.MOUSE_LEFT_BUTTON)) {
        selected = true;
    } else {selected = false;}

    for (int x = 0; x < width; x++)
    {
        for (int y = 0; y < height; y++)
        {
            if(IsMouseInsideTile(x, y) && selected) {
                if(tiles[index[x][y]]== tiles[0])
                    index[x][y] = 1;
            }
        }
    }

    startX = (int) (cam.camX/64);
    startY = (int) (cam.camY/64);

    stopX = startX + (gc.getWidth()/64)  + 2;
    stopY = startY + (gc.getHeight()/64) + 2;
    System.out.println(worldX);
}

public void render(Graphics g, GameContainer container) {
    for (int x = startX; x < stopX; x++) {
        for (int y = startY; y < stopY; y++) {
            tiles[index[x][y]].texture.draw(x * 64, y *64);
            if(IsMouseInsideTile(x, y)) {
                selection.draw(x * 64, y * 64);
            }
        }
    }
}

public boolean IsMouseInsideTile(int x, int y)
{
    return (worldX >= x * 64 && worldX <= (x + 1) * 64 &&
            worldY >= y * 64 && worldY <= (y + 1) * 64);
}

}


texts: What is the correct way to get the starting point of a Box2D body?

texts: when I use getPosition() I get the center point of the body. The fixture's position in the body is relative to the body. However if the body is inclined and has an angle do I need to calculate the starting point of the body? I need this point to draw a sprite on it. Is there an easy way to do this?


texts: Minecraft: What is the reasonable face/vertex limit for custom models?

texts:
When adding custom models to function as tile entity representations, what is a reasonable ceiling - based on performance - to maintain for individual models? Assume that the player will have the potential possibility to place as many of these as desired, but functionally it would also be reasonable to assume no more than 20 would have to be rendered at once.

If the answer has changed between significant versions of the game, it would be nice if that could be reflected


texts: How to keep my auto-aim in sync with the rendered frame?

texts:
In my FPS game there is an automated lock system. If you stare at an enemy, your weapon locks onto the enemy as long as your aim is hovering approximately around the target.

If my player sets frame rate high (say they changed frame rate from 60 to 140+) they have smooth frame rate in which allows them to change their view more smoothly. My players can now hover their aim onto an enemy more rapidly.

Problem is, if my game were to run at 60 ticks per second while the player set the render system to render 140+ frames per second, my game's tracking system will be a few frames behind what the player looks at.

So I am wondering, should my game's logic run at the same rate that the rendering system is rendering the game? Or can I solve this synchronization issue in another way?


texts: Drawing game objects that are bigger than tiles

texts:
Problem:

I have 32x32 world tiles, and a 64x64 object. I am only drawing visible tiles around the player.
The object has its x and y coordinates in the tile world. I am drawing the object after I've drawn the visible area.

I'm drawing the object like this :

for (int y = firstY; y < lastY; y++) {
        for (int x = firstX; x < lastX; x++) {
            if (object.visible(x, y))
                object.draw();
            }
        }
    }

The visible(x,y) method :

public boolean visible(int x, int y) {
    if (this.x == x && this.y == y) {
        return true;
    }
    return false;
}

Now what happens is this :

Image 1.
Character stands alongside the object, everything is ok.

Image 2.
Character triggers screen move left, half of the object gets drawn outside the map.

Image 3.
Character triggers screen move right, half of the object should be visible but its not.

I know that this happens because I'm checking only if the upper left corner of the object is visible. I'm stuck. What should I do to remedy this?

Thank you for any ideas.


texts: Full screen blackout using allegro in codeblocks

texts:
I'm very interested in game programming and I'm taking my first steps alone. So I installed allegro. Although Dev-C++ didn't work, Code::Blocks compiled successfully. I started out with this basic program:

#include <allegro.h>

int main(){

    allegro_init();
    install_keyboard();
    set_gfx_mode( GFX_AUTODETECT, 640, 480, 0, 0);

    readkey();

    return 0;

}
END_OF_MAIN();

The problem comes in when I try to run it. It opens the little window as always, but rapidly blacks out my whole screen. I press any key and it takes me back to the little window telling me that it finished, which means the program worked. But I try any other program with allegro, like:

#include <allegro.h>

int x = 10;
int y = 10;

int main(){

    allegro_init();
    install_keyboard();
    set_gfx_mode( GFX_AUTODETECT, 640, 480, 0, 0);

    while ( !key[KEY_ESC] ){

        clear_keybuf();

        acquire_screen();

        textout_ex( screen, font, " ", x, y, makecol( 0, 0, 0), makecol( 0, 0, 0) );

        if (key[KEY_UP]) --y;
        else if (key[KEY_DOWN]) ++y;
        else if (key[KEY_RIGHT]) ++x;
        else if (key[KEY_LEFT]) --x;

        textout_ex( screen, font, "@", x, y, makecol( 255, 0, 0), makecol( 0, 0, 0) );

        release_screen();

        rest(50);

    }

    return 0;

}
END_OF_MAIN();

And the same thing happens over and over again! Is there something I'm doing wrong?


texts: Converting many faces to single mesh and reduce poly-count in Blender

texts:
I'm not so familiar with 3D modelling, and I'm stuck on a simple task in Blender.

I have a fairly complex model that's been imported as a .DAE file from SketchUp. This model is composed of many polygons, not as one single mesh but in many components, in fact over many hundreds of surfaces.

As I said I'm new to Blender and want to learn. If I select one of the component surfaces, I can go into Edit mode and then use the Decimate modifier to reduce the poly-count.

But it doesn't want to let me do this if I select the whole object!

I think I need to combine all the surfaces into one mesh (?) and then apply the Decimate algorithm to gracefully reduce the poly-count.

I've managed to do this before but unfortunately I forgot how and I need to try again to get the balance right on the poly-count.

Appreciate the help.

Alex


texts:
I am making a game where the player gets chased by lava along a road.

From the road mesh i can access the points along each side. Currently i have an edge collider that moves along these points and once it reaches the player it's game over.

My problem is that i can't figure out how to make the lava follow the edge collider. Any ideas? I am using Unity.


texts:
I am currently developing a multiplayer html5 game, and the game has rpg elements (levels, items and such)

I just started working on the database side of things, and now I have a mongodb server setup with a basic user table (email, nickname, password hash and salt etc)

Now, each user should aquire items, and I am wondering should each user get his own collection in the db, or should there be a single collection that stores all the items, and has a email field that links the item to a user?


texts: Does a Standard Exist for Game Entity View Frustums

texts:
I was just recently adding the ability for my in-game entities to have their own Frustums, with the intentions of making them able to see enemies later down the road of my development cycle. My custom approach works great, but I find myself left with a suprisingly staggering question. What kind of perspective should my entities have? What is the standard for modern games? Here is a picture to show my implementation in action:

The Settings for that Frustum are as follows:

            // Just winging a random projection; worked pretty well, actually!
            Matrix4 entityProjectionMatrix = Matrix4.CreatePerspectiveFieldOfView(0.5f,1f, 0.1f, 50f);
            // Calculated by hand for testing purposes
            Matrix4 entityViewMatrix = new Matrix4(
                -0.02840426f, -0.1789574f, 0.9834467f, 0,
                0, 0.9838437f, 0.1790296f, 0,
                -0.9995965f, 0.005085204f, -0.02794535f, 0,
                50.50341f, 6.017713f, -46.88488f, 1);
            BoundingFrustum entityFrustum = new BoundingFrustum(entityViewMatrix * entityProjectionMatrix);

Now, clearly, those settings are a little lacking in the side-view peripheral department. I also don't think the entities should have a large frustum like players, who can see damn near anything(the player Frustum is absolutely massive). I feel as though something small, yet realistic would suffice, but I don't know if there is already a current standard for how much an entity should be able to see. I'm sorry if this question is broad, but it is a problem, and I am looking for some clarity/literature on the topic.


texts: I am trying to create a plugin and upload it online.But I do not want the users to be able to edit any of the content.Is that possible?

texts:
I am trying to create a plugin that can be uploaded into the unity asset store.I do not want the users to be able to edit the content.Functions should not be editable,just the variables should be editable.Is that possible? Or it would be still better if i could just hide the entire script.Any suggestions please ?The scripts are to be attached to the gameobject that will be active in the scene.
Thanks


texts: How to create data driven effects/abilities for collectable card game

texts:
I'm trying to create cards for a ccg/tcg that are completely "data-driven" from an xml/json/external file. I've read multiple articles on this issue already, even here on stack exchange, but i can't figure out how to actually code this. I have a simple example:

My two cards have the following abilities

1) "Increase the value of all adjacent red cards by 1"

2) "Increase the value of this card by the amount of all adjacent red cards"

In my code i have the following functions (pseudo) that i need to accomplish these effects:

Increase(targetCards, byValue) // increases a card's value by another value
FindCards(filter=adjacent) // returns all adjacent cards
FilterCardsBy(filter=isRed) // returns only red cards
Count(targetCards) // counts the number of cards

To create effect 1 i would use the functions like this:

Increase(FilterCards(FindCards(adjacent), isRed), 1);

and to create effect 2 i would use:

Increase(this, Count(FilterCards(FindCards(adjacent), isRed)));

So here's the problem:
I have no clue how i can describe these functions in my external file and also i have no clue how i actually tell my functions to work in this combination to achieve the desired effects.
Maybe i'm misunderstanding the concept here but as far as i understood and described here i can create some pseudo script/code in my external file that then my code can interpret and execute on. But i feel i somehow missing the middle part where i write code to interpret these commands i'm defining in the external file.

Anyone with experience here that can give me some super simple starter ideas on how to takle this. Especially the part where i can combine several functions into one.


texts:
Imagine a game with different types of characters or "actors" which can perform actions like walking and shooting. They are implemented using the state pattern to reduce the amount of coupling: each actor has a current state which can be one of the different possible state objects like DefaultState, ReloadingState or StunnedState which determine what happens when its methods like Reload(), Shoot() or Walk(direction) are called. Every frame the current state object updates the actor and returns the next state.

This works great for the player who doesn't need to know anything about the internals. However, an AI controller needs to know its character's current state to make intelligent decisions. For example, in the DefaultState the AI character would walk towards the nearest enemy while in StunnedState it would flee. It seems like every state should have its own AI routine, but how should this be implemented while trying to keep this logic separate from the actor class? The AI could query the actor for its current state and decide its actions based on that, but that would result in a bloated and messy if-else block. The State class shouldn't know anything about the AI so it cannot be in charge of changing the AI's state either. How can I implement an AI which chooses different actions based on the actor's current state while maintaining loose coupling?


texts:
Let's imagine we have a 60x60 grid (where a Tile is 64x64px). Within the viewport there should be 10 tiles. The player object is 32x32px.

To have smooth movement, I have to take delta time in consideration; and do something like:

this.player.x += 5 * dt;

To calculate viewports:

vX = parseInt(this.player.x); - Math.floor(0.5 * 10);
  if (vX < 0) vX = 0;
  if (vX+10 > 40) vX = 60 - 10;

  vY = parseInt(this.player.y); - Math.floor(0.5 * 10);
  if (vY < 0) vY = 0;
  if (vY+10 > 40) vY = 60 - 10;

And to render position of player:

this.context.rect((this.player.x - vX) * 64, (this.player.y - vY) * 64, 32, 32);

However I cannot get the math right.

How can I determine which tiles that should be rendered based on Canvas coordinates, in context to where the Player "actually" is on the tile grid. Basically I want to achieve this: https://stackoverflow.com/questions/11464550/html5-creating-a-viewport-for-canvas

But with smooth movement (and not jumping to one tile at a time).


texts: Why is Unity 5.6 displaying launch image wrong on iOS?

texts:
I updated from Unity 5.5.0p3 to 5.6.0f3, and I have no idea what's causing this. The iOS launch image which looked like this:

Now looks like this:


texts: How to pick a 3D object with known mouse coordinates if the camera is rotated 60 degrees?

texts:
I am making a simple game engine for a simple RTS game and would like to be able to pick a cube and move it around with the mouse coordinates. The problem is that my camera is rotated 60 degrees just like any RTS game and I am not sure how to use gluUnProject..

Thanks in advance!!


texts: Add navigation obstacles during runtime lags

texts:
Please watch this short video. http://screencast.com/t/vw2a5FdOOT It shows the problem.

It's using the build in Unity navigation and followed the guide to build the demo in the video.

Everytime I add a new obstacle than all agends pauses (hiccups) for a short time. I think this is because they have to recalculate a new path. How to make this recalculation in a background thread? I want to make a mace tower defense.

Thank you for reading an watching!


texts:
I'm trying to setup a simple ReorderableList in Unity 2017.3 for a list of enums. Adding items workes fine but selecting, dragging and deleting items from the list does not (see gif).

Here is my code:

[Serializable]
public enum RoofType { HIP, GABLE, FLAT, NONE }

UnityEditorInternal.ReorderableList roofTypeList = new UnityEditorInternal.ReorderableList(roofTypes, typeof(RoofType), true, true, true, true);
roofTypeList.drawHeaderCallback = (Rect rect) =>
{
   EditorGUI.LabelField(rect, "Roof types");
};
roofTypeList.drawElementCallback = (Rect rect, int index, bool isActive, bool isFocused) =>
{
   roofTypes[index] = (RoofType)EditorGUI.EnumPopup(rect, roofTypes[index]);
};
roofTypeList.DoLayoutList();

Any ideas why this does not work? My guess it is because I use enums and not classes but it is not documented anywhere.


texts:
I'm new to 3D-game programming and I'm having some trouble making objects rotate the way I want them to. I just read Glenn Fiedler's tutorials on game physics, awesome stuff by the way! (http://gafferongames.com/game-physics/physics-in-3d/)

Now, I'm trying to make a simple space sim. If you imagine a spaceship that is not yet rotated in any way (up = Vector3.Up etc..). If I apply some yaw-input (which would increase the angular velocity) I'd then expect the ship to rotate around the up-vector of the ship (which is also the world y-axis at the moment). That works fine. If I would then roll the ship a little bit, I'd expect the ship to roll around its forward axis, but it should also continue to spin around the world y-axis.

At the moment with my implementation instead of keeping it's momentum around the y-axis, it continues to spin around its local up-vector - which is obviously wrong.

I think I understand why this happens with my current implementation, I'm just not sure how to fix it.

This is what I have at the moment, with some minor simplifications (runs every update):

Vector3 addedRotation = new Vector3(pitchInput, yawInput, rollInput);
addedRotation = Vector3.Transform(addedRotation, rotation);
rotationVelocity += addedRotation;

rotation.Normalize();

Quaternion w = new Quaternion(rotationVelocity, 0);
rotation += Quaternion.Multiply(w * rotation, 0.5f);

I'd be very happy if someone could point me in the right direction here. If anything needs clarification, please tell me and I'll try explain it better.

Thanks for taking the time!


texts: How do i put random velocity in a Vector2?

texts:
I'm very new to C# scripting.
I want to use a random velocity for my Enemies using Vector2. Here's the code that I have done at the moment:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Enemy1 : MonoBehaviour
{
    [SerializeField]
    Rigidbody2D rb2d;

    [SerializeField]
    Vector2 vectorEnemysVelocity;

    [SerializeField]
    gameManager gameManager;

    [SerializeField]
    AudioSource source;

    [SerializeField]
    AudioClip deathSound;

    private void Awake()
    {
        gameManager = FindObjectOfType<gameManager>();
    }

    void Start()
    {
        MoveEnemy();
    }

    void MoveEnemy()
    {
        rb2d.velocity = vectorEnemysVelocity;
    }

    private void OnTriggerEnter2D(Collider2D collision)
    {
        if(collision.gameObject.layer == 8)
        {
            gameManager.GenerateGameOver();
            source.PlayOneShot(deathSound, 1f);
        }

        if (collision.gameObject.layer == 9)
        {
            Destroy(gameObject);
        }
    }
}

With this I can choose the velocity but as I said earlier I want it to be random. How can I do this?


texts: In a component/entity system, what's the correct way to implement entity-specific components?

texts:
I'm trying to create a basic C/E game engine for Android, and I'm trying to re-create pong as a basic warm-up. I currently have a EntityManager class that contains a list of all the UUIDs for its Entities, and has a render() function that calls render() on all Components that implement RenderableComponent (a basic interface with a render() function itself), and the same for update().

Stop me if I'm already doing something incorrectly...

My question is, should I be creating specific components that only apply to each entity? (E.g. a BallMovement, BallDraw, etc. component for the ball) or what is the correct way to create components for Entities?

Thanks in advance! (:


texts: Homing Fireball - Seiken Densetsu 3 style

texts:
I'd like to reproduce the fireball spell of Seiken Densetsu 3.
The Fireballs  don't follow the target directly, but encircle it more or less until they hit the target.

I have no idea how to reproduce this encircling.
I tried using the Forward Vector of my Fireball and adding it to the velocity. At the same time, the Rotation is slowly interpolated.

But no matter how I tweak the values, my fireballs mostly miss the target due to too slow rotation or the fireballs go straight to the target due to too fast rotation.

Does someone have a formula/ can point me into the right direction?
Here's a video on how the Fireballs in SD3 work:
https://youtu.be/PxtHGny88DM

Note how sometimes a fireball misses and encircles the target before it hits.


texts: How can I destroy a game object across the network in Unity?

texts: How do I go about destroying a game object across the whole network in a multiplayer scene in Unity? I can only get it to destroy on the local client and not for everybody else connected. I'm instantiating the object client side at runtime. Any pointers?


texts: Unity - custom Export and Import FBX Data

texts:
I am trying to write custom data inside a FBX file from 3dsmax at export time. This might be possible even if I don't know right now how to do that.
But my question would be how can I read those custom FBX data inside Unity on import.

Thanks a lot.


texts: Automatically create C# from manually created game objects

texts:
I have created 2 gameobjects along with its properties in the Unity Inspector.
I have attached a screenshot below.

For prototyping, I like the Inspector very much, but for runtime I prefer doing everything by scripts. This way nothing can go wrong: I don't have to carry so many files around, and I find it easier to understand everything.

I would now like to change this so that these 2 components are created at runtime by script.

Is there perhaps a way to automatically create the script that would create these game objects?

I would appreciate it very much if I could save some time with such an automatic script creation.

Thank you for any input.


texts:
I illumine model through model illumine of Phong. Ambient and diffuse light’s constituent work well, but specular works wrong. Under this message I sent screenshoots:
1) ambient and diffuse

2) ambinet + diffuse + specular.

Code shader's. Vertex's:

    cbuffer ConstantBufferVS
    {
    matrix World;
    matrix View;
    matrix Perspective;
    }

    struct VS_INPUT
    {
    float4 Pos: POSITION;
    float3 Normal: NORMAL;
    float4 Color: COLOR;
    };

    struct VS_OUTPUT
    {
    float4 Pos: SV_POSITION;
    float3 Normal: TEXCOORD0;
    float4 Color: COLOR0;
    float3 WorldPos: TEXCOORD1;
    };

    VS_OUTPUT main(VS_INPUT input)
    {
    VS_OUTPUT _out = (VS_OUTPUT)0;
    _out.Pos = mul(input.Pos, World);
    _out.Pos = mul(_out.Pos, View);
    _out.Pos = mul(_out.Pos, Perspective);
    _out.Normal = (float3)mul(float4(input.Normal, 1), World);
    _out.Color = input.Color;
    _out.WorldPos = (float3)mul(input.Pos, World); // position vertex in world
    return _out;
    }

Pixel's:

    cbuffer ConstantBufferPS
    {
    float4 Direction;
    float4 Color;
    float4 factors;
    float4 View; // position camera, 0, 2, -3
    }

    struct VS_INPUT
    {
    float4 Pos: SV_POSITION;
    float3 Normal: TEXCOORD0;
    float4 Color: COLOR0;
    float3 WorldPos: TEXCOORD1;
    };

    float4 main(VS_INPUT input): SV_Target
    {
    // ambient
    float4 ambient = (Color * factors.x) * input.Color;

    // diffuse
    float4 diffuse = saturate(dot((float3)Direction, input.Normal) * Color);

    // TODO
    // specular
    float4 specular = 0.0;
    float3 vView = normalize((float3)View - input.WorldPos); // vector from pixel towards eye
    float3 vReflect = reflect((float3)normalize(Direction), normalize(input.Normal)); // merror vector direction light
    // нормалью
    float spec = pow(dot(vReflect, vView), 64); // calculate spec
    specular = spec * factors.y * Color; // calculate specular light

    // multiply light's component's
    float4 out_color = (ambient + diffuse + specular) * input.Color;
    out_color.a = 1;

    return out_color;
    }

All the moments are commented on.


texts: How do I avoid big switches in my message system?

texts:
I've been implementing a message system for my small engine, and I have started to think about optimizing and maintaining it. Right now, my message class looks like this (at its simplest - only member variables):

typedef unsigned int MessageID;

class Message
{
    std::string message;
    MessageID messageID;
    MessageData* data;
};

At first I was only using std::string to recognize each event, and handling was done in cascade-if style:

void GUI_system::handleMessage(Message* message)
{
    if (message->message == "DELETE_HP")
    {
        deleteHearth(static_cast<AttInfo*>(message->data));

    }
    else if (message->message == "PAUSE_GAME")
    {
        showPauseIcon();
    }
}

However, I felt it is uncomfortable to work with, and for a switch I needed a numeric variable. This is why is MessageID is generated from unordered_map each time a message is created; each message has its own ID, and if not, a new one is created. So now it looks like this:

void GUI_system::handleMessage(Message* message)
{
    switch(message->messageID)
    {
        case 1 :
        {
            deleteHearth(static_cast<AttInfo*>(message->data));
            break;
        }
        case 2 :
        {
            showPauseIcon();
            break;
        }
    }
}

However, this was more confusing than the cascade-if style, where I at least had a little knowledge of what is going on, internally, apart from a plain int. I know enumerations are easier to use and implement, but this was the first method I tried, and I also wanted to try it the other way.

This brings me to my question; how do I avoid big switches in my message system? Should I just use enums?

My first suggestion was to create an unordered map of function pointers that define the behavior for a message, where the MessageIDs would act as keys, so the initialisation function would be defined in some init function, like this:

typedef void* func(Message*) messageF;

std::unordered_map<MessageID,messageF> _messageMap;

void GUI_system::InitBehaviorFunctions()
{
    _messageMap[MessageIDMapper::findID("DELETE_HP")] = deleteHearth;
    _messageMap[MessageIDMapper::findID("PAUSE_GAME")] = showPauseIcon;
}

void GUI_system::handleMessage(Message* message)
{
    //Or the right way as this is just a sketch
    _messageMap[message->messageID](message);
}


texts:
SmileBASIC (for Nintendo 3DS) comes with some sample programs.

I assume these are stored somewhere on the Micro SD card, but I cannot find them.  Where are they?  I would like to view the source on a PC.


texts: What information would I need to calculate proper placement of my Unity 3D orthographic HUD elements?

texts:
I have a Unity project and I have managed to create a 3D HUD by creating a separate (orthographic) camera for rendering elements on the UI layer.  I already have some objects appearing in the HUD and rendering correctly.

What I want to do now is calculate the proper position and scale of these elements to make sure they are in the upper left corner and only take up 60% of the vertical space.

I am optimistic the necessary information is available to C# script components, but I have no idea which formulas and which members or methods (probably on the Camera object) can tell me what the X/Y bounds of the orthographic view are (for whatever the current aspect ratio is).


texts: How to get the physics just right in a physics driven game

texts:
I'm working on a physics driven game using a java port of Bullet (JBullet).

In our game we have a ball that can have collisions with the other objects, including the objects that define the boundaries of the playing area.

Since we consider collisions between the ball and other objects as a very important aspect of the gameplay we wish to handle those collisions in our own code. This allows us to get non-realistic but very controllable behavior for the ball.

The other gameobjects also collide with each other, but JBullet handles those collisions well and we have no issues there.

The problem is that we have great difficulty triggering the custom behavior in the correct way. In our first set-up called our custom collision handling code every time JBullet reported a collision for the ball. This caused undesired behavior as a single hit could trigger multiple reported collisions. Which caused the ball to be sort of glued to the wall.

Our "fix" for this was to have the ball keep a timer and to ignore subsequent collisions occurring within let say 0.1 second of another. However, this caused ball to bounce through walls in some cases, probably because the first reported collision isn't the one we expect, and the ball-wall collision occurring shortly after is sadly ignored.

So that brings me to my question. How does one sort this out without resorting to all sort of "fixes" that only make the problem more complicated and less predictable?

Would for instance placing the ball at the last known position before the collision and handling the collision from there work? But what if another object has moved to that position in the mean time.

Or maybe calculate future collisions with the ball for non-moving objects and enforcing them if they are missed by the physics?

Any feedback / thoughts / revelations would be greatly appreciated!


texts: Opengl Es 1.1 Setting Different Transformations For Different Parts of Array

texts:
I have the following code:

glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

glPushMatrix();
glTranslatef(.03f * state, 0.0f, 0.0f);

state = 0;

glDrawArrays(GL_TRIANGLES, 0, LOC);

glPopMatrix();

I pop the matrix at the end so that I can apply a different transformation to a different part of the array. The problem is, when glPopMatrix() is present at the end of this code, the object drawn keeps wiggling instead of moving like its supposed to.

Note: State is set somewhere out of the loop and does not cause the draw function to stop working (as the function works without glPopMatrix()).


texts: Generating island terrains with Simplex Noise (C#/XNA)

texts:
I've got one little question: Is there any code or sample which shows how the simplex noise works? I cannot find anything about it... How should I implement it, without the knowledge how the algorithm works?...

The other question is: Is the simplex noise a good algorithm for island generation? I need huge islands (really huge), with different layers (sand, gras, stone) and clearly visible height-differences, which have soft-edges, so you can go out/into water without jumping over uneven surfaces.


texts:
my units have a function that returns a position (vec3) and a facing (quaternion) for any point in time.

A position and direction is perhaps called a ray or, in some contexts, a line segment; however, neither of these sounds appropriate in this context and neither normally has a quaternion...

What better name should a compound position and facing be called?


texts: How to define axis of Sprites in a CCAnimation?

texts:
I'm struggling to find how to define a kind of axis in my frames, when my sprite punches it moves back. I want to define the head as a pivot for the other sprites with different sizes.

How can I accomplish that?


texts:
I am writing a game using SharpDX with DirectX11 and I have been reading that it is important to apply gamma correction to my engine in order to perform correct linear lighting calculations.

So I modified the function which loads my diffuse texture maps so that it uses R8G8B8A8_UNorm_SRgb format rather than R8G8B8A8_UNorm.  I then modified my framebuffer format so that it also uses R8G8B8A8_UNorm_SRgb.

It was my understanding that this would use hardware to remove gamma correction from my textures allowing me to perform linear lighting calculations and then reapply gamma correction when rendering the final scene to the frame buffer.

However when I do this the scene looks washed out and too bright.  My next step was to take a look at some gamma calibration charts Gamma Calibration Chart.  When viewing this chart in my browser I get a value of approximately 2.2.

I then loaded this chart into my engine and rendered it to screen.  When using R8G8B8A8_UNorm I get the same value (approximately 2.2) but when using R8G8B8A8_UNorm_SRgb I get a value around 1.2.

It seems like the scene has already been gamma corrected somehow.  Is this the case, what am I missing?


texts:
I'm new with Unity and I'm working on recreating memory game. I found this sample: http://xtasestudios.com/unity/samples (select "Memory"). I decided for C#.

I've created my own card in Blender, added 3 different materials (without textures), also I created flip-flop animations. After importing .blend file in Unity and assigning scripts, textures, animations, positioning camera etc..

Everything works fine, except textures on cards.
I can change color on cards, but when I want to see any texture on my card, I see only color, not whole texture. I really have no idea why is this happening and how to fix it.

Any help will be appreciated!


texts:
I'm coding a Bidirectional Path Tracing application for school in C++ and I have some questions (I haven't found useful explanations on the web)

1) Why does the EyePath have one more vertex?

2) When I compute the direct illumination during the EyePath creation, do I need to take account of the value of the previous vertex? I'm asking that because I saw it in some code but it seems weird.

3) I don't understand very well how to connect both paths. Randomly? Everyone with everyone? For the moment I randomly connect one vertex with another one.

4) Our PBRT book implements a contribution according to Eyepath and LightPath length. Do I need to do it, given that all the objects in my scene geometry are diffuse?

5) Are new rays randomly generated in a hemisphere at every bounce?

All objects are diffuse.

For the moment I get this result with 15 samples:

6) Do you have any idea what's going on ?

Thanks you for all of your replies :)


texts:
I'm trying to Instantiate a prefab when the mouse goes over collider of some GameObject so I'm using OnMouseEnter to instantiate and will use OnMouseExit to destroy it after (when this part of code works fine), the problem is that no error appears in the console but the prefab are not being instantiated, does not appear in the inspector or in the scene, even so, when I print it's name in the console (last line), it appears right. Is my syntax correct?

void OnMouseEnter ()
{
    string nomeSeta = "SETA" + direcao.getNome ();
    GameObject seta = Resources.Load<GameObject> (nomeSeta);
    float[] pontosXeZ = Util_CalculosGeometricos.ObterPontosCentraisXeZDeUmRetanguloPorNumeracaoSemRotacao (terrenoPai, direcao.getCoeficienteHorario ());
    seta.transform.localPosition = new Vector3 (pontosXeZ [0], 0.0f, pontosXeZ [1]);
    seta.name = nomeSeta;
    print ("seta.name: " + seta.name);
}


texts:
Alright, so before you down vote saying that OpenGL doesn't support rays for rendering, please read:

So I want to detect a quad in opengl 1.1( I don't want to use opengl 3.0). I wanted to detect it using OpenGL, but that doesn't seem possible.

But basically I have one choice, which is kind of "hacky". I create custom matrices and store the transformed vertices somewhere, then do a simple collision test.

What is the common way of doing ray-tracing in legacy OpenGL?


texts:
When attempting to draw a line in 3D space with D3DPT_LINELIST, then Direct3D gives me an error about an invalid vertex declaration, saying that it cannot be converted to an FVF. I am using the same vertex declaration and shader/stream setup as for my D3DPT_TRIANGLELIST rendering which works absolutely correctly.

How can I use D3DPT_LINELIST to render some lines in 3D space?

Edit: Here's my raw Draw call.

D3DCALL(device->SetStreamSource(1, PerBoneBuffer.get(), 0, sizeof(PerInstanceData)));
D3DCALL(device->SetStreamSourceFreq(1, D3DSTREAMSOURCE_INSTANCEDATA | 1));
D3DCALL(device->SetStreamSource(0, LineVerts, 0, sizeof(D3DXVECTOR3)));
D3DCALL(device->SetStreamSourceFreq(0, D3DSTREAMSOURCE_INDEXEDDATA | lines.size()));
D3DCALL(device->SetIndices(LineIndices));
PerInstanceData* data;
std::vector<Wide::Render::Line*> lines_vec(lines.begin(), lines.end());
D3DCALL(PerBoneBuffer->Lock(0, lines.size() * sizeof(PerInstanceData), reinterpret_cast<void**>(&data), D3DLOCK_DISCARD));
std::for_each(lines.begin(), lines.end(), [&](Wide::Render::Line* ptr) {
    data->Color = D3DXColor(ptr->Colour);
    D3DXMATRIXA16 Translate, Scale, Rotate;
    D3DXMatrixTranslation(&Translate, ptr->Start.x, ptr->Start.y, ptr->Start.z);
    D3DXMatrixScaling(&Scale, ptr->Scale, 1, 1);
    D3DXMatrixRotationQuaternion(&Rotate, &D3DQuaternion(ptr->Rotation));
    data->World = Scale * Rotate * Translate;
});
D3DCALL(PerBoneBuffer->Unlock());
D3DCALL(device->DrawIndexedPrimitive(D3DPRIMITIVETYPE::D3DPT_LINELIST, 0, 0, 2, 0, 1));

Here's my vertex declaration:

D3DVERTEXELEMENT9 BasicMeshVertices[] = {
    {0, 0, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_POSITION, 0},
    {1, 0, D3DDECLTYPE_FLOAT4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 0},
    {1, 16, D3DDECLTYPE_FLOAT4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 1},
    {1, 32, D3DDECLTYPE_FLOAT4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 2},
    {1, 48, D3DDECLTYPE_FLOAT4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 3},
    {1, 64, D3DDECLTYPE_FLOAT4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_COLOR, 0},
    D3DDECL_END()
};

The LineIndices are just 0, 1 and the LineVerts are just {0,0,0} and {1,0,0}, to represent a unit 3D line along the X axis.


texts: A* pathfinding takes too long, shortcuts needed

texts:
So I have a game where the player can move on a grid 108 X 192 large. It uses a simple A* path-finding algorithm to move. Unfortunately, After 0.03 seconds, it would have only looked at about 300 nodes, meaning that if the end node is blocked from passage, it would take about 2 seconds for it to realize this (A* without optimizations returns failed when the open list is empty, when it has inspected every path and realized there was no solution). And I want at least 20 fps!

I have not used any optimizations, and each point in the grid is a boolean blocked or unblocked. Any ways to speed it up?

For example, in Dota 2 (a popular MOBA), the map is full of trees and cliffs, and is 15,000 game units by 15,000 game units big, but the character starts moving as soon as you click where you want it to go. How do they do that, and is it a simple thing I am missing?


texts: My Java Game's movement looks awfull. Maybe Problem with Thread.sleep

texts:
I have a big problem with my Java games. In every game I make the movement of the player and objects just looks awfull. The framerate is 60 fps without any problems. But the movement looks extremly unsmooth. I tried several things but nothing worked. The game code is too long and unstructured to show the hole one but here are some parts that may cause the problem:

this.repaint();

//Framerate
try {
    Thread.sleep(15);
} catch (InterruptedException e) {
    e.printStackTrace();
}

and that's how I tested the framerate:

 //FPS anzeigen

    if(RaumNr >= 0){

        FPSCount += timesincelastframe;
        howoften ++;
        if(FPSCount > 1){
            FPSCount = 0;
            FPS = howoften;
            howoften = 0;
            System.out.println(FPS);
        }
    }

That's how my delta time system works:

 while(true){

        long thisframe = System.currentTimeMillis();
        timesincelastframe = ((float) (lastframe - thisframe)) / -1000f;
        lastframe = thisframe;

        if(!M.hasFocus())
            M.requestFocus();

and so on.

    super.paintComponent(g);

    Graphics2D g2d = (Graphics2D) g;

    g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

    g2d.scale(BreiteMulti, HöheMulti);

And that's how I move the player for example:

 x -= 350 * timesincelastframe * speed;

I hope you have any ideas wht the problem might be. If you need more code examples please tell me.


texts: Help with moving object to mouse position

texts:
I'm trying to make an object follow my cursor using raycasting. I'm creating the raycast each frame and checking the player's distance from the hit and whether or not the hit landed on an object tagged 'surface'. The code works fine with only one of those conditions, e.g. if I just check for the surface tag or just check the range, but when checking for both the object will only move to a few certain (apparently random) positions on the surface.
        if (Physics.Raycast(ray, out hit))
        {
                if (hit.transform.tag == "Surface" && Vector3.Distance(player.transform.position, hit.point) < range)
                {
                    obj.transform.Find("holo").gameObject.SetActive(true);
                    obj.transform.position = new Vector3(hit.point.x, hit.point.y + 0.5f, hit.point.z);
                }
            }

At first, I thought maybe the double condition was causing lag, but I have a powerful pc and I struggle to believe that two conditions in a frame are enough to create a noticeable loss in performance.
Video of the bug: https://youtu.be/mLug2ThX2hg ,
Full script just in case: https://pastebin.com/ruUXivsc
Any pointers would be greatly appreciated :)


texts:
I've recently been working on a fairly complicated game. I've stored information with local storage, but that allows the player to edit it, and does not transfer from computer to computer. The two scripts run on a single server, and I use the following to ping the php server:

function initiateLoginSequence() {
    var isnewplayer=prompt("Hello! Are you new?(Y/N)");
    if(isnewplayer.equalsIgnoreCase("N")) {
        var username = prompt("Enter username.");
        var password = prompt("Enter Password.");
        //parsing code goes here later.
    } else {
        var username = prompt("Enter a username. This will be used for future logins.");
        var password = prompt("Enter a password. This will be used for future logins.","*");
        var req = new XMLHttpRequest();
        req.open('POST', 'http://69.144.34.106/Scores.php', true);
        req.send("returning=false"+"&name="+username+"&pw="+password+"&level="+lvl+"&save=true");
        req.send();
    }
}

I then process the results with this:

<?php
   $returning=_POST["returning"];
   $save=_POST["save"]
   $password=_POST["pw"];
   $username=_POST["name"];
   $score=_POST["lvl"];
   $connection=mysql_connect("localhost:3306","****","*****");
   if($returning=="false" && $save=="true") {
     mysql_select_db("userdata",$connection);
     $sqlcmd = "CREATE TABLE ".$username."(
     Username varchar(".$username.")
     Password varchar(".$password.")
     Score varchar(".$score.")
     )";
     mysql_query($sqlcmd);
   } else if($save==false) {
     $sqlcmd="SELECT * FROM userdata"
     $result = mysql_query($sqlcmd);
     while($row=mysql_fetch_array($result)) {
        if($row['Username']==$username && $row['Password']) {
            echo row['Score'];
        }
     }
   } else if($save==true) {
     $sqlcmd="SELECT * FROM userdata"
     $result = mysql_query($sqlcmd);
     while($row=mysql_fetch_array($result)) {
        row['Username']=$username
        row['Password']=$Password
        row['Score']=$Score
     }
   }
?>

But after creating the mysql database, nothing is populated. So my basic question is, Am I doing this right? If not, what am I missing?


texts: How to solve ArrayList outOfBoundsExeption?

texts:
I'm getting:

    09-02 17:15:39.140: E/AndroidRuntime(533): java.lang.IndexOutOfBoundsException: Invalid index 1, size is 1
    09-02 17:15:39.140: E/AndroidRuntime(533):  at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:251)

when I'm killing enemies using this method:

    private void checkCollision() {
    Rect h1 = happy.getBounds();
    for (int i = 0; i < enemies.size(); i++) {
        for (int j = 0; j < bullets.size(); j++) {
            Rect b1 = bullets.get(j).getBounds();
            Rect e1 = enemies.get(i).getBounds();
            if (b1.intersect(e1)) {
                enemies.get(i).damageHP(5);
                bullets.remove(j);
                Log.d("TAG", "HERE: LOLTHEYTOUCHED");
            }
            if (h1.intersect(e1)){
                happy.damageHP(5);
            }
            if(enemies.get(i).getHP() <= 0){
                enemies.remove(i);
            }
            if(happy.getHP() <= 0){
                //end-screen                           !!!!!!!
            }
        }
    }
}

using this ArrayList:

        private ArrayList<Enemy> enemies = new ArrayList<Enemy>();

and adding to array like this:

   public void createEnemies() {
    Bitmap bmp = BitmapFactory.decodeResource(getResources(),
            R.drawable.female);
    if (enemyCounter < 24) {
        enemies.add(new Enemy(bmp, this, controls));
    }
    enemyCounter++;
}

I don't really understand what the problem is, I've been looking around for a while but can't really find anything that helps me. If you know or if you can link me someplace where they have a solution for a similar problem I'll be a very happy camper!


texts: Is screenplay for a low budget to no budget indie game necessary?

texts:
i'd love any advice about knowing if screenplay for indie games are necessary or not.

i've seen loads of successful and unsuccessful games that dont require them,

the only issue is, im a 3d artist not a writer, and in triple A title movies there are a max of 100 pages of screen play, though in games its around 600 pages.

thank you for any help!


texts:
I want to detect if a device uses WVGA, WXGA, 720p or 1080p resolution. In addition, I want to store the resolution of the device in a variable. For example, if the resolution is 800x480 pixel, then the variable has the value: string CurrentResolution = "720p".

How can I do that? How can I detect the screen resolution of a Windows Phone device?


texts: Where do the buffer values come from when rendering?

texts:
In the textbook I am reading, it talks about fragment tests that are performed when rendering.

All of these tests involve comparing the current fragment x value (x can be alpha, color, etc.) with a corresponding buffer value, and doing something in case the test passes. The test is usually a comparison between those two values (for example, >=, <=, etc.).

What I cannot understand is where do these buffer values come from in the first place?

Are these previous values? If so, what do the current values have to do with previously calculated values?

I don't even know what to search in google for this topic. Sorry if it is a total starter question. I am currently reading about rendering for the first time


texts:
I'm trying to implement a camera that tracks a 3D model in my game. I've taken a look at this MSDN article on creating a 3rd person camera, as well as experimenting on my own; but I don't get the correct result.

My camera follows behind my model correctly, until I rotate the model about the y-axis. In this case, the camera seems to fly off to one side or the other.

What I want, is when the model is rotated to the left the camera will remain behind it; so as too mimic the view that can been seen in the left image (minus the fact that the rest of the world will display the rotation). I have tried looking around for tracking camera implementations, but to no avail.

Here is the code I use to calculate the position and look-at vectors of the camera:

// Calculate the offset vector
Vector3 offset = new Vector3(0.0f, this.DistanceAboveTarget, -this.DistanceBehindTarget);

// Transform the offset by the target's rotation
float targetRotation = mTarget.Rotation.Y;
Matrix rotationMatrix = Matrix.CreateRotationY(targetRotation);

Vector3 transformedOffset = Vector3.Transform(offset, rotationMatrix);

// Calculate the new position and look at vectors
Vector3 targetPosition = mTarget.Position;
mLookAt = targetPosition;

mPosition = targetPosition + transformedOffset;

EDIT

All other matrices are calculate elsewhere in my code and are correct, so far as I understand. Full code samples can be found in the below links:

TrackingCamera
GameModel
SandboxGame


texts: How to encourage players to not lessen their own gaming experience with mods and cheats?

texts:
In many games (often single-player computer games) there's a built-in way to alter gaming experience; either by modding (e.g. Minecraft, most games on Steam Workshop and Nexus Mods) or by some in-game way to cheat (console commands or retro-style cheat codes). And even if there is no native support, life will find a way. This can be an amazing asset to any players for several reasons:

It can enhance your gaming experience by adding new content (levels, quests, items, etc.).
It can remove / change features you dislike about a game (perhaps you dislike the 10 minute long game intro where you cannot move. I'm looking at you, Skyrim!)
It helps you have some stupid fun (what happens if every force applied to a rag-doll is multiplied by x10?)

These are all great things, but from experience and observation it's very clear that these things can have the complete opposite effect:

New content can be utterly broken and unbalanced (instant-kill weapon).
Removing features can lessen gameplay (I don't like questing; let's remove all quests).
Remove the need to actually do anything (I need to gather 1000 gold to buy this item? give_gold 1000).

Of course what a player finds fun and what might run their experience is completely subjective, which is why I'm not wanting to remove these features, just discourage extensive the use of them. Because the problem here is not that the player is able to do these things; the problem is that the player is unable to see that it might affect their gaming experience in a negative fashion and when it does they are often unable to localize the problem and its source leading to them getting bored of the game because of their own actions.

So my question is this; How do I give players all of the benefits of altering my game but also make them understand that it might lessen their gaming experience so that they (themselves) can regulate their use of it? Again note that I'm not trying to completely prevent it; only discourage it.


texts: How to make an enemy projectile head to the player's position with constant speed

texts:
How can I dynamically set the movement speed of the X and Y of the projectile so that it moves at a constant speed when the projectile heads at the player's position? I know this has something to do with vectors but I don't really have an idea how to do it. My current implementation of the speed is getting the difference of the x and y positions so what happens is that the projectile will be slower the nearer the player is to the enemy. I set the projectile's speed using the code below:

projectile.moveSpeedX = Math.abs(position.x - targetPlayer.position.x);
projectile.moveSpeedY = Math.abs(position.y - targetPlayer.position.y);

Below is the contents of the update(float delta) method of the projectile:

if(xdirection == LEFT) {
    position.x -= moveSpeedX * delta;
}
else if(xdirection == RIGHT) {
    position.x += moveSpeedX * delta;
}

if(ydirection == UP){
    position.y -= moveSpeedY * delta;
}
else if(ydirection == DOWN) {
    position.y += moveSpeedY * delta;
}

The movement will slow down when the player is near the enemy since the distance between them is small. The speed is the problem although this already makes the projectile head to the player's position.


texts: How to make money from creating a game for Windows?

texts:
I'm going to create a game. Well, a set of games, but they will accrue little by little.
So, at the beginning there will be one game.

The game will be written in C# with WPF and WCF techs, including server-side game processing, statistics and so on.

And yeah, I just have quit my current job in one company, so I need to live on.

So, how to start making money on this wonderful development? It will make much pleasure for me, as soon as I like developing and actually playing those games (gomoku, sea battle, etc)?

I only see two ways — one of them is to find an investor and the other one is to complete at least one game with 100% server uptime and start distributing it.

But I need recommendations. I need help, actually — the explanation how exactly to do all of this things and to to not starve:) .


texts: Should I compress WebSocket payload data in a game where latency matters?

texts:
I have started work on a new game project where users are in an open environment and fight each other in a fast-paced shoot-out. I know that compressing all of the WebSocket's payload data using zlib can be a significant improvement over non-compressed data in terms of bandwidth, but does the latency of packing/unpacking data have more advantages over not packing it?

I know using zlib on the data can have some advantages - less bandwidth and harder for hackers to read the data, but it also has a disadvantage - takes time to [un]pack.

Should I use zlib in a game where latency could be the difference between life or death?


texts: Java: AI to make a mob face the player working half-way correctly

texts:
While creating some basic AI for my "ghost" mob that is just up for testing at the moment, I thought of allowing it to face the player, depending on the player location. I get it to work correctly, but it doesn't act exactly as I want it to. Here is the current code I use for when getting the ghost to face the location of the player:

if (player.getX() < this.getX())
    dir = 3;
else if (player.getX() > this.getX())
    dir = 1;
else if (player.getY() < this.getY())
    dir = 0;
else if (player.getY() > this.getY())
    dir = 2;

It will switch viewing position as I want along the x-axis, but along the y-axis I have to be exactly lined up for it to face me as so (the sprite below the first one is the player, I am just using the same sprite for the ghost at the moment):

As long as I am down there I would like it to face that location, but if I adjust one pixel this happens:

For the mapping, I want it to act similar to this, positions will change within a certain range is what I really want though, so if I were to move to the left side of the ghost, it would switch to that view, but if I were to stay at the bottom, I want it to stay facing that way:

My problem is that I want the ghost to face the player depending on the location, and I just can only get it to face the way I want it to on the x-axis, and not how I want on the y-axis, I have to be exactly lined up by the pixel for the y-axis for the ghost to face the player vertically. How would I accomplish this?


texts: creating a trigger to play multiple animations at once

texts:
I need a "button" like trigger. The player would walk within the invisible cube that is the trigger, once the player is in the trigger (and only in the trigger) they would be able to press 'e' on their keyboard which will cause the animations to play at once. After the animation plays, the screen fades to black and loads the next scene.

I'm still incredibly new to Unity so a brief summary of the code you provide would be much appreciated! (but not at all demanded!)

Personally I'm a lot more comfortable with C# so if the code can be in that, it would really help. Thank you!


texts: How to get enemy to follow character using angles? (atan2)

texts:
I have an enemy and a character to control. I want to get the enemy to follow the character in a straight line. I already found the angle in which the enemy needs to travel.

double angle = Math.atan2(y, x) * 180 / Math.PI;

Now, let's say it return 73.0. What do I do with that number? And what if it's a negative angle.

BTW, I'm using dx(dynamic x) and dy(dynamic y) to control movement.


texts: Could stealth and chase mechanics suit well for an exploration / branching paths game?

texts:
Our game focuses on exploring a city searching for clues and learning new skills to reach new locations to find something very valuable to the protagonist.

The game design is based on two ideas:

Choices through gameplay. Instead of explicitly making the action of "choice", the outcome of a level objective is what makes the choice. For example: Gary's Eevee evolves into 3 different Pokémon depending on your previous battles with him in Pokémon Yellow. It's not something you chose; it's something that happened while you tried to win or lose against him.
Real time actions. While you are doing an action (i.e. Jump over a fence), you may be interrupted by something or some NPC, and the resulting outcome differs a lot from the one expected by the player.

When we started testing the first levels, we noticed that the player may get bored exploring the streets of the city.
The protagonist is a small sized animal (like an adult pet dog), and we wanted to make the scale of the city realistic relative to the main character, so in comparison the size differences of both protagonist and levels are huge.

So we thought of adding stealth and pursuit mechanics (the protagonist, as an animal, would have to avoid animal rescuers). Both of these mechanics seem to fit very well within the two main game ideas. But when it comes to implementing them, it becomes a huge hassle.

Firstly, the player will be forced to escape once a pursuit sequence happens, trying to find a good hiding place, and will not stop to think where they should go.
Then we have the problem that the game doesn't have a proper Game Over concept, but just bad endings, so we don't know how we should handle what will happen if the protagonist is caught. The only current possible "Game Over" situation is to starve (which on a normal gameplay would be almost impossible to achieve), and you'd have to start over from the very beginning because its considered a bad ending of the game. Getting caught might happen much more often, so if we do the same as for starting, it would be extremely frustrating for the player to play all the way from the beginning.
Another problem, which is more production wise, is that it may turn out to be so time consuming to implement the AI of each NPC that may chase over the player, since we'd want to include factors such as personality, number of encounters with said NPC and the time the player has been within that NPC's FOV, and make a variation of pathfinding for these kind of Al's (we have to do it manually since we're using a custom engine).
Also, we may have to rethink the design of certain streets and areas, which may alter the layout of the town, which is tightly designed after the branching story, the main axle of the game.

Is there a better way to include these stealth and chase mechanics, that minimize the occurrence of these problems? If not, would there be anotjer workaround?


texts: Electricity effect using XNA and Shaders

texts: I'm looking for a shader or sample that does an electricity or lines-of-force effect between two points that can be used with XNA 3.1.


texts: Narrow-phase collision detection algorithms

texts:
There are three phases of collision detection.

Broadphase: It loops between all objecs that can interact, false positives are allowed, if it would speed up the loop.
Narrowphase: Determines whether they collide, and sometimes, how, no false positives
Resolution: Resolves the collision.

The question I'm asking is about the narrowphase. There are multiple algorithms, differing in complexity and accuracy.

Hitbox intersection: This is an a-posteriori algorithm, that has the lowest complexity, but also isn't too accurate,
Color intersection: Hitbox intersection for each pixel, a-posteriori, pixel-perfect, not accuratee in regards to time, higher complexity
Separating axis theorem: This is used more often, accurate for triangles, however, a-posteriori, as it can't find the edge, when taking last frame in account, it's more stable
Linear raycasting: A-priori algorithm, useful for semi-realistic-looking physics, finds the intersection point, even more accurate than SAT, but with more complexity
Spline interpolation: A-priori, even more accurate than linear rays, even more coplexity.

There are probably many more that I've forgot about. The question is, in when is it better to use SAT, when rays, when splines, and whether there is anything better.


texts: Child object free movement on Parent object

texts:
Just to be straightforward, I am completely new to many aspects of coding and am searching for different specs and guidelines to aid me on my journey to crafting a wonderful game in Epic Games' Unreal Engine 4.

Okay, I know upon viewing this, some may have little to no clue what I mean, so I'll put it like this to explain what I mean :

Imagine a third person game with a simple model of a character. Now, say I have an object as a torso of a character in a game. Now Say I have an object as a head of the character. How could I keep the head as a child of the torso, but at the same time, allow it to move with the camera angle.


texts: Camera rotation according to target direction

texts: I am facing issue when camera is following to my target and target rotates to 90 degree or -90 degree than camera is not rotating.i want smooth rotation according to target when target is change the direction of movement.please help me if you can..thanks in advance.


texts: text wrapping on a texture applied to a 3D model

texts:
How would I create and implement a texture of text that wraps around a 3D model? The texture will just be white and you should be able to add text to it, but I need to create this so that when the texture is wrapped around a model of a person, the person is then composed of lines of text and the lines should not be distorted.

In my head the way I would do it is to put the flattened texture in a file, and draw text on to it. Is this the best way? are there any issues that I'm unaware of that I might come across?


texts:
i want drawing bitmap outline

Now Drawing

Device.DrawBitmap(mBitmap, GetBound(), Opacity, d2.BitmapInterpolationMode.Linear);

// mBitmap as SharpDX.Direct2D1.Bitmap

// GetBound() as Bitmap Bound


texts: Why is my depth buffer texture so bright?

texts:
https://www.youtube.com/watch?v=QuvAEqgHrMY&feature=youtu.be

https://www.youtube.com/watch?v=5ob1JsPIGAs&feature=youtu.be

gluPerspective(60, (float)CONTEXT_WIDTH / CONTEXT_HEIGHT, 0.1f, 1.f); //values used for first video
gluPerspective(60, (float)CONTEXT_WIDTH / CONTEXT_HEIGHT, 0.1f, 2000.f);//values used for second video, the further z clip value seems to improve the depth rendered, but far from example images below.

I set my projection matrix with gluPerspective.

This seems to happen when I try gluPerspective; when I set my projection matrix to first person.

The type of image I would like to get is

Is the visual result I am getting correct? Then are the listed examples of depth buffer images are merely a result of refining post rendering process, that are simply added in order for humans to see it better?


texts: List has no value after adding values in

texts:
I am creating a a ghost sprite that will mimic the main sprite after 10 seconds of the game. I am storing the users movements in a List<string> and i am using a foreach loop to run the movements. The problem is when i run through the game by adding breakpoints the movements are being added to the List<string> but when the foreach runs it shows that the list has nothing in it. Why does it do that? How can i fix it?

this is what i have:

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

    public void UpdateGhost(float scalingFactor, int[,] map)
    {

        // At this foreach, ghostMovements has nothing in it
        foreach (string s in ghostMovements)
        {
            // current position of the ghost on the tiles
            int mapX = (int)(ghostPostition.X / scalingFactor);
            int mapY = (int)(ghostPostition.Y / scalingFactor);

            if (s == "left")
            {
                switch (ghostDirection)
                {
                    case ghostFacingUp:
                        angle = 1.6f;
                        ghostDirection = ghostFacingRight;
                        Program.form.direction = "";
                        break;

                    case ghostFacingRight:
                        angle = 3.15f;
                        ghostDirection = ghostFacingDown;
                        Program.form.direction = "";
                        break;

                    case ghostFacingDown:
                        angle = -1.6f;
                        ghostDirection = ghostFacingLeft;
                        Program.form.direction = "";
                        break;

                    case ghostFacingLeft:
                        angle = 0.0f;
                        ghostDirection = ghostFacingUp;
                        Program.form.direction = "";
                        break;

                }
            }
        }
    }

    // The movement is captured here and added to the list
    public void captureMovement()
    {
        ghostMovements.Add(Program.form.direction);
    }

EDIT:

    // Ghost is the name of the class that creates the ghost sprite
    // as well as where captureMovement() is in.
    Ghost ghost = new Ghost();

    // This update is in a class named turtle
    public void Update(float scalingFactor, int[,] map)
    {
        // current position of the turtle on the tiles
        int mapX = (int)(turtlePosition.X / scalingFactor);
        int mapY = (int)(turtlePosition.Y / scalingFactor);

        //The rest of the code that contains the captureMovement method being called
        //looks the same as the if statement with just different directions.
        if (Program.form.direction == "left")
        {
            ghost.captureMovement();
            switch (turtleDirection)
            {
                case turtleFacingUp:
                    angle = 1.6f;
                    turtleDirection = turtleFacingRight;
                    Program.form.direction = "";
                    break;

                case turtleFacingRight:
                    angle = 3.15f;
                    turtleDirection = turtleFacingDown;
                    Program.form.direction = "";
                    break;

                case turtleFacingDown:
                    angle = -1.6f;
                    turtleDirection = turtleFacingLeft;
                    Program.form.direction = "";
                    break;

                case turtleFacingLeft:
                    angle = 0.0f;
                    turtleDirection = turtleFacingUp;
                    Program.form.direction = "";
                    break;

            }
        }
    }

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

        turtle.Update(scalingFactor, map);
        ghost.UpdateGhost(scalingFactor, map);

        base.Update(gameTime);
    }


texts: Confused with how I should organize my code in a 2D game using OpenGL

texts:
I've just now started learning OpenGL and I'm getting very overwhelmed and confused with some things. I don't want to permaturely optimize things, but I also don't make decisions about things I still don't fully understand.

Question 1: I know that immediate mode compared to the use of VBOs in OpenGL is primitive and slow, but how much does it really matter for a 2D game, unless I start rendering tens of thousands sprites? At which point does it really justify the hassle of having to go through all that tedious process of the modern OpenGL? (I know modern OpenGL is a better practice, I am just legitimately curious!)

Question 2: I'm making a 2D game, it is going to implement particles, a few sprites, raycasted shadows and some blending tricks. My question is, do I keep one VAO and VBO for each Sprite, or do I create all the sprites in one single VBO / VAO? If so, how do I do that, how should my code be structured? I'm very confused as to how I should batch the draw calls.

Question 3: Is it significantly expensive to swap shaders? How do I handle multiple shaders? I thought about categorizing the objects and join the ones that have the same shader together for drawing, so I don't have to switch shaders as much, but I wasn't sure if it was worth the hassle.


texts: AlphaToCoverage + Alpha Blending = Artifacts

texts:
I'm experiencing a strange problem using OpenGL SampleAlphaToCoverage mode. There are rendering artifacts when using alpha-blending on pixels that have been rendered using alpha-to-coverage - and I can't explain why.

Here's the basic setup:

Render the world. Some batches of vertices are rendered using alpha-to-coverage. Blending is never enabled at this stage.
Disable depth testing an render a screen overlay. At this point I'm using alpha blending. Alpha-to-coverage is never enabled at this stage.

I'm using alpha-to-coverage on the airplanes glass window. This is what the scene looks like:

Everything works as expected so far. However, as soon the screen overlays alpha blending is drawn at a screen location where alpha-to-coverage has been previously active, I'm getting this:

Note that there is no error as long as blending affects different pixels than alpha-to-coverage!

I also tested the following cases:

Use alpha-to-coverage for the overlay instead of alpha blending: No artifacts.
Clear the entire screen before rendering the screen overlay: No artifacts.
Clear all buffers except the color buffer: Artifacts
Clear only the color buffer: No artifacts

The screen overlay item in question consists of a single textured Quad. The texture is 256x256.

You can download the test application at http://www.fetzenet.de/atc_error.zip
Camera controls are WASD + Mouse (Hold left or right button)

Does anyone have a clue whats going on here? Also, can anyone reproduce this behavior?


texts: does cocos2d cache texture automatically

texts:
I know if we want the textures cached we can use the sharedtexture manager to cache them, but since this is on mobile platform , why don't cocos2d-x just do this for all texture loads ?

when creating sprites with images, are these textures cached as well ?


texts: StartCoroutine from other MonoBehaviour is not working

texts:
I am trying to replicate the model of Unity documentation about coroutines, but I want to partition it in another class:

I have these two:

public class A: MonoBehaviour {

    void Start() {
        print("Starting " + Time.time);
        B test = new B();
        StartCoroutine(test.WaitAndPrint(2.0F));
        print("Before WaitAndPrint Finishes " + Time.time);
    }
}

public class B: MonoBehaviour {

    public IEnumerator WaitAndPrint(float waitTime) {
        yield return new WaitForSeconds(waitTime);
        print("WaitAndPrint " + Time.time);
    }
}

It prints, ignoring the coroutine:

Starting 0
Before WaitAndPrint Finishes 0

The two methods work well in the same class.


texts: Libgdx fix small objects on android devices

texts:
I'm having issues with optimizing my game for android.
I've basically created a simple menu with two buttons (see pictures below)!
The size of the window is 720x480px ( in the Desktop Launcher ). My Problem is now the following: On my PC everything looks fine, but when launching my game on an android device, everything is "zoomed out" too much! This is obviously caused by the resolution (1440 x 2560 pixels). My question is now: How do I "scale" the screen correctly, so that it look identical with the desktop version?

Desktop

Android

CODE: http://pastebin.com/HtMfd4Jz


texts: Scaling world - projection, view or separate matrix?

texts:
I am currently writing a simple 3D space visualisation program.
Things get loaded into it from a simple XML file, which contains positions and sizes of objects in space, so you can put basically any numbers into the XML and it will show you what the things look like in 3D.

My problem is that when I try view for example a solar system, using real numbers as they really are in space (e. g. earth-moon distance = 3.844e8 m), my objects loose their form and textures get detached from faces due to limited floating position precision. I simply can't make users to scale the scene themselves, because with 10 planets or so it's too much work, and sometimes calculations little bit more complex.

Because of this, I decided to add an option that would make it possible for one to scale whole scene automatically.

My question is rather simple:
If I want to scale world/scene, which matrix should I use? Projection matrix, view matrix, or a completely new matrix (please, not this one, I'm running out of uniforms)?

Thank you.


texts: How to detect and prevent abuse (botting) of online game API?

texts:
I have been ocassionally working on a game idea in my free time. The gameplay and content renders it to be implemented as a online multiplayer game built with well established web technologies. You should know that it falls into the strategy and simulation genre. That means: No running around with characters or similar but only atomic actions (regarding client-server communication) like "build thing A on location X".

At one point I realized there is a huge problem: having a browser based front end relying on a REST API back end makes it a more than excellent target for bots. While automation is desireable for business it is poison to a game which is about fun. I experienced it first hand in a browser game in the past were the most successful players were bots which subdued everybody.

From my current point of view I do not see any possibility to protect against bots when building a multiplayer online game based on  a REST API. Exception: Making it open source so everybody can host his own instance for private groups or even just oneself (to not get annoyed by jerks with bots).

Is there any way to differenciate between an honest player who just set an alarm for the next possible action and a bot automatically taking every chance on appearance of it? Besides such show stoppers like captchas. If not, I would think about another technology stack which makes it at least much harder to mess with client-server communication (proprietary encrypted binary protocol in a native code client).

Edit: Thank you, your answers are inspiring but also made me realize that specific countermeasures cannot be made by going further into details of the game. However, that would be too much for a question on Stack Exchange. So I just want to point out the most important points:

Players are exploring, developing and managing whenever they want to. Their businesses still run fine when they are offline (it is a peaceful game, no weapons involved). Only expansion and progress need the players action. Those actions are limited by:
time is one of the key resources (like in EVE Online skill training). All processes in game require it. There is no point in being online 24/7. The average player should be successful already with spending not more than an hour every day in one or two sessions (roughly, the concept is still in development).


texts: Can I run my own loading script during the Unity splash screen?

texts:
Can I load data in the background while the Unity splash screen is up?  If so, how?

I am trying to run code during the splash screen, not just load assets.

I have not been able to find any information on this in Google or the Unity Documentation.


texts:
I'm trying to add some text to my Canvas but it seems to disappear in front of it? So does particle systems and other things?

It is a child object of the canvas.


texts: What is the proper term for "permanent world"?

texts:
How to name the fact that for a MMO game there's one big session, the same things are happening for all the players, you log out and after two days log in to the same place as the same person ?

I'd like to mention that not all MMO games are constructed this way, for example majority of MMOFPS games are based on lobby/separated severs system, so prefix "MMO" isn't necessarily equal to "onesessionism".

I myself can't think of any better expression than "permanent world".


texts: Designing for multiple screen resolutions and aspect ratios, target one resolution then scale to meet others or use normalized values?

texts:
I feel like what I'm currently doing is stupid but would just like reaffirmation it is. Basically I'm writing games which target a certain screen resolution (800x480), so all positions, widths and heights I set for sprites is for that resolution.

On the engine side I have special scalers which will change the width and height of what is being drawn to meet the current platforms res, so for example if the platforms screen res is 1200x720 I will stretch a sprite by a factor of:

1280 / 800.0f;
720 / 480.0f;

Positions are also offset and manipulated in a similar way.

I really feel I should move to a normalized system for widths and positions (i.e. 0 to 1) but at the same time feel this is more intuitive since the first platform I target is 800x480 and I already kind of have a good udnerstanding of dimensions and such for that.

So my question is, is it really that bad to target a specific ccreen res then in the engine side modify this res to meet different platforms?


texts: What is the difference between getWidth and getBackBufferWidth in LibGDX?

texts:
In regards to gdx.graphics, what is the difference between using getWidth and getHeight, and using getBackBufferWidth and getBackBufferHeight?

I am learning LibGDX and Java. I programmed formerly in pygame.
To my knowledge, getBackBuffer means the width and height of the actual window. Is that true?


texts:
I'm currently creating a game which should be multiplayer (client-server-client), but I'm stuck.

I have been doing crazy things like building a text chain like

string networkMessage = userHash+" "+userX+" "+userY+" "+userRotation;

but it looks crazy and parsing is also bad

string[] pieces = networkMessage.Split(' ');
string userHash = pieces[0];
int userX = pieces[1];
int userY = pieces[2];
float userRotation = pieces[3];

So, what is the best way to pack my network commands & parse them on the second side?

Yeah, ehm.. I'm using TCP & StreamReader/StreamWriter

PS: yes, I know that giving client a possibility to set their coordinates is cheating risk and I'll change it later, so server will be more authorative


texts:
I'm trying to create a falling word game like z-type (code here). Once the game starts a few words are displayed on the screen. When the user types a letter and if that matches with the first letter of any of the words displayed, an "activeWord" tag is added to the word. I have also created a laser script that checks if the tag is active and when that happens, it shoots the laser. What's happening right now is that the laser is shot only once i.e when the first letter matches but doesn't shoot a laser when the remaining words are typed. Can someone please have a look at the code and tell me where I'm making a mistake.

this is the word display script where the active word is assigned:

public void RemoveLetter() // remove the first letter if its correct and so on for the remaining letters. change the color of the word to red and add the "activeddWord" tag.
 {
 text.text = text.text.Remove(0, 1);
 text.color = Color.red;
 text.gameObject.tag = "activeWord";
 }

public void RemoveWord()
{
    Destroy(gameObject); // removes the word from display
}

here is the input manager script:

public class WordInput : MonoBehaviour {

public WordManager wordManager;

void Update () {
    foreach (char letter in Input.inputString)
    {
        wordManager.TypeLetter(letter);
    }
}

EDIT

This is the player script where the laser is instantiated:

public class Player : MonoBehaviour {
public GameObject laserPrefab;
void Start () {
    transform.position = new Vector3(0.0f, -3.92f, 0); // player position
}

void Update () {
      Instantiate(laserPrefab, transform.position, Quaternion.identity);
        }
}

This is the updated laser script:

public class Laser : MonoBehaviour
{
public float speed = 10.0f;

private Vector3 laserTarget;

private void Start()
{

}

GameObject activeWord = GameObject.FindGameObjectWithTag("activeWord");

if (activeWord != null && activeWord.GetComponent<Text>().text.Length > 0){

  laserTarget = activeWord.transform.position; // find position of word
  transform.Translate(laserTarget * speed * Time.deltaTime);

  for (int i = 0; i < Input.inputString.Length; i++){

   Debug.Log("Character from input string: " + Input.inputString[i] + "\n" +
   "Character from word displayed: " + activeWord.GetComponent<Text>().text[0]);

   if (Input.inputString[i] == activeWord.GetComponent<Text>().text[0]){

     laserTarget = activeWord.transform.position; // find position of word
     transform.Translate(laserTarget * speed * Time.deltaTime); // shoot the laser
  }
 }
}

After I do this, there are two major errors that I get:

As soon as I hit play, the laser fires continuously without stopping.
The laser still shoots only once after the word is typed...This is the message I get in the console (screenshot attached). There is a difference of one word between the input string and whats displayed on the screen...Can someone please tell me how to rectify these.....


texts: Including Microsoft.XNA.Framework.Input.Touch in a project?

texts:
So after running through tutorials by both Microsoft and www.xnadevelopment.com I feel very confident in my ability to get to work on my first game using the XNA Framework. I've manipulated sprites, added audio, changed game states, and even went a step further to apply the knowledge I had and figure out how to make animations and basic 2-dimensional physics (including impulses, force, acceleration, and speed calculations)

But then shortly into the project I hit a curious bump that I've been unable to figure out.

In wanting to implement menus, pause screens, and several different aspects of play (a "pre-level" prep screen, the level itself, and a screen after the level to review how well you did) I took a look at Microsoft's Game State Management sample. I understood the concept, although it was admittedly quite a lot to take in. Not wanting to recreate the entire concept by scratch (after all- what purpose would that serve?) I tried copying and pasting the sample code into my own ScreenManager class (as well as InputState and GameScreen classes) to try and borrow their ingenuity. When I did this, however, my project stopped compiling. I was getting the following error:

  The type or namespace name 'Touch' does not exist in the namespace 'Microsoft.Xna.Framework.Input' (are you missing an assembly reference?)

Having read through their sample code already, I realized that this namespace and every function and class within it could be safely ripped from the code without losing functionality. It's a namespace simply for integrating with touchscreen devices (presumably Windows Phone 7, but maybe also tablets).

But then I began to wonder- how come Microsoft's sample compiled but mine didn't? I copied their code exactly so there must be a setting somewhere that I need to change in Visual Studio in order to correct this. I tried creating a new project as a Windows Phone 7 game rather than a Windows game, however that only forced it to compile to a Windows Phone emulator and denied me the ability to change the resolution and other features which I clearly had the power to do in the sample code.

So my question is simple - how do I properly use the namespace Microsoft.XNA.Framework.Input.Touch?


texts: Loading texture from constructor doesn't work but does from function call

texts:
I am trying to load a SDL texture through my class's constructor. All I'm doing is calling a function from the constructor to load the texture. As mentioned in the title, this does not seem to work. However, if I call the function directly then it loads fine and I can see it on the screen. I'm fairly new to C++ so please let me know what I'm doing wrong.

Game.h

#include "Player.h"

class Game {
  private:
   Player player;

  public:
   Game();
   ~Game();

   void update();
   void draw();
}

Game.cpp

#include "Game.h"

Game::Game() {
  this->player = Player("somefile.png", 0, 0, 10, 10);  // Doesn't draw
  this->player.load("somefile.png", 0, 0, 10, 10) // Will draw
}

void Game::update() { /* ... */ }

void Game::draw() { /* ... */ }

Player.h

class Player {
  private:
    SDL_Texture* texture;
    SDL_Rect source, destination;

  public:
    Player();
    Player(const std::string& filepath, const int x, const int y, const int w, const int h);
    ~Player();

    void load(const std::string& filepath, const int x, const int y, const int w, const int h);

    void update();
    void draw();
  }

Player.cpp

#include "Player.h"

Player::Player() {}

Player::Player(const std::string& filepath, const int x, const int y, const int w, const int h) {
  this->load(filepath, x, y, w, h);
}

void Player::load(const std::string& filepath, const int x, const int y, const int w, const int h) {
  this->texture = SDL_CreateTextureFromSurface(renderer, IMG_Load(filepath.c_str());

  if (this->texture != nullptr) {
    this->source = { x, y, w, h};
    this->destination = { 0, 0, w, h};
  }
  else {
    std::cout << "Could not load image." << std::endl;
  }
}

void Player::update() { /* ... */ }

void Player::draw() { /* ... */ }

In Game.cpp, if I use the line with the constructor then nothing draws in the window. If I use the line that has load(), then it works fine. I never get the Could not load image. error in either cases.


texts:
I am trying to rotate game camera using my android device orientation.Like this  Using accelerometer input of device this may be done. But I don't know how to do this. I tried lot of methods, but failed. Anybody please help.

I am using unity 5.3 with C#.


texts:
when I switch between weapons by Number [1 2 3 4] the weapon don't switch between them but the variable " selected weapon value changed"
anyone help me, this my Code and screenshots!

    using UnityEngine;
    using UnityEngine.Networking;

    public class weaponSwitching : NetworkBehaviour
   {
      public int selectedWeapon = 0;

   void Start () {

      CmdSelectWeapon();
   }

   void Update () {
      if (!isLocalPlayer)
      {
         return;
      }
    if (Input.GetKeyDown(KeyCode.Alpha1))
    {
        selectedWeapon = 0;
    }
    if (Input.GetKeyDown(KeyCode.Alpha2) && transform.childCount >= 2)
    {
        selectedWeapon = 1;
    }
    if (Input.GetKeyDown(KeyCode.Alpha3) && transform.childCount >= 3)
    {
        selectedWeapon = 2;
    }
    if (Input.GetKeyDown(KeyCode.Alpha4) && transform.childCount >= 4)
    {
        selectedWeapon = 3;
    }
}

[Command]
void CmdSelectWeapon()
{
    int i = 0;
    foreach(Transform weapon in transform)
    {
        if(i == selectedWeapon)
        {
            weapon.gameObject.SetActive(true);
        }
        else
        {
            weapon.gameObject.SetActive(false);
        }
        i++;
        if (i == 4) // this my Gun Effect i don't need to deactivate
        {
            weapon.gameObject.SetActive(true);
        }
    }
 }
}

https://imgur.com/CTN5TNL "Weapons Holder"

https://imgur.com/6a0KZC0 "Weapons HolderInspector"


texts: Where do you put assets on iOS 5.1 apps?

texts:
I'm starting with iOS 5.1 and I'm trying to figure out how to download/and load asset files to the iPad, such as sprites and sounds.

Previously I think I packed them into a .xib file for iOS 3, (wasn't .xib for general user interfaces?) but I'm not sure if this practice is outdated with the new GLKit package.


texts: Which are the most futureproof languages for graphics (shader) programming?

texts:
I have written some GLSL and Cg shaders a couple years back. I am starting another graphics engine project and I want to choose my technologies carefully so that my code will be accessible years down the road.

It seems to me that GLSL and Cg and HLSL are just slightly different syntaxes. Are there any other alternatives to these shader languages? It used to be I only cared about my code compiling correctly on ATI and nVidia hardware (their drivers, to be accurate) but these days I'd like it to function well on Intel's integrated solutions as well. From what I know since all vendors support OpenGL, GLSL should work, and HLSL is its counterpart for DirectX, so there shouldn't be problems there either. What about Cg?

Another question I have is whether these languages are still relevant for using newer techniques. I think they are, but maybe what I don't know is that nobody uses Cg anymore because it's gone out of style, or whatever. When I get around to learning and implementing these techniques myself, I'll surely find out all about the ins and outs, but I'd like to get a feeling for which languages and toolkits are being used NOW by those who are on the cutting edge, so I don't end up building my framework on software that will become obsolete.


texts: I am making a game with WPF and C#, and I frequently am in need of artwork for it.  Some things could be easily shared, such as explosion animations, exhaust plumes, etc.  I was wondering if there are any good web sites for this?  All I can find are tutorials and the infrequent sample, but I imagine there is a site out there that I am missing.  I would also like to clarify that I am looking for pure vector based XAML snippets.  I know there are a lot of sites out there for sprites and textures, but I am looking for XAML components that I can tweak.


texts: How can I store a set of concrete components and implement "GetComponent()?"

texts:
I would like an abstract class, AbstractComponentAggregate, which has many AbstractComponents.  Users of my framework will create their components by extending AbstractComponent and appending the component to this AbstractComponentAggregate.

I would like to know if there is an elegant way to have AbstractComponentAggregate to store a dictionary of the concrete classes that extend AbstractComponents.  Note, that I want to store many concrete classes, each of which is an AbstractComponent.  This is different than storing a list of AbstractComponents.

Thus, you can invoke a method on AbstractComponentAggregate, such as:

AbstractComponentAggregate.GetComponent(), which returns type T.  T is the concrete class, and we ensure T is of type AbstractComponent.

Something similar to this is done in Unity3d, and I would like to emulate this.


texts: Direct3D - ways to retrieve world position from depth buffer without matrix information

texts:
For an existing game (VBS3) I'd like to write a plugin which exports all the rendered pixels with their world position (basically something like a LIDAR point cloud).

Actually I don't need the position of each pixel, instead I could also use the application's internal collision checking system with equally spaced ray endpoints, but it turned out that this approach is way too slow and coarse.

The game provides a callback which gets called whenever the back buffer has been filled. Then this callback provides references to a depth buffer and a render target, both of type IDirect3DSurface9.

As a first shot I just wanted to do it like Andon M. Coleman described in [1] but my problem is that the IDirect3DDevice9 linked to the surfaces only returns identity matrices when I call GetTransform() on it with types D3DTS_PROJECTION and D3DTS_VIEW.

Therefore I suppose the application does not use those matrices at all and instead does all the matrix / projection stuff internally. Am I right? Is this common? And are there other approaches I could take?

Thanks in advance!

[1] https://stackoverflow.com/questions/32227283/getting-world-position-from-depth-buffer-value


texts: Position/orient parent to place child at a particular position/orientation

texts:
I have a GameObject for which I know its world position and rotation.
From another app, I receive a new rotation and position, which should represent the local position and rotation of my GameObject.
How can I compute the position and rotation of the parent object knowing the (world) position, the (world) rotation, the localPosition and the localRotation of its child? How can I find the necessary transform to obtain the second pair of coordinates from the first pair of coordinates?


texts: How can I edit .qvm (Quake Virtual Machine) files?

texts:
I was browsing through how to mod a game (Urban Terror, a Quake 3 mod). I found that it can be done by editing .qvm files in the game. Under the file named zpak000.pk3. That file contains other files named

ui.qvm
qagame.qvm
cgame.qvm

But I can't find a way in which I can edit these files.


texts: Pathfinding to Get In Attack Range with "Transparent" Tiles

texts:
Currently I'm using A* and a raycasting algorithm to determine the path an entity (Player) should take to get close enough to the enemy (Enemy). The player has an attack range (it's illustrated around the enemy to show how close the player has to get to the enemy in order to attack it).

This works pretty well, but as soon as I add tiles that prevent entities from moving from them, but allows them to attack through them (imagine a river).

Using my current implementation the player entity takes the purple route to attack the entity, but I want it to take the yellow path.

I came up with the following, but this is highly inefficient:

Mark the tiles around the enemy (cyan circle), which are in line of sight to the enemy (raycasting) as possible destinations
Run the pathfinding algorithm to find which one of those destinations is the closest to the player

I know A* is good for finding a single destination and Dijkstra is better for multiple destinations, but since I already got this working with A* I wanted to know if it's possible to achieve this is an efficient manner.

Side question: how are the tiles where you cannot walk through, but can shoot through called in the industry? I know the wall likes entities are mostly called "solids".


texts: I have big creativity burnout :/ Do you have any ideas how can I fight with it ??