texts: Best way of approach? Mob moving around a section of tiles

texts:
Think the beginning stages of Metroid, where there would be a turtle-like mob that would move around a section of tiles, normally 1-3 in a line.

What would be the best approach to accomplish this sort of AI?

It seems so simple but its giving me headache.

The solution I've found have been to have a fixed distance for it to move, and changing directions once the distance has been met. This isn't that OOP though.

Another would be have a rectangle made of the section of tiles, and when the bounds of the mob no longer contains the line of rectangle, change directions. This is proving to be harder to implement and only works for rectangular sections, not for abstract "tetris" like sections of tiles.


texts: LUA - Keeping track of game state for a digital card trading game

texts:
I am building a card game.  Let's say it's similar to Magic the Gathering, Hearthstone, etc.

The problem I am trying to figure out is how to architect "auras" and how much damage each card takes.

Right now I have a deck and I store card data as follows.  I've made up names for the types of cards that will exist.

M.card = {}
-- Minion cards have health and damage
M.card[1].name = "Minion"
M.card[1].hp = 1
M.deck[1].dmg = 1

-- Super Minions have more health and damage
M.card[2].name = "Super Minion"
M.card[2].hp = 4
M.card[2].dmg = 4

-- Spell cards have no health and damage. Instead they affect the health and damage of other cards.
M.card[3].name = "Heal"
M.card[3].details = "This card heals any character for +2 health"
M.card[3].healthboost = 2

M.card[4].name = "Damage Boost"
M.card[4].details = "This card gives + 1 damage to any other card for 1 turn"
M.card[4].dmgboost = 1

-- Super damage boost gives more damage boost to other cards
M.card[5].name = "Super Damage Boost"
M.card[5].details = "This card gives +3 damage to any other card permanently"
M.card[5].dmgboost = 3

So when one card attacks another card, I need to keep track of the damage taken by both cards. I don't want to change the base stats of each card so I need to keep track of adjustments.

I could do something like this

-- Super Minion takes 3 damage
M.card[2].newHp = 1
-- or
M.card[2].adjHp = -3
-- Not sure which is better.

During the battle I need to keep track of which auras are played.   So for example if the Damage boost card is played.  I need to give another card +1 damage for just one turn.

Let's say that I am keep track of each turn number starting from 1.

Should I do something like this
    M.aura[1] = 4   -- ( aura 1 is card # 4)
    M.aura[1].target = 2   -- (this aura is applied to card 2)
    M.aura[1].expires = 5  -- (this aura expires on turn 5)

M.aura[2] = 3    ( second active aura is heal, card #3 )
M.aura[2].target = 2
M.aura[2].expires = 0   -- this is a one time aura.  So I need to apply it to card #2 and then immediately expire it so it never activates again.

Then on every new turn I loop through all the auras and make sure they are still active before a fight begins?

Just wondering architecturally what is the best way to keep track of Damage that characters have taken and spells that are active that are giving characters special abilities.


texts: Movement looks funny If player takes up multiple tiles in tile-based game


texts: I'm using the XInput API to support gamepads. As XInput is not event-driven, but requires polling, my question is, what is the recommended polling rate (ms) for gamepads or specific, the XBOX 360 controller?


texts: How much assembly is really used in modern game code?

texts:
On average, how often is assembly used in modern game code?

Specifically on platforms that already have good C++ compilers, like x86, PPC, or ARM--because I assume games on embedded systems make extensive use of assembly.


texts: Creating a curved mesh on inside of sphere based on texture image coordinates

texts:
In Blender, I have created a sphere with a panoramic texture on the inside.  I have also manually created a plane mesh (curved to match the size of the sphere) that sits on the inside wall where I can draw a different texture.

This is great, but I really want to reduce the manual labor, and do some of this work in a script -- like having a variable for the panoramic image, and coordinates of the area in the photograph that I want to replace with a new mesh.

The hardest part of doing this is going to be creating a curved mesh in code that can sit on the inside wall of a sphere.

Can anyone point me in the right direction?


texts: Side scroll game with 8000xScreen_Height, which technique is best

texts:
I got one new requirement for iOS side scroll game with screen size : 8000xScreen_Height

For this, tileMap is best or normal texture based is best? I need to use parallax background too.

Help me to find right technique.

Thanks in advance.


texts: Receiving keyboard events on a canvas in Javascript

texts:
I need to receive keyboard events in a canvas element. Click events are received but key presses aren't.

Here is my code which doesn't handle key events:

var canvasElm = $('canvas');
Event.observe('canvas', 'keypress', function(e) {
    console.log('Key event is received!!');
    console.log(e);
});

How can I make it handle those key events?


texts: How to render tile maps in modern opengl?

texts: I'm trying to use SDL2 and Modern OpenGL to make a 2D rpg. The problem is, I have no idea how to render a tile map. I'm using the Tiled map editor to create maps. I have a vague idea of how to parse the maps using this (https://github.com/andrewrk/tmxparser) tmx parser.  I try to parse the maps using said parser, but then I run into the problem of how to actually get the tile maps to appear on screen, when using a spritebatch class. How would I go about rendering these maps using modern OpenGL?


texts: How to create transfer function for temperature in 2D space

texts: I am looking for ways that can transfer temperature from tiles to tiles in space such as in Rim World, when you click on a tile, it will display the temperature on that particular tile and you can regulate the temperature in a confine space by installing air conditioner. Wonder is there any method in unity that can perform such function? Would like to learn it by myself. I am new to programming so not even sure where should I start my search.


texts: Animations in Unity are not working properly

texts:
I've done a few animations in Blender for my 3D character but the problem is, that they look different in Unity. It seems like the eyes are moving too much. I tried to change many things in import like rig etc. but nothing helped at all. Here are screenshots:

Wrong animation

Good animation


texts: Set sprite for UI2DSprite from NGUI at runtime

texts:
How can I set sprite for UI2DSprite from NGUI at runtime?

This is what I tried:

gameObject.GetComponent<UI2DSprite>().sprite2D = Resources.Load<Sprite>("Assets/Content/UI/level/notLife.png");

I tried not to write .png in the end but it did not help as well.

Here is my Project view so that to prove you that I am using the right path:

And the problem here is that instead of showing me the newly placed sprite my old one disappears and nothing else happens.

So, how can I change sprite in UI2DSprite in NGUI from script?


texts:
I just created a simple MMO in unity3d, then me and my friends test it via LAN and the result is very smooth. But when I hosted it in public (100ms ping) the server became unresponsive and causes random disconnection.

Host Setup
- 1gbps
- 32gb ram
- 256 ssd
- off firewall

Server Setup
- max of 100 players
- every 100ms update
- no other updates, just only X and Y location of player by index
- c# sockets w/ async

Server Flow
- when 100ms tick reaches, server sends position of player base on index in a loop.

ex.

if (gtick >= 0.1f) {
    for (x < maxPlayers; x++) {

        // check ifs
        //couples of ifs here...

        // send
        sendToWorld(x ... player[x].posX ... player[x].posY);
    }

    // somewhere, gtick = 0, then counts up again...

}

then the result is delay, unresponsive, and random disconnection.
maybe it flooding itself, I don't know. but when we test it locally (10+ players), it is very smooth and no problem at all.

My question is, How can I update all players every 0.1 without server flooding itself?


texts:
Summary: What approach should I take to allow custom inputs saved in a file be interpreted in the engine?
So I am making a game engine similar to Mugen where I want characters to have their own special combo inputs. Similar to how Kage has the Shun Goku Satsu. Where its just a combination of multiple keys pressed in quick succession. The thing is I want to give the ability to create these combinations to the character creators and let the engine handle the rest.
I already parsed the list of moves from the character file, so now I got an in-memory list of valid input sequences for each character and what moves they trigger. But I don't really know how to interpret a valid sequence.


texts:
I need to simulate the effects of adding supporting materials to a building structure for a genetic algorithm in a block-based world. Essentially I am planning to use a genetic algorithm to optimise the viability of a structure for a game in Java.

I've tried looking around for examples of algorithms, but so far have only come up with JBullet. How would the stress be calculated from a list of materials and their properties?


texts: Disable/Remove Warning about a not bound Render Target View

texts:
So to render into my shadow map depthstencil buffer i only bind a DepthStencilView to the Output Merger. Like this

    m_pContext->OMSetRenderTargets(0,0, m_pShadowMapDV);
    m_pContext->ClearDepthStencilView(m_pShadowMapDV, D3D11_CLEAR_DEPTH, 1.0f, 0);

Now this works fine and my shadow-map also produces the desired result. What bothers me though is the constant warnings in the debug-window. Is there a way or trick to disable that warning?

D3D11 WARNING: ID3D11DeviceContext::DrawIndexed: The Pixel Shader expects a Render Target View bound to slot 0, but none is bound. This is OK, as writes of an unbound Render Target View are discarded. It is also possible the developer knows the data will not be used anyway. This is only a problem if the developer actually intended to bind a Render Target View here. [ EXECUTION WARNING #3146081: DEVICE_DRAW_RENDERTARGETVIEW_NOT_SET]

This might be a pretty dumb question, but after googling a lot i still came up empty. Only i a lot of people who are not doing this on purpose.

EDIT: Maybe the question can be asked in another way:

Is there a way to define an empty PixelShader? If i define the return value as void it notifies me, that i have to at least return the 4 pixel colors. If i don't give it any Semantics it does not work either.


texts:
I'm having a strange behavior simulating water waves. It works perfectly with directional waves, but point waves don't work like expected. If i do not normalize the directional vector(WoldPosition - waveCenter), it works like this:

Which would be nice if i would want to display 10 point waves, but i just added one point wave(the center one). And if i do normalize the directional vector, it looks like this:

Which is not even close of what a point wave should look like.

Do you have any idea of what could be the problem?

This is the formula used to calculate the heights of the waves:

amplitude * sin(dot(direction,vec2(x,z))*w + deltaTime*phase);

Vertex shader:

#version 330

layout (location = 0) in vec3 Position;
layout (location = 1) in vec2 TexCoord;
layout (location = 2) in vec3 Normal;

uniform mat4 gWVP;
uniform mat4 gWorld;
uniform float gMatSpecularIntensity;
uniform float gSpecularPower;
uniform vec3 eyePoint;
uniform float deltaTime;

out vec2 TexCoord0;
out vec3 Normal0;
out vec3 WorldPos0;
out vec2 Specular0;
out vec4 wvp;
out float relativeFactor;

const float w = 1.2f;
const float amplitude = 0.1f;
const float phase = 2.2f;

vec3  wavePosition = vec3(20,0,20);

float CalculateHeight(float x, float z, vec2 direction)
{
    return amplitude * sin(dot(direction,vec2(x,z))*w + deltaTime*phase);
}

vec3 CalculeNormal(float x, float z, vec2 direction)
{
    float heightR = CalculateHeight(x-1,z,direction);
    float heightL = CalculateHeight(x+1,z,direction);
    float heightU = CalculateHeight(x,z+1,direction);
    float heightD = CalculateHeight(x,z-1,direction);
    return normalize(vec3((heightR - heightL),1, (heightU - heightD)));
}

void main()
{
    wvp            = gWVP * vec4(Position, 1.0);
    gl_Position    = wvp;
    TexCoord0      = TexCoord;
    WorldPos0      = (gWorld * vec4(Position, 1.0)).xyz;

    vec2 direction = (wavePosition-WorldPos0).xz;

    gl_Position.y  += CalculateHeight(WorldPos0.x,WorldPos0.z,direction);
    Specular0      = vec2(gSpecularPower,gMatSpecularIntensity);
    relativeFactor = dot(normalize(eyePoint - WorldPos0),vec3(0,1,0));

    Normal0        = CalculeNormal(WorldPos0.x,WorldPos0.z,direction);
    relativeFactor = clamp(relativeFactor, 0.0, 1.0);
}

Variables:

direction: Vector which defines the direction of the wave. It is
perpendicular to the wave front.
x: Position x in world coordinates.
z: Position z in world coordinates.
amplitude: The amplitude of the wave
phase: The phase of the wave
deltaTime: The total time passed in ms.
gWVP: Camera perspective matrix * Camera view matrix * Water transformation matrix (position matrix * rotation matrix(no rotation) * scale matrix)
gWorld: Water transformation matrix (position matrix * rotation matrix(no rotation) * scale matrix)

The fragment shader and the other variables do not influence in the displayed wave, it just combine the reflextion + refraction image + apply the fresnel efect.

For more info about the wave function: http://http.developer.nvidia.com/GPUGems/gpugems_ch01.html


texts: Integrating the Steamworks API achievements into your game

texts: I'm coding a game in Visual Studio 2015 and am wondering how to go about adding steam achievements to it using the Steamworks API, do I need to have my game on steam before hand or if not what's the process of adding achievements?


texts:
I have a object at the center. Other set of objects rotating around center in first orbit. Now i want other objects to rotate around the objects in 1st orbit.

In the above fig, set of triangles are rotating around the square and circles are rotating around the triangle.
I have the code which works for 1st orbit, but i am  not able to render that second orbit.

I am calling display in loop. i is static global variable.
which transformations will do the second orbit?


texts:
I am trying to make a simple weapon change in Unity3D. The best way to do this is with the mouse scroll wheel, as far as I can see.

I googled on how to do this and found that I have to use Input.GetAxis("Mouse ScrollWheel"); I use this piece of code and print it. Still, I always get an value of 0.
any ideas? I just need to solve how to get the value first, I'll figure out the rest myself.

Code idea:

function Update () {
    print(WeaponNumber);

    if(Input.GetAxis("Mouse ScrollWheel")){
    WeaponNumber += Input.GetAxis("Mouse ScrollWheel");
    }
}


texts: Am I allowed to use a real life celebrity in a game?

texts: In previous questions many users asked whether or not an athlete can be used in a game. Yet the answer was no due to multiple copyright their images and names had. However anyone can use a politician's name and physical appearance due to the fact that they are "public figures" (example: Obama). In this case, I want to use famous game developers such as Kojima and Gabe Newell in a game. Am I allowed to use them? or should I make references to them using distinct names (I.E. Lord Gaben). How can I find out whether or not a person is a "public figure" and if their appearance/name is protected?.


texts:
Suppose I have a GameObject, and I want it's transform.forward to be facing up. Is it possible to change it as seen below?

public class Main : MonoBehaviour
{
    void Start ()
    {
        Vector3 forward = transform.forward;
        forward = new Vector3 (0, 1, 0);
        transform.forward = forward;
    }
}


texts: Is it possible to draw a model partially (along the X, Y or Z axis) to make an extending barrier or something like that? (Scaling doesn't work because of the textures)


texts: Box2D Platform body not moving player body along with it

texts:
I am creating a game using Box2D (Javascript implementation) - and I added the ability to have a static platform, that is moved along an axis as a function of a sine.

My problem is when the player lands on the platform, as the platform moves along the X axis - the player is not moved along with it, as you visually would expect.

The player can land on the object, and if it hits the side of the object, it does colide with it and is pushed.

This image might explain better than I did:
After jumping on to the red platform the player character will fall off as the platform moves to the right

UPDATE:
Here is a live demo showing the problem:
http://onedayitwillmake.com/ChuClone/slideexample.php


texts: How to access the currently touched instance of the Prefab?

texts:
I have a prefab which is instantiated in the Scene and what I am trying to do is to disable with a touch or timeCounter but sometimes it disables all the instances of the prefab and sometimes 2 or 3 of them.

I want to disable particular object which I have touched currently.

when i am passing the collider in Destroy(hit.collider) it works perfect but how to handle it null is passed as parameter.

Here is my code:

 void Update () {
     blastingTimeCounter -= Time.deltaTime;

     if (blastingTimeCounter <= 0) {
         DestroySquare (null);
     }

     for (int i = 0; i < Input.touchCount; i++) {
         if (Input.GetTouch (i).phase == TouchPhase.Stationary) {
             hit = Physics2D.Raycast (Camera.main.ScreenToWorldPoint (
                 Input.GetTouch (i).position),
                 Vector2.zero);
             if (hit.collider != null) {
                         DestroySquare (hit.collider);
             }
         }
     }
  }

  void DestroySquare(Collider2D collider){

     if(collider == null)
     {

     }
     else{
     collider.gameObject.SetActive (false);
     blastingTimeCounter = blastingTime;
     }
   }


texts:
Say I have my main "screen" plane, where vectors can be represented

I "know"/can represent vector Q, but the only information I know about vector R is relative to Vector Q. An easy way to visualize this is to have another plane at o2-- I can represent vector R in this plane (e.g. in cartesian coordinate form, or polar form), but how do I "globalize" to the original plane, or represent vector P?

Thank you


texts:
I just developed a facebook game(mifia like), but the graphics I made are not good, because it is reference with some existing photo, trace with AI, and coloring it.

Therefore, I invited my friend to join me, he is a graphic designer, owns a company with his friend (I know both of them), for the shares, I expect at least 70% for me, and at most 30% for them (both of them want to join).

Therefore, they give me a counter offer, 60% for me and 40% for them, of course, I feel their counter offer is unacceptable because they only build the image in part time, and all the other work just like coding, webhosting...etc, is what I do in full time. Why they said they worth 40% is that they will make a good graphic, they can provide a advertise channel(on local magazine), etc... Actually, I don't think the game need advertisement on local magazine because the game is not target for local...

Please give me some comments on this issue (is the share fair? what is the importance of the image of the game, is it worth more than 30%), or can anyone share the experience on this.


texts: Correcting projection of 360° content onto a sphere - distortion at the poles

texts:
I'm using the Autopano Giga 4.4 and Autopano Video Pro 2.6 to stitch and create spherical content, but I've recently moved into wanting to create 360° tours via Unity. I know this is partly a developers question, but if anyone out there can help me with the right specs for exporting a spherical image or video from Giga to use to create the image for the inside of the sphere on Unity, I'd appreciate it!

Experimenting with Premiere and FCPX to edit highlight reels of spherical content, I've had seamless experiences created. For some reason in Unity, the images appear to be stretched around the sphere wrong and it's creates issues on the top and bottom of the image:

The image shown is the bottom of the sphere. I'm using the Android platform to hopefully turn these tours into apps when completed. Thank you for any help!


texts: Should Animations in Turn-Based Games Happen Before or After State Transitions?

texts:
I'm planning a roguelike game and I'm unsure how to design for animations. Since a roguelike is turn-based, the game model is discrete and would have no intermediate states during an animation(?). I've come up with two possible approaches:

Perform state transitions immediately upon input and compute the animations that occurred. In the case of a moving character, draw the animation as a member of the destination tile (instead of the static sprite) and coming from the origin tile.
Compute animations before transitioning and transition the state asynchronously after the animation completes. Draw moving objects as members of their origin tile so that they arrive immediately before the state transition.

Do developers of this type of game tend to prefer approach 1 or 2 (or some third option) and why?


texts:
I have a top-down 2D shooter. I have an image of a player holding a gun, that rotates to face the mouse. Please note that the gun isn't a separate image tethered to the player, but rather part of the player. Right now, bullets are created at the player's x and y. This works when the player is facing the right way, but not when they rotate. The bullets move in the right direction, but don't come from the gun. How can I fix this?

TL;DR: When the player rotates, bullets don't come from gun.

public void fire() {
    angle = sprite.getRotation();
    System.out.println(angle);
    x = sprite.getX();
    y = sprite.getY();

    Bullet b = new Bullet(x, y, angle);
    Utils.world.addBullet(b);
}


texts: How to correctly specify the offset in a call to glVertexAttribPointer()?

texts:
I'm trying to draw a simple triangle using the following vertices:

std::vector<VertexFormat> vertices;
vertices.push_back(VertexFormat(glm::vec3(0.25, -0.25, 0.0),
    glm::vec4(1, 0, 0, 1)));
vertices.push_back(VertexFormat(glm::vec3(-0.25, -0.25, 0.0),
    glm::vec4(0, 1, 0, 1)));
vertices.push_back(VertexFormat(glm::vec3(0.25, 0.25, 0.0),
    glm::vec4(0, 0, 1, 1)));

The corresponding Vertex format is given by the following struct:

struct VertexFormat
{
    glm::vec3 position;
    glm::vec4 color;

    VertexFormat(const glm::vec3 &iPos, const glm::vec4 &iColor)
    {
        position = iPos;
        color = iColor;
    }
};

The first call to glVertexAttribPointer() is easy since the position vector appears first in the struct, the call is as follows:

glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(VertexFormat), (void*)0)

The second call to glVertexAttribPointer() should be made specifying a suitable offset for the color attribute of a vertex. Since the color vector appears after the position, then such offset should be given by sizeof(glm::vec3). The corresponding call is:

glVertexAttribPointer(1, 4, GL_FLOAT, GL_FALSE, sizeof(VertexFormat), (void*)(sizeof(glm::vec3)))

The output of the program using these parameters is:

This output is wrong. There are only two colors (green and blue) and the colors are in the wrong position, note that the bottom-left vertex is blue, but according to the code the vertex should be green.

If the offset is changed to sizeof(glm::vec4) the call is:

glVertexAttribPointer(1, 4, GL_FLOAT, GL_FALSE, sizeof(VertexFormat), (void*)(sizeof(glm::vec4)));

And the triangle is rendered correctly

So, Is my understanding of the offset parameter wrong? Why using an offset with the size of a vec4 gives the right output?

Any help would be appreciated.

P.S. Sorry for the bad english.

Edit: After reading the answer of Fibbles, and the comments of Fuzz Logic, I checked the size of the VertexFormat struct. A sizeof() gives a size of 32 bytes for a 32 bit executable. So padding is indeed the problem here. Using the macro suggested by Fibbles solves the problem. Thanks for everything guys!


texts: How can I support the clamping of quaternion-based rotations?

texts:
Currently I have an orbiting camera that fixates on a single point. In the node-based structure, _cameraNode is a child of _cameraTargetNode. I am able to orbit around the target node via the following code snippet:

Urho3D::Quaternion rotY = Urho3D::Quaternion(1.f, Urho3D::Vector3(dy, 0.f, 0.f));
Urho3D::Quaternion rotX = Urho3D::Quaternion(1.f, Urho3D::Vector3(0.f, dx, 0.f));

Urho3D::Vector3 curPos = _cameraNode->GetTransform().Inverse().Translation();

_cameraNode->RotateAround(curPos, rotY, Urho3D::TS_LOCAL);
_cameraNode->RotateAround(Urho3D::Vector3::ZERO, rotX, Urho3D::TS_PARENT);

cameraNode->LookAt(Urho3D::Vector3::ZERO, Urho3D::Vector3::UP, Urho3D::TS_PARENT);

Now what I want to do is clamp this movement. I want to be able to orbit within a set area between the two following values:

const Urho3D::Vector3 rotClampMin = Urho3D::Vector3(0.f, -45.f, 0.f);
const Urho3D::Vector3 rotClampMax = Urho3D::Vector3(90.f, 45.f, 0.f);

RotateAround sets both the angle and position of _cameraNode, so I must pre-compute the values with the clamping in mind. I would like to avoid working with Euler angles as much as possible. How can I clamp my rotation prior to calling _cameraNode->RotateAround?


texts:
How to create good timer for HTML5 Canvas games?
I am using RequestAnimationFrame( http://paulirish.com/2011/requestanimationframe-for-smart-animating/ )

But object's move too fast.

Something like my code is:

http://pastebin.com/bSHCTMmq

But if I press UP_ARROW player don't move one pixel, but move 5, 8, or 10 or more or less pixels. How to do if I press UP_ARROW player move 1 pixel?

Thanks for help.


texts: Differences between object movement functions

texts:
So I was trying to understand the differences between different ways to move an object in Unity and got opposite answers in different places. Here is what I was able to figure out though. I would ask you to check and correct me if I am wrong at any of them:

transform.Translate has nothing to do with the physics. It simply teleports the object from point A to point B.
MovePosition for kinematic bodies slides (instead of teleporting) the object from point A to B + interpolates the object position in the frames to be rendered in-between FixedUpdate calls.
MovePosition for non-kinematic bodies ( aka dynamic ) teleports them from point A to point B.


texts: How to store "chunks" of tiles or How to make my implementation work

texts:
I asked a previous question about the loading and unload of chunk data and people noted that my way of storing chunks is weird and I was wondering how I would go about doing it properly. @Byte56 suggested using a linked list or adjacency list but i have no clue how to do those even after searching google/stackoverflow. Any advice to a person new to xna programming?

Source

Previous Question


texts: IndexOutOfRangeException: Array index is out of range even though the inspector clues otherwise

texts:
I am currently making a randomized infinite platform with GameObject already made platforms in 3 arrays. In the inspector everything is obviously running quite smoothly but I keep weirdly keep getting uncalled for errors like: IndexOutOfRangeException: Array index is out of range.

Here is my code:

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

public class BackFloorSetter : MonoBehaviour {

    public GameObject[] gameBackFloorsOne;
    public GameObject[] gameBackFloorsTwo;
    public GameObject[] gameBackFloorsFinal;

    public Vector3 nextPosition;

    public float unroundedFinalOrTwo;
    public int finalOrTwo;

    public float unroundedTwoFloor;
    public int twoFloor;

    public float unroundedFinalFloor;
    public int finalFloor;

    public GameObject currentSpawnFloor;

    public float floorSpawnCounter;

    public int counterGoal = 5;

    void Start()
    {
        nextPosition = new Vector3(0, 0, 0);
        Instantiate(gameBackFloorsOne[0], nextPosition, Quaternion.identity);
    }

    void Update()
    {
        floorSpawnCounter += 1 * Time.deltaTime;

        if(floorSpawnCounter == counterGoal)
        {
            floorSpawner();
            counterGoal += 5;
        }

        unroundedFinalOrTwo = Random.Range(0.6f, 2.4f);
        finalOrTwo = Mathf.RoundToInt(unroundedFinalOrTwo);

        unroundedTwoFloor = Random.Range(-0.6f, 3.4f);
        twoFloor = Mathf.RoundToInt(unroundedTwoFloor);

        unroundedFinalFloor = Random.Range(-0.6f, 4.4f);
        finalFloor = Mathf.RoundToInt(unroundedFinalFloor);

        if (finalOrTwo == 1)
        {
            currentSpawnFloor = gameBackFloorsTwo[twoFloor];
        }
        if (finalOrTwo == 2)
        {
            currentSpawnFloor = gameBackFloorsFinal[finalFloor];
        }
    }

    public void floorSpawner()
    {
        nextPosition.x -= 232;
        Instantiate(currentSpawnFloor, nextPosition, Quaternion.identity);
    }

    public void flatGroundSpawner()
    {
        nextPosition.x -= 232;
        Instantiate(gameBackFloorsOne[0], nextPosition, Quaternion.identity);
    }

}


texts: What should I keep in mind when making 2D games for multiple resolutions?

texts:
I'm making a 2D (Android) game. Android devices vary quite a lot in screen resolution; what do I need to keep in mind when making my game?

Do I need to keep big versions of all images and scale down depending on the resolution (doesn't that waste space)?
Do bitmap fonts scale well or do I need to use something else?
Anything else I'm forgetting?


texts: Is it better to import photoshop files or illustrator files into flash?

texts:
I was wondering what would be better to import into flash for when I animate.
My intention is to animate my characters and objects and then export as a png sequence and make a sprite sheet then take into cocos2d.

Illustrator like flash is vector based but I will have to turn it into pixels anyway to play on a screen.

So I was just wondering what would be better or easier or does it not matter either way?

Additional information:
I have all the adobe software above at CS5.
I am slightly more comfortable working in Illustrator.
My intention was to make the graphics in illustrator so that I could easily resize my graphics for multiple devices, sometimes I may have to rasterize my illustrator file and add final touches in photoshop.

As I'm sure you can tell i'm pretty new to flash and iphone development so any help or advice would be greatly appreciated, sorry for all the questions.


texts: Single pass box blur is not giving same result as double pass box blur

texts:
I've been using 2-pass box blur written in GLSL in Blender without problem.

Blur horizontally:

uniform sampler2D bgl_RenderedTexture;
void main()  {
    float blur = 0.3;

    float resolution = blur * 0.1;
    int n = 10;
    int i = -n;
    int totalWeight = 0;

    vec2 st = gl_TexCoord[0].st;

    vec4 outColor = vec4(0.0);
    for(; i < n; ++i) {
        vec2 uv = st + vec2(float(i) / 2.0 / float(n) * resolution, 0);
        outColor += texture2D(bgl_RenderedTexture, uv);
        totalWeight += 1;
    }
    gl_FragColor = outColor / float(totalWeight);
}

Blur vertically:

uniform sampler2D bgl_RenderedTexture;
void main()  {
    float blur = 0.3;

    float resolution = blur * 0.1;
    int n = 10;
    int j = -n;
    int totalWeight = 0;

    vec2 st = gl_TexCoord[0].st;

    vec4 outColor = vec4(0.0);
    for(; j < n; ++j) {
        vec2 uv = st + vec2(0, float(j) / 2.0 / float(n) * resolution);
        outColor += texture2D(bgl_RenderedTexture, uv);
        totalWeight += 1;
    }
    gl_FragColor = outColor / float(totalWeight);
}

The output is as desired:

But when I try to do it with single pass, it's only blurring in the direction of the inner loop.

uniform sampler2D bgl_RenderedTexture;
void main()  {
    float blur = 0.3;

    float resolution = blur * 0.01;
    int n = 10;
    int i = -n;
    int j = -n;
    int totalWeight = 0;

    vec2 st = gl_TexCoord[0].st;

    vec4 outColor = vec4(0.0);
    for(; i <= n; ++i) {
        for(; j <= n; ++j) {
            vec2 uv = st + vec2(float(i), float(j))
              * resolution / float(n) / 2.0;
            outColor += texture2D(bgl_RenderedTexture, uv);
            totalWeight += 1;
        }
    }
    gl_FragColor = outColor/ float(totalWeight);
}

I must be missing something really simple but it's not visible to me. Can anyone help me?


texts: Resetting a level in unity when exiting to main menu

texts:
I have a pause screen in my game having two buttons : resume game and exit to main menu
The main menu have only 1 button wish is play,
when i click on exit to main menu the main menu level is loaded,if then i click Play My game level scene is not restarting but continuing everything,having all it's pre created prefabs and all its game object.

How should I fix this particular bug and restarting the game when exit to main menu is clicked

Exit to Menu Button :

void OnMouseDown() {
    PauseGame.isPause=false;
    Application.LoadLevel("MainMenu");
}

Play button :

void OnMouseDown() {
    spriteRenderer.sprite = s2;
    Application.LoadLevel("Game");
}

I have three Prefabs:

Turret :

using UnityEngine;
using System.Collections;
public class Turret : MonoBehaviour {
// Use this for initialization
double LastBallTime=0.0;
double LastTurretMovingTime=0.0;
public double spawnballTime=1.5;
public double StartTurretMovingTime=35.0;
public double BallCount=2;
public bool IsRed=false;
public GameObject BallPrefab;
public GameObject RedBallPrefab;
Vector2 v ;

void Start () {
}

// Update is called once per frame
void Update () {
    if (Time.time > LastBallTime + spawnballTime) {
        LastBallTime=Time.time;
        int rand= Random.Range(1,6);
        if(rand>=1 && rand<=4)
            Instantiate(BallPrefab, transform.position, transform.rotation) ;
        else{
            Instantiate(RedBallPrefab, transform.position, transform.rotation) ;

        }

    }
    if (Time.time > LastTurretMovingTime + StartTurretMovingTime) {
        LastTurretMovingTime=Time.time;
        int x = Random.Range (-2,3);
        int y = Random.Range (-3,3);
        v = new Vector3 (x, y,0);
        gameObject.transform.position=v;

    }
}
void OnBecameInvisible ()
 {
    Destroy(gameObject);
 }
}

BALL :

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

public class Ball : MonoBehaviour {
// Use this for initialization
public static double Killed=0;
public Text ScoreTextPrefab;
 GameObject ParentCanvas;

void Start () {
    ParentCanvas = GameObject.Find ("Canvas");
}
void OnMouseDown() {
    if (!PauseGame.isPause) {
        Text t = Instantiate (ScoreTextPrefab, transform.position, transform.rotation) as Text;
        t.transform.SetParent (ParentCanvas.transform, false);
        if (gameObject.name.Contains ("RedBall")) {
                t.text = "O o P s";
                RedKilled++;
        } else {
                Killed++;
        }
        Object.Destroy (gameObject);
    }

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

}

void OnBecameInvisible ()
{
    Destroy(gameObject);
 }
}

TurretBall manager wish is assigned for the main camera of the game scene :

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

public class TurretBallManager : MonoBehaviour {

// Use this for initialization

public GameObject TurretPrefab;
public double turretSpawnTime=35;
public double LastTurretTime=0;
public double MaxTurret=10;
int currentTurretCount=1;
public Text Killedtxt;
Vector2 v;

void Start () {
    v = new Vector2(0,2);
    Instantiate (TurretPrefab, v, Quaternion.identity);

}
void CreateTurret()
{
    if (Time.time > LastTurretTime + turretSpawnTime) {
        LastTurretTime=Time.time;
        currentTurretCount++;
        if(currentTurretCount>1)
            v.x=TurretPrefab.transform.position.x-currentTurretCount/2;
        if(currentTurretCount<=MaxTurret){
            Instantiate(TurretPrefab,v,Quaternion.identity);
        }

    }
}
// Update is called once per frame
void Update () {
    Killedtxt.text = "Kill : " + Ball.Killed;
    CreateTurret ();
  }
}


texts: How do I make a blueprint run keyboard key commands?

texts:
I created a project based on the Top Down Example.

In the project comes a character that I can move by clicking on the terrain that already comes by default.

Image of gameplay:

In the character's blueprint, I added a function on the N KEY. Simply to print a sentence (key N).

Character's blueprint:

I created an NPC based on creating a Blueprint Class > Character:

In the NPC blueprint I added a function, only now in the M KEY, but with the same principle. Print a sentence (key M).

NPC's Blueprint:

It turns out that only the command made in the blueprint of the character works:

I alternately clicked the N and M keys to take the screenshot.

I scanned the character's blueprint to see if something was missing, something I needed to add in order for the NPC blueprint to recognize the keyboard command. But I only found things like that related to the mouse.

Scan:

I'd like to know what I need to do to make the NPC blueprint recognize the M KEY.


texts:
I am going to reference this image of what I want to accomplish in JavaScript.

This is the Diablo buffer system.  This question may be a bit advanced (or possibly not even allowed).  But I was wondering how you might go about implementing this type of system in a JavaScript game.  Currently to implement such a system in JavaScript escapes me, and I am turning to SO to get some suggestions, ideas, and hopefully some insight in how I could accomplish this without being to costly on the CPU.

Some thoughts of mine for implementing such a system would be to:

Create DIVS within a DIV that hold each position of the inventory
Go through each item you own in a container and see which DIV it belongs to
Make said item images the DIVs image

This type of system might possibly work if ALL items were 1x1, but for this example its not going to work out.

I am at a complete lost of ideas how to even accomplish this.  Although, maybe rendering directly to the canvas and checking mouse cords could work, there would more than likely be A HUGE annoyance when checking if other items are overlapping each other (meaning you cant place the item down, and possibly switching item with the cursor item ).

That said, what am I left with?  Do I need to makeshift my own hack system with messy code, or is there some source out there (that I don't know about) that has replicated this type of system in their own game.

I would be very grateful to get some replies on how you might go about doing this, and will accept answers that can logically explain how you might implement such a system (code is not required).

P.S. Id like to use pure JavaScript, and nothing else (even though it might be "reinventing the wheel", I also like to learn).


texts: Get / Calculate edges of a 3D object - C #

texts:
I need to get all vertices in the edge position of a determinate object 3D (in this case a path).

See the image:

My question is, how can I get only the edges vertices, like the image?


texts: What score/level function is often used?

texts:
In many games you raise a level when you reach a certain score, and later levels are harder to reach than in the beginning.

I am suspecting that it is some sort of exponential function that is used in e.g. WoW.

Does anyone know of a good exponential function for this purpose?


texts: I am using Unity Mecanim and I would like an animation ( walking animation about 2 seconds longs ) to repeat X times before moving to the next animation. How can I achieve this?


texts: Can someone explain the (reasons for the) implications of colum vs row major in multiplication/concatenation?

texts:
I am trying to learn how to construct view and projection matrices, and keep reaching difficulties in my implementation owing to my confusion about the two standards for matrices.
I know how to multiply a matrix, and I can see that transposing before multiplication would completely change the result, hence the need to multiply in a different order.

What I don't understand though is whats meant by only 'notational convention' - from the articles here and here the authors appear to assert that it makes no difference to how the matrix is stored, or transferred to the GPU, but on the second page that matrix is clearly not equivalent to how it would be laid out in memory for row-major; and if I look at a populated matrix in my program I see the translation components occupying the 4th, 8th and 12th elements.

Given that:

  "post-multiplying with column-major matrices produces the same result
  as pre-multiplying with row-major matrices.
  "

Why in the following snippet of code:

        Matrix4 r = t3 * t2 * t1;
        Matrix4 r2 = t1.Transpose() * t2.Transpose() * t3.Transpose();

Does r != r2 and why does pos3 != pos for:

        Vector4 pos = wvpM * new Vector4(0f, 15f, 15f, 1);
        Vector4 pos3 = wvpM.Transpose() * new Vector4(0f, 15f, 15f, 1);

Does the multiplication process change depending on whether the matrices are row or column major, or is it just the order (for an equivalent effect?)

One thing that isn't helping this become any clearer, is that when provided to DirectX, my column major WVP matrix is used successfully to transform vertices with the HLSL call: mul(vector,matrix) which should result in the vector being treated as row-major, so how can the column major matrix provided by my math library work?


texts: Use floats or doubles when writing mobile games

texts:
I know for shaders, floats should be used because they are the optimal choice for performance. Doubles are slow and use more memory which isn't ideal for shaders. While floats are less accurate and are prone to float overlflows, the tradeoff for speed is ideal on mobile hardware.

But what about everywhere else in the code base not related to the shader pipeline? I'm writing an engine and use doubles for the delta update tick and try to keep all units relative to that data type so there's lots of places using doubles. Should I be using floats on mobile in the engine as well?

The engine is written in C++ language


texts:
I have been having an issue with frustum culling, specifically culling planes (not to be confused with the frustum planes). I am using JOML in Java with the FrustumIntersection class, and using the projection matrix * the view matrix for the matrix (for the projection view matrix). The way I am finding the minimum and maximums for the AABB is by simply iterating through the vertices and multiplying that by the transformation matrix in JOML. Although this issue doesn't appear to happen with any meshes other than planes, here is a gif of what is happening:

As you can see, the plane is being culled when the camera moves on a certain axis when looking straight down (it should not be doing that), but only on that axis. Any answer that could hint me in the right direction would be great.

Thanks!

UPDATE:
The issue was fixed, it was just a simple problem with the way I was storing the vertices, getting the axises intertwined.


texts: What Java library/framework for a game with Baldur's Gate like grapics?

texts:
I really would like to create my own small rpg. It could probably look as simple like baldurs gate. So without fancy 3D stuff.

As language I want to use java (or scala, I thinking about it - the good thing is that all java libs would work with scala too, and there are a lot of java game libs) and I'm not sure what lib/framework should I choose. I thought about LWJGL or Slick2D. Because I wont use that much 3D, Slick2D would be the better choice? Or doesn't matter? Any ideas or suggestions? Thank you


texts: In my browser game's website description, can I use a title of another game?

texts:
For instance, if I think my game is a cross between Age of Empires and Minesweeper, can I have written on the description of my website "A browser-based hybrid of Age of Empires and Minesweeper" ?
Thanks!


texts: Lagging problem with chunk creation in Godot

texts:
We are developing a 2D game in Godot and we are stuck while trying to divide the map in chunks. Namely, the scene is a forest, where trees spawn positions were generated by noise: since the trees are too many to be loaded altogether, we created a Chunk node, which only instances trees contained in it, and gets instanced and deinstanced according to player's position. Though, this does not seem to be enough: each time a new chunk is to be instanced, we get a lag spike. How can we improve this?
This is the script attached to Chunk:

extends Node2D

var noise

func _ready():
    randomize()
    self.name=str(global_position)
    noise=get_node("/root/global").noise
    LoadTrees()

func LoadTrees():
    var x=-38
    while x<39:
        var y=-14
        while y<15:
            if noise.get_noise_2d(global_position.x+float(10*x),global_position.y+float(12*y))>0.07:
                InstanceTree(Vector2(10*x+rng.randi_range(-3,3),12*y+rng.randi_range(-3,3)),self)
            y+=1
        x+=1

func _on_Exit_body_exited(body):
    if body.name=="Player":
        call_deferred("free")

func _on_AreaLeft_body_entered(body):
    if body.name=="Player":
        var NewChunkPos=global_position-2*Vector2(380,0)
        get_parent().InstanceChunk(NewChunkPos)

func _on_AreaRight_body_entered(body):
    if body.name=="Player":
        var NewChunkPos=global_position+2*Vector2(380,0)
        get_parent().InstanceChunk(NewChunkPos)

func _on_AreaDown_body_entered(body):
    if body.name=="Player":
        var NewChunkPos=global_position+2*Vector2(0,170)
        get_parent().InstanceChunk(NewChunkPos)

func _on_AreaUp_body_entered(body):
    if body.name=="Player":
        var NewChunkPos=global_position-2*Vector2(0,170)
        get_parent().InstanceChunk(NewChunkPos)

The functions the script calls from its parent's script go as follows:

func InstanceTree(pos,Parent):
    var tree=Tree.instance()
    tree.position=pos
    tree.name=str(global_position)+"_tree_"+str(pos)
    Parent.call_deferred("add_child",tree)

func InstanceChunk(NewChunkPos):
    if not self.has_node(str(NewChunkPos)):
        var NewChunk=Chunk.instance()
        NewChunk.global_position=NewChunkPos
        NewChunk.name=str(NewChunkPos)
        call_deferred("add_child",NewChunk)


texts: How to sync towers and enemies in Tower Defense?

texts:
I'm going to build a tower defense (like) game.

In a heavy tower defense, it takes time to processing.

So, if i set a time interval, it costs interval+processing time so it's not fair.

If i make a processing unit run every 100ms and process all things, it'll be fair but it costs more. And this is not good for flying weapon(like bombs).

Any another way or just use 100ms process unit?


texts:
My renderBoard is slow and it's because of font.draw function. I read that I should use stringBuilder instead of string, but it didn't help at all. I suppose I'm using it wrong. Could you guide me to the right way?

public void renderBoard(SpriteBatch sb, BitmapFont font) {
    int L = 0;
    String string;
    ...
    // "size" is a private variable of the class, the same goes for "stringBuilder"
    for(int k = - size + 1; k <= size - 1; k++) {
        for (int j = 1; j <= size - Math.abs(k); j++) {
            string = L + "";
            for(int g = 0; g < string.length(); g++) {
                stringBuilder.setCharAt(g, string.charAt(g));
            }
            sb.draw(
                    this.getTexturesArray().get(L),
                    x_j_k_position,
                    y_j_k_position
            );
            font.setColor(Color.WHITE);
            font.draw(
                    sb,
                    stringBuilder,
                    x_j_k_position,
                    y_j_k_position
            );
            L++;
        }
    }
}

If I comment out the font.draw line, the game accelerates, so I guess here lies the problem.


texts: How to draw and store a Zelda-like map in custom game engine?

texts:
I have a school assignment where I have to draw a 2D map from one of the first zelda games, along with some animated sprites. Now I got the sprites to work, Im having trouble drawing the map. This is what it should look like:

This is the TileSet that we have to use to draw the map (each tile is 32x32 pixels):

We work in a custom game engine that our teacher made for us.

To draw a bitmap we use this command:
GAME_ENGINE.DrawBitmap([Name], x.cord (on the canvas), y.cord (on the canvas), x.cord(on the Tileset), y.cord(on the Tileset), amount of pixels you want to cut out of the Tileset (Width), amount of pixels you want to cut out of the Tileset (Height).

If I use this command I would draw the staircase tile (top left) on the canvas:
GAME_ENGINE.DrawBitmap([Name], 200, 200, 0, 0, 32, 32);

So I found out that with a nested for loop you can draw a 2D map on the canvas, this is the code I used for that:

for (int y = 0; y < 10; y++)
{
    for (int x = 0; x < 16; x++)
    {
        GAME_ENGINE.DrawBitmap(Link_Level, 128 + (x * 32), 0 + (y * 32), 0, 0, 32, 32);
    }
}

But obviously then it draws a 16 x 10 map consisting of only one tile.

My question is: How can I use that same for loop but somehow let it know which tiles to draw on the correct position?

Any help would be appreciated!


texts: How to reference the right object in Unity

texts:
So, I'm developing this small 2D project where I have a sphere that detects if objects get close to it from three different directions.

I have successfully found a way to detect if an object touches my line if the object is referenced to a certain LayerMask, in this case the walls.

So, basically I'm doing this:

var layerMask = 1 << 10; //wall layer
float left = 0f, middle = 0f, right = 0f;

Debug.DrawLine (leftStart.position, leftEnd.position, Color.green);
Debug.DrawLine (middleStart.position, middleEnd.position, Color.green);
Debug.DrawLine (rightStart.position, rightEnd.position, Color.green);

leftSpot = Physics2D.Linecast(leftStart.position, leftEnd.position, layerMask);
middleSpot = Physics2D.Linecast(middleStart.position, middleEnd.position, layerMask);
rightSpot = Physics2D.Linecast(rightStart.position, rightEnd.position, layerMask);

Now, what I would like to do is reference the right wall (Horizontal or vertical) and calculate the distance between the wall and my sphere with:

Vector2.Distance(transform.position, wall1.position);

How can I get the reference to the correct wall to do this?

Thank you


texts: Why do I get an error "exit() redefinition" while using OpenGL?

texts:
I am using Visual C++ 2010 and I get the following errors:

1>d:\visual c++\vc\include\stdlib.h(353): error C2381: 'exit' : redefinition; __declspec(noreturn) differs
1>d:\glut-3.7.6-bin\include\gl\glut.h(146) : see declaration of 'exit'

In my project I have 3 files.  Here are the includes from each of them.

Main.cpp

#include<iostream>
#include "BmpLoader.h"
#include<glut.h>

BmpLoader.h

#include<stdio.h>
#include<glut.h>
#include<Windows.h>

BmpLoader.cpp

#include "BmpLoader.h"

As far as I know, I receive this error due to the include order.  I have tried so far several arrangements of the includes, but haven't figured out the proper arrangement.

What library combination causes this error and what include order should I use in order to prevent it?


texts: Change Shader on This Material Via Code?

texts:
How do I change this material to have the Toon/ Lit Outline shader via code at the Start of the scene?

Here is my code that I have as of now, that does not work:

 using UnityEngine;
 using System.Collections;

 public class MainMenuManager : MonoBehaviour
 {
     public Material hatMaterial;    //This is my character's hat shader - I set this in the Inspector

     private Shader toonShader;    //This is the Toon Shader with an Outline

     void Start ()
     {
         toonShader = GetComponent<Shader> ();

         toonShader = Shader.Find ("Toon/Lit Outline");

         hatMaterial = GetComponent<Material> ();

         hatMaterial.shader = toonShader;
     }
 }


texts: What does it mean to cross a scalar with a vector in a 2D plane?

texts:
At the moment, I'm following this page to create a physics engine.

As per that page, I need to cross angular velocity by a distance vector to get relative torque and such, but I'm not sure how (in a 2D plane), you can cross a scalar(angular velocity), and a vector(such as the distance vector). I've assumed so far that you multiply the magnitude, but obviously this isn't correct, as I continue the debugging of my flimsy code. What am I missing?


texts: Follow behaviour with transform.LookAt on Unity2d

texts:
So i've been trying to make an enemy follow my player on Unity2d using transform.LookAt.
While it does follow the player, It also rotates the enemy as well in 3D but my sprite is made for 2d so the sprite just vanishes. Any ideas?

//follows player
transform.position = Vector2.MoveTowards(transform.position, target.position, speedEnemy * Time.deltaTime);

//make enemy look towards player
transform.LookAt(target);


texts: How Extract Frustum Planes from Clip Coordinates?

texts:
I'm having some problems with my Frustum Culling and I want to debug it, so I'm trying to render it's planes, to see exatly the Frustum. But I'm using the Clip Coordinates to do the culling (like OpenGL pipeline do), but I dont know how to render a frustum, in another words, I dont know how to convert a frustum in Clip Coordinates to a "Frustum Mesh".

Actually to calculate the frustum I use this function:

glm::vec3 point = MVP * glm::vec4(-radius, -radius, -radius, 1.0f)) //leftTopPoint
return (point.x > -point.w) && //Inside left clipping pane
       (point.x < point.w) && //Inside right clipping pane
       (point.y > -point.w) && //Inside bottom clipping pane
       (point.y < point.w) && //Inside top clipping pane
       (point.z > -point.w) && //Inside near clipping pane
       (point.z < point.w); //Inside far clipping pane

Where MVP is a glm::mat4 of Projection * View * Model matrices.

This function is activated only when I press the left click of mouse, so I want to render the Frustum and see how it is.

Also I dont use a "lookAt" function to rotate the camera, I'm using Quaternions (dont know if that matters).

Sorry if it is a bit confusing, it's hard to explain. So I just need a tip or a orientation/example of how achive this.

Thanks for your attention.


texts:
I am creating own sprite drawer with DX11 on C++. Works fine but I dont know how to apply source rectangle to texture coordinates of rendering surface(for animation sprite sheets)

            //source = (0,0,32,64); //RECT

            D3DXVECTOR2 t0 = D3DXVECTOR2( 1.0f, 0.0f);
    D3DXVECTOR2 t1 = D3DXVECTOR2( 1.0f, 1.0f);
    D3DXVECTOR2 t2 = D3DXVECTOR2( 0.0f, 1.0f);
    D3DXVECTOR2 t3 = D3DXVECTOR2( 0.0f, 1.0f);
    D3DXVECTOR2 t4 = D3DXVECTOR2( 0.0f, 0.0f);
    D3DXVECTOR2 t5 = D3DXVECTOR2( 1.0f, 0.0f);

    VertexPositionColorTexture vertices[] =
    {
        { D3DXVECTOR3( dest.left+dest.right,  dest.top,              z),D3DXVECTOR4(1,1,1,1), t0},
        { D3DXVECTOR3( dest.left+dest.right,  dest.top+dest.bottom,  z),D3DXVECTOR4(1,1,1,1), t1},
        { D3DXVECTOR3( dest.left,             dest.top+dest.bottom,  z),D3DXVECTOR4(1,1,1,1), t2},
        { D3DXVECTOR3( dest.left,             dest.top+dest.bottom,  z),D3DXVECTOR4(1,1,1,1), t3},
        { D3DXVECTOR3( dest.left ,            dest.top,              z),D3DXVECTOR4(1,1,1,1), t4},
        { D3DXVECTOR3( dest.left+dest.right,  dest.top,              z),D3DXVECTOR4(1,1,1,1), t5},
    };


texts: What is a simple way to pull input from a keyboard and attach it to a std::string?

texts:
The question says it all to be honest. I have a game that I am making in Ogre3D, using OIS as the main input library. My issue is that I am attempting to use CEGUI (with tons of errors) all to simply attempt making a string for my upcoming textbox class. The textbox graphics and font are already taken care of (by other classes), but what I need is the text from the keyboard to make this all happen (and this implementation seems way to difficult being such a commonplace thing to have in any program...).

My closest attempt with making a string to simulate that is as follows:

class CustomKeyListener: public OIS::KeyListener{
        using namespace OIS;
        public:
        std::string mString;
        CustomKeyListener(){mString="Blank";};
        bool keyPressed(const KeyEvent &arg){
            CEGUI::GUIContext& context = CEGUI::System::getSingleton().getDefaultGUIContext();
            context.injectKeyDown((CEGUI::Key::Scan)arg.key);
            context.injectChar((CEGUI::Key::Scan)arg.text);
            std::cout<<arg.text<<std::endl;
            return true;
        }
        bool keyReleased(const KeyEvent &arg){
            CEGUI::System::getSingleton().getDefaultGUIContext().injectKeyUp((CEGUI::Key::Scan)arg.key);
            return true;
        }
    };

As stated in the code, I want mString to be the containing text, and the textbox class (not made yet) will pull that string out and use it for whatever purposes. I would also like the idea of not having CEGUI included in the example if unneccesary (since it doesn't even take input, but gave me over a hundred errors upon adding to the program...)


texts: How to use motioncontroller thumbstick move (not press) to teleport motion controller pawn in UE4

texts:
To clarify the title: I'm using the built in VR blueprint, Oculus Touch controllers as my MotionControllers, and I'm trying to replicate the teleport style that RoboRecall uses (which should be possible given that RoboRecall was made in UE4 by EPIC themselves).

The blueprint does have a teleport feature built in, but it's activated by pressing
the thumbsticks in (as in pressing the thumbstick down until you hear the button click), what I'm hoping to do is instead activate it on thumbstick push (as in just tilting and move the thumbstick around, but not clicking it down).

So I can actually get it half working by just changing the input in the game settings > inputs section, but when you release the stick it loses the rotation data (though it does actually move your charecter to the right xyz).

So it would seem that the first part (activating the teleport blueprint stuff) activates when the thumbstick is moved, it requires the thumbstick to fully return to centre in order to move the player, which by then has lost rotation.
I'm new it UE4 and it might be a simple fix, so any pointers appreciated!


texts:
I have a DirectX10 texture (ID3D10Texture2D) that I load from disk with the following code:

CComPtr<ID3D10Device>   spD3D; // Initialized correctly elsewhere

hr = D3DX10CreateTextureFromFile(
        spD3D.p,
        wsFilename.c_str(),
        NULL, NULL,
        &spTextureResource,
        NULL
    );

if( FAILED(hr) || ! spTextureResource.p )
    return false;

spTextureResource->QueryInterface <ID3D10Texture2D> ( &m_spTexture );
if( ! m_spTexture.p )
    return false;

The texture loads fine, I can blit this onscreen.

Later, I want to use that texture as an atlas.  To do so, the first thing I want to do is to call ID3D10Texture2D::Map() in order to get at the texels and parse them (to determine where my tiles are).

The following call fails with E_INVALIDARG:

D3D10_MAPPED_TEXTURE2D mapped;
HRESULT hr = spTexture->Map( 0, D3D10_MAP_READ, 0, &mapped );

So I'm thinking that this fails because the texture can't be read from by the CPU.  So in order to get a texture that is CPU readable, I tried setting the D3DX10_IMAGE_LOAD_INFO structure to include D3D10_CPU_ACCESS_READ.  This fails on D3DX10CreateShaderResourceViewFromFile() with E_INVALIDARG.

So I guess I've given up trying to load in a texture and be able to read its data from on the CPU.

So I thought, what about making a texture with the following D3D10_TEXTURE2D_DESC flags:

    D3D10_TEXTURE2D_DESC    desc;
    ZeroMemory(&desc, sizeof(D3D10_TEXTURE2D_DESC));
    desc.CPUAccessFlags     = D3D10_CPU_ACCESS_READ | D3D10_CPU_ACCESS_WRITE;
    desc.Usage              = D3D10_USAGE_DYNAMIC;
    desc.BindFlags          = D3D10_BIND_RENDER_TARGET | D3D10_BIND_SHADER_RESOURCE;

Step 2 of my plan is to use CopyResource or CopyResourceSubregion to copy data from the disk file into my dynamic texture, so I can use the dynamic texture as a source to read texel data from.

Will this approach work?  Am I barking up the wrong tree and missing an obvious simpler route?

I'm worried that CopyResource won't work either, since the original texture was loaded from disk without the D3D10_CPU_ACCESS_READ flag.

God, I've got to write this for OpenGL too, I hope it's easier with GL!

My plan is to parse this texture and determine where my tiles are, so I can use the texture as an atlas for generating sprites.


texts:
I have created the walking and idle animation for my fps player. I've added a JavaScript script to access it, but when I run it and press button(w), it stops and says that the animation is not attached to the object.

When I drag the walking/idle animation and drop to that object, it creates an animation controller. Again I run it, still same error. I can't find where to attach the animation

Here's my script:

function Update ()
{
  if(Input.GetKeyDown("w"))
  {
    GetComponent.<Animation>().Play("walk_anim2", PlayMode.StopAll);
  }
  if(Input.GetKeyUp("w"))
  {
    GetComponent.<Animation>().Play("idle_anim2", PlayMode.StopAll);
  }
}

Where do I need to attach the animation?


texts:
I've been looking for something that can help me understand matrix transformations.  I've been to multiple different sites, including Wikipedia and quite a lot of related questions on SE and other forums.  I also posted a similar question in another forum and was unable to get results. Oh, and I visited a number of learning sites like Khan Academy to no avail.

The linked websites all provide methods to calculate transformed pixel-perfect collisions, but they require matrices for input.  Some of the sites tell you to ignore how matrices work and focus on the collision methods, but how can you do that if you need to use matrices for input?

In trying to figure out how to convert my data into matrices and use XNA's mysterious matrix transformation tools, I ran into one of math's famous jargon-barriers with such head-scratchers as vector space and linearity, among plenty others.

So the question is, can you explain how to create position, rotation, and scaling matrices, as well as how to combine them and why they work?

As I've explained, I wouldn't be asking this question if I hadn't exhausted all of my searching queries.  I am no more advanced in my mathematical understanding than Pre-Calculus.


texts:
I'm trying to use stencil buffer in directx 12. I have problem that probably is really easy to solve.
So, it's look like dx12 ignore it, ClearDepthStencilView() affect only depth, writing to stencil doesn't work.

D3D12_DEPTH_STENCIL_DESC for PSO:

static D3D12_DEPTH_STENCIL_DESC const defaultDepthStencil =
{
    /*DepthEnable*/                         TRUE
    /*DepthWriteMask*/                      ,D3D12_DEPTH_WRITE_MASK_ALL
    /*DepthFunc*/                           ,D3D12_COMPARISON_FUNC_LESS
    /*StencilEnable*/                       ,TRUE
    /*StencilReadMask*/                     ,D3D12_DEFAULT_STENCIL_READ_MASK
    /*StencilWriteMask*/                    ,D3D12_DEFAULT_STENCIL_WRITE_MASK
    /*FrontFace.StencilFailOp*/             ,{ D3D12_STENCIL_OP_REPLACE
    /*FrontFace.StencilDepthFailOp*/        ,D3D12_STENCIL_OP_REPLACE
    /*FrontFace.StencilPassOp*/             ,D3D12_STENCIL_OP_REPLACE
    /*FrontFace.StencilFunc*/               ,D3D12_COMPARISON_FUNC_ALWAYS }
    /*BackFace.StencilFailOp*/              ,{ D3D12_STENCIL_OP_REPLACE
    /*BackFace.StencilDepthFailOp*/         ,D3D12_STENCIL_OP_REPLACE
    /*BackFace.StencilPassOp*/              ,D3D12_STENCIL_OP_REPLACE
    /*BackFace.StencilFunc*/                ,D3D12_COMPARISON_FUNC_ALWAYS }
};

DSV heap desc:

D3D12_DESCRIPTOR_HEAP_DESC dsvHeapDesc = {};
    dsvHeapDesc.NumDescriptors = 1;
    dsvHeapDesc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_DSV;
    dsvHeapDesc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_NONE;

DSV desc:

D3D12_DEPTH_STENCIL_VIEW_DESC depthStencilDesc = {};
    depthStencilDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
    depthStencilDesc.ViewDimension = D3D12_DSV_DIMENSION_TEXTURE2D;
    depthStencilDesc.Flags = D3D12_DSV_FLAG_NONE;

Resource desc:

m_gBuffer[GB_Depth].Dimension( D3D12_RESOURCE_DIMENSION_TEXTURE2D );
m_gBuffer[GB_Depth].Width( m_width );
m_gBuffer[GB_Depth].Height( m_height );
m_gBuffer[GB_Depth].DepthOrArraySize( 1 );
m_gBuffer[GB_Depth].MipLevels( 1 );
m_gBuffer[GB_Depth].Format( DXGI_FORMAT_R24G8_TYPELESS );
m_gBuffer[GB_Depth].SampleCount( 1 );
m_gBuffer[GB_Depth].Layout( D3D12_TEXTURE_LAYOUT_UNKNOWN );
m_gBuffer[GB_Depth].Flags( D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL );

Then OMSetRenderTargets() and ClearDepthStencilView() with flags D3D12_CLEAR_FLAG_DEPTH, D3D12_CLEAR_FLAG_STENCIL.

Any idea what's missing?


texts: Is it legal to allow users to install replacement game data containing real-world personalities?

texts:
I'm thinking of developing a game for iOS which will ship with fake sports personality data. So, for argument sake, let's say fake football player names.

On OS X and Windows games like this often allow for users to install fan-made databases - which essentially overwrites the game's default data with (fan-made) "real word" data, thus circumventing intellectual property / likeness usage issues for the developer(s).

Is this legal?


texts:
I am working with cocos2d.

All my objects are declared on the CCLayer that I'm using, I have the logic of the game there and all the CCSprites.

Should I put the CCSprite for the player and all it's related properties (HP, Velocity, etc) in a Player object and then have that player object in my CCLayer?

But then how to add the CCSprite of the player to the CCLayer? Should I put in the CCLayer this?:

[self addChild:[PlayerObject playerSprite]];

Or should I create a controller?


texts: LibGdx: Pad the text inside an ImageTextButton

texts:
How can I pad (move around) text inside an ImageTextButton? Getting the cell of the label seems to not do anything.

ImageTextButton btn= new ImageTextButton("some text", btnStyle);
btn.getLabelCell().padLeft(-200); //does nothing


texts:
I have a camera at position P, and a normalized direction vector D (where the camera is facing). I want the target of the camera to be 5 units forward from the position. Here's my attempt:

F = (0, 0, 5) // forward
target = P + (D * F)

The obvious problem is that D * F can eventually reach (0, 0, 0), which would cause the target to be equal to the initial position. I feel like I'm missing something even more obvious than the problem here but, how would I properly have the target be 5 units forward?


texts: Is localisation important for a mobile game with little text?

texts:
Let's say it's a physics puzzle (Cut the Rope, Angry Birds) or a runner (Crossy Road, Subway Surfers) clone with some gameplay twists. Assume it puts text on some of the few controls: 'Play', 'Sound Volume', 'Level 15' etc. Most labels are accompanied with "standard" icons. Story is communicated with a text-free comic strip. Tutorial is also text-free.

can I publish it to Apple App Store and Google Play Store to every market while using English labels or it will be rejected?
will sales be affected a lot or negligibly when going:

freemium
premium.

Most articles I have seen are either PR of localisation companies or dealing with large/medium story-rich games.

PS: recommendations like "just remove all the text and use only icons" and "just localize it" are not something I am looking for.


texts:
I've been making this game where one of the characters, The Bandit, runs away from you mistaking you for a zombie. However, I can't seem to be able to animate the bandit. Is there a way I could use this w3schools example and make it fit with this canvas function?

The code for bandit is here or the second site:

   function drawBanditFacingDown(){
        //His face
    ctx.fillStyle = "#FFDE7A";
    ctx.fillRect(banditX, banditY, 25, 25);
    //His left eye (your left not his)
    ctx.fillStyle = "black";
    ctx.fillRect(banditX + 5, banditY + 5, 5, 8);
    //His right eye (again your right)
    ctx.fillRect(banditX + 15, banditY + 5, 5, 8);
    //His bandit thing on his mouth? I don't know what it's called
    ctx.fillStyle = "red";
    ctx.fillRect(banditX, banditY + 15, 25, 10);

    //His shirt
    ctx.fillStyle = "black";
    ctx.fillRect(banditX + 5, banditY + 25, 16, 25);

    //His arms
    //His right arm (YOUR RIGHT!!!!)
    ctx.fillStyle = "#FFDE7A";
    ctx.fillRect(banditX + 21, banditY + 25, 8, 20);
    //His left arm (On your left side)
    ctx.fillRect(banditX - 3, banditY + 25, 8, 20);

    //His pants
    //His right pant leg (ur right)
    ctx.fillStyle = "#11226B";
    ctx.fillRect(banditX + 12, banditY + 49, 8, 20);
    //his left pant leg
    ctx.fillRect(banditX + 5, banditY + 49, 8, 20);
    ctx.fillStyle = "black";
    ctx.fillRect(banditX + 11, banditY + 53, 3, 15);
    //his shoes
    //200 LINES!!!!!!
    ctx.fillStyle = "black";
    ctx.fillRect(banditX + 5, banditY + 68, 15, 5);
    }


texts: Projective texture and deferred lighting

texts:
In my previous question, I asked whether it is possible to do projective texturing with deferred lighting. Now (more than half a year later) I have a problem with my implementation of the same thing. I am trying to apply this technique in light pass. (my projector doesn't affect albedo). I have this projector View a Projection matrix:

Matrix projection = Matrix.CreateOrthographicOffCenter(-halfWidth * Scale, halfWidth * Scale, -halfHeight * Scale, halfHeight * Scale, 1, 100000);
Matrix view       = Matrix.CreateLookAt(Position, Target, Vector3.Up);

Where halfWidth and halfHeight is are half of the texture's width and height, Position is the Projector's position and target is the projector's target. This seems to be ok. I am drawing full screen quad with this shader:

float4x4 InvViewProjection;

texture2D DepthTexture;
texture2D NormalTexture;
texture2D ProjectorTexture;

float4x4 ProjectorViewProjection;

sampler2D depthSampler = sampler_state {
    texture = <DepthTexture>;
    minfilter = point;
    magfilter = point;
    mipfilter = point;
};

sampler2D normalSampler = sampler_state {
    texture = <NormalTexture>;
    minfilter = point;
    magfilter = point;
    mipfilter = point;
};

sampler2D projectorSampler = sampler_state {
    texture = <ProjectorTexture>;
    AddressU  = Clamp;
    AddressV  = Clamp;
};

float viewportWidth;
float viewportHeight;

// Calculate the 2D screen position of a 3D position
float2 postProjToScreen(float4 position) {
    float2 screenPos = position.xy / position.w;
    return 0.5f * (float2(screenPos.x, -screenPos.y) + 1);
}

// Calculate the size of one half of a pixel, to convert
// between texels and pixels
float2 halfPixel() {
    return 0.5f / float2(viewportWidth, viewportHeight);
}

struct VertexShaderInput {
    float4 Position : POSITION0;
};

struct VertexShaderOutput {
    float4 Position :POSITION0;
    float4 PositionCopy : TEXCOORD1;
};

VertexShaderOutput VertexShaderFunction(VertexShaderInput input) {
    VertexShaderOutput output;
    output.Position = input.Position;
    output.PositionCopy=output.Position;
    return output;
}

float4 PixelShaderFunction(VertexShaderOutput input) : COLOR0 {
    float2 texCoord =postProjToScreen(input.PositionCopy) + halfPixel();

    // Extract the depth for this pixel from the depth map
    float4 depth = tex2D(depthSampler, texCoord);
    //return float4(depth.r,0,0,1);
    // Recreate the position with the UV coordinates and depth value
    float4 position;
    position.x = texCoord.x * 2 - 1;
    position.y = (1 - texCoord.y) * 2 - 1;
    position.z = depth.r;
    position.w = 1.0f;

    // Transform position from screen space to world space
    position = mul(position, InvViewProjection);
    position.xyz /= position.w;
    //compute projection
    float3 projection=tex2D(projectorSampler,postProjToScreen(mul(position,ProjectorViewProjection)) + halfPixel());
    return float4(projection,1);
}

In first part of pixel shader is recovered position from G-buffer (this code I am using in other shaders without any problem) and then is tranformed to projector viewprojection space. Problem is that projection doesn't appear. Here is an image of my situation:

The green lines are the rendered projector frustum. Where is my mistake hidden? I am using XNA 4. Thanks for advice and sorry for my English.

EDIT:

Shader above is working but projection was too small. When I changed the Scale property to a large value (e.g. 100), the projection appears. But when the camera moves toward the projection, the projection expands, as can bee seen on this YouTube video.


texts: What is the best way to create a square grid in Unity?

texts:
So I need to create a square grid like the one below. And be able to click on a square, the square you chose then is filled with a different color as well as all the squares right and below the square you have chose.
My question is what will be the most efficient way to create this grid either in 3D or 2D in Unity.


texts: MotionBuilder- Actor attached to Mocap moves fluently, but Character using Actor as source jitters and has joints occasionally pop out

texts:
I'm trying to get a MotionBuilder animation to work in Unity on my custom character.
I've downloaded Motionbuilder FBX mocap files with Actors already attached from http://dancedb.eu/main/performances
The thing is that when I put the Actor as the Input source for my own (Characterized) character model and hit play on MotionBuilder, my model follows the animation 80% correctly but for the other 20% my character jitters and shakes and occasionally even "breaks a limb" when a joint randomly pops out of its place for a second.
Does anyone have suggestions on how to get the animation smoother for my Character?


texts:
How can I jump down from a platform in Unity?
I use two 2D colliders: one is my character, another one is platform. These colliders allow my character to stand on platform. Now whenever a characters ducks I show a button, when it is clicked I want my character to go through platform down. How can I achieve this?
I researched a few options and none of them worked for me. Let me explain them.
1 I can make the character collider isTrigger = true;. There is a serious problem with that option, because character would for a moment ignore all collissions. So, if for example, previously he would loose health due to bullet being hit into him, now the bullet will just go through him. Of course I can duplicate the code from the OnColliderEnter2D to the OnTriggerEnter2D. But it is a mess, so I feel that it would produce a technical debt. Hence, I want to avoid it.
2 I can make the platform collider isTrigger = true;. The problem with this approach is that now anyone standing on the platform would fall from it. Not only the character who clicked the button to jump through the platform down.
3 I can disable the collision of the colliders layers. Here the issue is that I feel it is a wrong way to treat layers. They are not intended to be used like that. My feelings can be easily proven by an example. Let us suppose we have two enemies with the same layer standing on the same platform. One of the enemies wants to go down, so I disable the layer collision. And as a result two of the enemies go down. Yeah, I actually want a generic solution for the down jump. Such a solution which would be applicable not only as if it is the last feature I add into my game. I want to be able to empower enemies later on to do the same things as a character does.
So, I basically need something which would take the character collider and allow it to go down through the platform collider once.


texts: Do you need special permission to personify companies as characters?

texts:
in the Hyperdimension Neptunia series a number of human characters are personifications of games companies ie.

Compa = Compile Heart
Red = Red Entertainment
Tekken = Namco
Falcom = Nihon Falcom
Cave = CAVE Interactive
IF (Iffy) = Idea Factory
Nippon Ichi-chan/Nisa = Nippon Ichi Software/Nippon Ichi Software America

I am wondering if the creators of Hyperdimension Neptunia had to get special permission/licences from companies to personify them in the game? (ie. a developer personifying Valve or Square in their own game)


texts: Spell design and comunication with Player

texts:
Im trying to design Spell class that can modify almost anything, Player, Units, other spells, etc. I figured out two ways of doing it, but none of this seems proper for me. Thats mainly because of Player class that got a lot of parameters and setting spell is a bit troublesome.

First is:

Spell interface that Im adding to each class of spell, which have method: execute.

Pros:

dont have to pass a lot of parameters, just call proper function of target class of a spell
To use spell just pick spell Player.GetSpell("Fireball").Execute(targets)
Big flexibility

Cons:

A LOT OF CLASSES, like 30 or more. One for each spell type
Each spell need to be wrote manually

Creating spell

class Fireball : SpellBase, ISpell
{
    public void Execute(Player caster, List<Object> target)
    {
        caster.Mana -= ManaCost;

        foreach (var o in target)
        {
            if (o.GetType() == typeof(Player))
            {
                var p = (Player)o;
                p.Health -= 10;
                Console.WriteLine("Player: {0} recieved 10 dmg, now has {1}",
                    p.Name, p.Health);
            }
            else if (o.GetType() == typeof(Spell))
            {
                var s = (Spell)o;
                s.Cooldown += 1;
                Console.WriteLine("Unit: {0} recieved 10 dmg, now has {1}",
                    s.Name, s.Health);
            }
        }
    }
}

Construction

spells.Add(new Fireball());

Executing

spells.First().Execute(caster, enemy);

Second approach:

Write one or few classes that can have different functionality depending on parameters set in constructor.

Pros:

few classes
loading parameters from file or data base

Cons:

setting a lot of parameters for different classes(spells and player really dont have much common fields)
One gigantic method, to handle spell execution

Creating spell

class Spell:SpellBase
    {
        public SpellData Data { get; set; }

        public Spell(SpellData param)
        {
            Data = param;
        }
    }

Construction

 spells.Add(new Frostball(params));
                {
                    HealthMod = -10
                });

Executing

public void CastSpell(Player caster, List<Object> enemy)
        {
            Caster.Mana -= ManaCost;

            foreach (var o in enemy)
            {
                if (o.GetType() == typeof(Player))
                {
                    var p = (Player)o;
                    p.Health += spell.Data.HealthMod;
                    //p.Defence += spell.Data.DefenceMod;
                    //and a lot of atributes and dependencies
                    //.
                    //.
                    //..........
                }
                else if (o.GetType() == typeof(Spell))
                {
                    var s = (Unit)o;
                    s.Cooldown += spell.Data.CooldownMod;
                    //s.Defence += spell.Data.DefenceMod;
                    //and a lot of atributes
                    //.
                    //.
                    //..........
                }
            }
        }

So... I need flexibility a lot. Im not saying its not possible to make it with second way but it will make one big Method with a lot of ifs, which I want to avoid, and i know that with time complexity of this will overwhelm me. Also setting parameters of all spells easily from DB would be nice.

Which one approach do you suggest? Maybe change sth or even you have ideas for whole different way of doing this? Please help me :)

Designin's hard...
Sorry for english.


texts:
As stated in the title, my program stutters like crazy, even though my program for the most part runs for 60 fps. During the moments it stutters, FPS momentarily drops down to 59(stats from FRAPS).

Here is an video capture of the stuttering in action. If you look closely, you can see the game stutter around 3-4 times. It is much more noticeable in real life.

http://gfycat.com/SevereCanineBabirusa

CLR Profiler shows that garbage collection doesn't run at all during that time, never mind 4 times, so it's not that.

Here's the code for movement:

            //Movement logic
            //Increase the speed
            speed = Math.Min(speed + (speedIncrement * (gameTime.ElapsedGameTime.Milliseconds / 200.0f)), maxSpeed);

            for (int i = fruits.Count - 1; i >= 0; i--)
            {
                //Move the fruits
                fruits[i].pos.Y += speed * gameTime.ElapsedGameTime.Milliseconds;
                fruits[i].rect.Y = (int)fruits[i].pos.Y;
                //Check if the fruit is past the screen. If it is, remove it from fruits
                if (fruits[i].rect.Y > screenHeight)
                {
                    fruits.Remove(fruits[i]);
                }
            }

IsFixedTimeStep is set to false, but SyncronizeWithVerticalTrace is on. Any idea what could be the cause of the stuttering?

EDIT: Apparently it was a combination of this: http://answers.microsoft.com/en-us/windows/forum/windows_7-performance/presentationfontcacheexe-uses-50-of-my-cpu/4200fe85-458f-4f19-b791-1fe5395304da and f.lux eating up my CPU/GPU cycles.


texts:
I'm using Shader-toy to experiment and try to learn a bit the shader science.
As exercise I wan to replicate some of the wikipedia math plots. I've started with a Super Formula.

What I want to achieve is this:

(taken from this wikipedia image)

This image shows the parameter of the super formula thing:

a=b=1,
m=3,
n1=5,
n2=18 and
n3=18

I've looked for a similar example, simplified it and try to reproduce my curve.

In shader-toy this is my code:

void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
    // Variables to be fed into the formula
    float a = 1.0;
    float b = 1.0;
    float m = 3.;
    float n1 = 5.0;
    float n2 = 18.;
    float n3 = 18.;

    vec2 uv = fragCoord.xy / iResolution.xy;

    // translation
    vec2 sf = uv - 0.5;

    // r of the current point
    float pr = sqrt(sf.x*sf.x + sf.y*sf.y);
    // Angle (Phi) of the current point
    float f = atan(sf.y/sf.x);

    // The formula itself. Division by 10.0 added to scale the result down a bit.
    float r = pow((pow(abs(cos(f*m/4.0)/a),n2) + pow(abs(sin(f*m/4.0)/b), n3)), -(1.0/n1)) / 10.;

    // Output with coloring by relative radius
    fragColor = (pr <= r) ?
        vec4(1., 0., 0., 1.0) :
        vec4(0.1, 0.1, 0.1, 1.0);
}

But I'm achieving a different shape:

What am I doing wrong?


texts: For a 2D scenario, I want to have a fan blow at an object and make the object move with the "wind". How can I simulate the wind force blown by the fan?


texts: Cocos2d how to correctly preload a spritesheet before the scene start?

texts:
I'm working on a game with Objective-C and Cocos2d, the game has a huge number of images, and obviously as I add images on the spritesheet (well yes I'm using spritesheets) the loading time get longer, I've seen a huge increasing in loading time since the last update (I had to add a lot of stuff) and that's why I truly need to preload the entire spritesheet before the game start. So here is what I don't know exactly how to do, I'm using this method in the appDelegate in the applicationDidFinishLaunchingWithOptions method:

[[CCSpriteFrameCache sharedSpriteFrameCache] addSpriteFramesWithFile:@"spriteSheetFile.plist"];

but seems to do nothing. There is surely something I'm missing...

I've also tried:

[[CCTextureCache sharedTextureCache] addImageAsync:image_png target:self selector:@selector(loadImage:)];

but to be honest I'm not sure on how to use this with a spritesheet...

so my question is: what here is wrong and how can I preload a spritesheet full of sprites before the game start? and also what I'm not totally sure about is, if I preload a spritesheet, this means that when the game start the sprite needs to be draw the first time, there is where the loading comes from? how can I make this scene loading as fastest as It can?

any help would be great, thanks


texts:
In my game I have model loading functions for Assimp model loading library. I can load the model and render it, but the model displays incorrectly. The models load in as if they were using a seperate projection matrix. I have looked over my code over and over again, but I probably keep on missing the obvious reason why this is happening.

Here is an image of my game:

It's simply a 6 sided cube, but it's off big time!

Here are my code snippets for rendering the cube to the screen:

void C_MediaLoader::display(void)
{
    float tmp;

    glTranslatef(0,0,0);
    // rotate it around the y axis
    glRotatef(angle,0.f,0.f,1.f);
    glColor4f(1,1,1,1);

    // scale the whole asset to fit into our view frustum
    tmp = scene_max.x-scene_min.x;
    tmp = aisgl_max(scene_max.y - scene_min.y,tmp);
    tmp = aisgl_max(scene_max.z - scene_min.z,tmp);
    tmp = (1.f / tmp);
    glScalef(tmp/5, tmp/5, tmp/5);

    // center the model
    //glTranslatef( -scene_center.x, -scene_center.y, -scene_center.z );
    // if the display list has not been made yet, create a new one and
    // fill it with scene contents
    if(scene_list == 0) {
        scene_list = glGenLists(1);
        glNewList(scene_list, GL_COMPILE);
            // now begin at the root node of the imported data and traverse
            // the scenegraph by multiplying subsequent local transforms
            // together on GL's matrix stack.
        recursive_render(scene, scene->mRootNode);
        glEndList();
    }
    glCallList(scene_list);
}

void C_MediaLoader::recursive_render (const struct aiScene *sc, const struct aiNode* nd)
{
    unsigned int i;
    unsigned int n = 0, t;
    struct aiMatrix4x4 m = nd->mTransformation;

    // update transform
    aiTransposeMatrix4(&m);
    glPushMatrix();
    glMultMatrixf((float*)&m);

    // draw all meshes assigned to this node
    for (; n < nd->mNumMeshes; ++n) {
        const struct aiMesh* mesh = scene->mMeshes[nd->mMeshes[n]];

        apply_material(sc->mMaterials[mesh->mMaterialIndex]);

        if(mesh->mNormals == NULL) {
            glDisable(GL_LIGHTING);
        } else {
            glEnable(GL_LIGHTING);
        }

        for (t = 0; t < mesh->mNumFaces; ++t) {
            const struct aiFace* face = &mesh->mFaces[t];
            GLenum face_mode;

            switch(face->mNumIndices) {
                case 1: face_mode = GL_POINTS; break;
                case 2: face_mode = GL_LINES; break;
                case 3: face_mode = GL_TRIANGLES; break;
                default: face_mode = GL_POLYGON; break;
            }

            glBegin(face_mode);

            for(i = 0; i < face->mNumIndices; i++) {
                int index = face->mIndices[i];

                if(mesh->mColors[0] != NULL)
                    glColor4fv((GLfloat*)&mesh->mColors[0][index]);

                if(mesh->mNormals != NULL)
                    glNormal3fv(&mesh->mNormals[index].x);

                glVertex3fv(&mesh->mVertices[index].x);
            }

            glEnd();
        }
    }
    // draw all children
    for (n = 0; n < nd->mNumChildren; ++n) {
        recursive_render(sc, nd->mChildren[n]);
    }
    glPopMatrix();
}

Sorry there is so much code to look through, but I really cannot find the problem, and I would love to have help.


texts: Why aren't more games 64-bit executables?

texts:
Until now I've seen that many games are still compiled in 32-bit architecture although nearly 50% of current Windows users are on 64-bit OS? Why is this?

If the reason is for getting larger audience (since 32-bit app could run on 64) why don't they make two versions of it, since it is more or less about recompilation and running 64 bit apps could give performance benefit due to more available CPU registers and other features.


texts: Texture filtering of look-up table in post process shader

texts:
I am doing post processing by drawing to an FBO and then applying a certain fragment shader when drawing the FBO's texture to the screen. I want to use a look-up table texture to apply color grading. Since I am targeting OpenGL ES 2.0 and possibly older PCs, I cannot use 3D textures. Instead I can use a 2D texture as an atlas of the layers of my 3D look-up table.

What I'm concerned about is correctness and performance when the texture lookup is performed. My look-up texture needs to have linear filtering so I don't have to have a full 256^3 sized look-up table to cover all hues.

My fragment shader would look something like this: Round B up and down to get the two regions of the texture to sample from, add offsets accordingly to R/G and sample the texture twice with the two offset .rg values. And finally linearly interpolate based on B.

But I as I understand it, the when the GPU encounters a texture2D call on a texture with linear filtering, it will be calculating the input coordinates for those calls for neighboring pixels in parallel to get a derivative. This derivative is used to determine how to sample the texture pixels.

Since this is a post process, I don't want two neighboring pixels to influence each other. It could be a black pixel from the edge of a sprite next to a bright blue sky pixel. In the look-up table, these two would need to sample distant points. So is the GPU going to decide the derivative is huge (minification) and try to linearly sample and involve all the random in-between texels on my look-up table?

Is there a way to get my linear filter to ignore neighboring pixels and only interpolate from the 4 nearest texels? Sort of like treating everything as magnification?

The problem is similar to this question that was asked in regards to HLSL, but I'm targeting OpenGL 3.0 and OpenGL ES 2.0: Color grading, shaders and 3d textures


texts: Bounding volume hierarchy for outdoor scenes

texts:
I started with a very simple graphics engine a few weeks ago and I have finished a simple scene-graph and I am now at a point where I need to create a bounding volume hierarchy.

I never really thought about it that much and now I am stuck. Basically my current goal is to achieve view frustum culling and I know how to do this but I have no idea of how to generate a bounding volume hierarchy.

The problem that I have is that I don't know how to create bounding boxes spatially.

My scene-graph allows me to group objects together and at the moment I am doing this

[object_group1,object_group2,....object_groupN]

And now I just check if the object_group is inside my view frustum, but this is only a naive solution.

Which algorithm/data structure would you recommend for an outdoor scene?


texts: How to generate random points on the surface of a quadrilateral

texts:
Alright, I'm sure there has to be a simple way to do this but it eludes me at the moment.

I want to be able to generate random points on the surface of a quadrilateral in 3D space. (Defined simply as four points) What is the best way to go about doing this?

If the quad is a rectangle, this is trivial to do with random interpolation between points. However, this won't work for me since my quads aren't guaranteed to have rectangular properties.


texts: Good item distribution for 2d scroller game

texts:
I have made a scroller game where player moves to the right of the screen. I add a new uniform ground block about every 5 seconds.

I was wondering how often should I put bonus items. Currently I put them with 0.5 chance per added block of ground and if I fail to do, I do another 0.5 as a secondary chance. Once the player has enough number of items, then she can buy skins.

Is there a well known item distribution algorithm or a resource I can benefit from? I only have 1 type of item to keep it simple and the game is for mobile, but sounds like those items shouldn't be rare.


texts: How can I move the camera directly under a certain plane?

texts:
I am attempting to render a "reflection" of a scene for water:

To create this illusion, I need to render the scene from below, and then ignore all geometry below the water line.

As such, I need to move the camera below the water, and invert the pitch.

I have one problem: My entire framework is based on the fixed-function pipeline. Basically, I need to call the correct glTranslatef() calls and glRotatef() calls to be able to simulate the camera being in the new position, and then render the scene.

Unfortunately, I have so far failed to achieve this. Calling the glRotatef() function obviously just rotates the entire scene, so I am struggling to just simulate the camera rotation.

The water is at a height of 300. I believe I may be moving the camera down correctly by calling glTranslatef(0, -(2 * (camera.y() - 300))), but it has been impossible for me to get them to both work.


texts: How do game engines like Unity and Game Maker exports to other platforms?

texts:
From what I understand, if you want to export a Unity or GameMaker game from the editor, the game needs to be compiled to create an executable. I thought that to produce a Windows executable, you needed to be on Windows. How does Unity and GameMaker compile to Mac and Linux, if the engine is running on Windows? Likewise, How do they export to Android and iOS? Do they use the NDK for Android? What about WebGL?

How does the export actually work? Do they use a cross-platform framework written in some programming language, and when you do things with the editor it generates code using that programming language and framework, so that when you export, that code gets compiled? For WebGL, since the UnityScript code doesn't get compiled, can we see the .js files with the code?


texts: Wind-blown fire particle effect from scratch

texts:
I want to create an effect of fire and be able to give it a variable amount of "wind" to make it blow to the side. I don't want the particles to just curve off to the side, but to flow through the air semi-realistically, similar to the effect of the fire in this video.

I'm assuming this would involve using trigonometric functions to achieve a "wavy" pattern?

My engine is completely from scratch and built on top of Slick2D / LWJGL. I already have a particle system in place that I implemented for everything from simple blood splatter effects to projectiles.

Simple effects like a "spray" or blood splatter are easy, but I don't know how to make something more complicated. I'm not really sure how to make this look like anything but a random burst of small squares or poorly drawn fire sprites.


texts:
When distributing my game, I am going to compile all the resources and level data into a single binary package file, which is loaded from by the game.  Do I have to worry about my machine being a different endian-ness than the end-user's, or are discrepancies here obsolete?

If this is going to be a problem, what is the best way to circumvent or solve it?


texts:
I'm working on a 2D iPhone game using Corona (Trial version, so I can't use their forums). The game involves the character falling through the sky, and I'm trying to implement a "double jump" for the character, for him to be able jump up while falling. I'm using Corona's physics library to have the character fall, and so far the best method of having him jump is using the vertical impulse method

object:applyLinearImpulse(0, -0.4, object.x, object.y)

The problem I face is that when the character is just starting out (vertical velocity is low), he jumps really high, and when he's been falling for a while (vertical velocity is high), the jump is negligible. I'm guessing that the best solution is to use some sort of equation with the velocity as input to make the jump the same regardless of velocity, but I can't figure out what that equation would be.

Okay, so that's all my thoughts. The end question is, how exactly do you implement a double jump with physics? Is there a proper equation for my problem? Should I take a different approach? It's been done before in games like Smash Bros, so there's a repeatable solution, right?