texts: GLFW Problem "The driver does not appear to support OpenGL"

texts:
I am trying to learn OpenGL & GLFW , when I run this simple project
I get error ID : "65542" with the message "The driver does not appear to support OpenGL".
My graphics card is an old & cheap Intel 64MB


texts: What's a good method to update the U.I in Unity after a player scores a point?

texts:
I'm practicing with making a Pong clone and I've decided I want 2 large empty gameObjects on either side off camera to act as triggers to reset the game and add a point to either player's score, but Unity's U.I system confuses me.

Any help would be appreciated.


texts: Fast fullscreen quad rendering in Direct3D 11?

texts:
For the last few weeks, I've been trying to port a DX9 implementation of HDR rendering (tone mapping, bloom, stars, etc.) over to DX11. I believe I've got all features working but I'm not getting good enough performance. I'd like to be able to render the whole effect in under 4ms on a fairly low-powered GPU, but using D3D11 Queries I'm noticing that it takes 0.5ms to just render a fullscreen quad with a solid color, and 1.0ms to render a fullscreen texture! And because tone-mapping is the only part of the effect that uses a fullscreen texture, this makes it the most expensive!

I'm already doing some optimisations with my limited graphics knowledge, I've disabled blending and depth-testing, I make sure that the texture sampler uses sensible filtering settings, and I'm pretty sure that the effects of any state-changes are negligible. I've heard that rendering 1 oversized triangle instead of 2 can yield some improvements, but I'm not sure if that will help me in this situation. Basically, does anyone have any suggestions to speed up rendering of a textured quad?


texts: A shader that casts shadows, doesn't receive shadows and doesn't render any textures/models at all?

texts:
Bit of a strange one but I'm in the situation where i need a shader to essentially render nothing and cast a shadow!

I found this though some googling but sadly that casts shadows onto itself which is undesirable.


texts: Attaching a Body to another, without the new body impacting the physics of the first in ANY WAY

texts:
Basically I want to add a vision / sight cone to an enemy body,

So I have the sight cone body, and enemy body, but every joint or weld I have tried so far has caused the sight cone to severely affect and disrupt the physics and movement of my enemy, most of the time causing the poor guy to go into tailspins.

I only want the sight cone as a sensor, a sensor that has NO physics impact whatsoever on its parent body (the enemy) except simply to stay stuck to it as it moves, matching its position and rotation. but all I can seem to find is weighted attachments, that set up new anchors and whole new physics properties to me new joined body.

I hope you can help.


texts: Objective-C or C++ of game engine header file for iOS developers?

texts:
We've developed a game engine written in C++. Now we are preparing our game engine for iOS developers.

I guess that many game developers use C++ or Objective-C for their game apps. So I think we should expose the API of our library in both Objective-C (@class blahblah) header files and in C++ (class blahblah) header files.

Am I on the right track? If not, what is the most recommended way of exposing the API for our library?


texts:
I am currently developing a 2D multiplayer game in Java and I would like to use Lua to define clientsided visual animations. Although this sounds like a reasonable idea to keep the core Java code to a minimum, these scripts would be depending on the core code and would therefore break if the core code is obfuscated (think of naming of classes and fields, imports).

What options do I have? Is there a way around this? If I was the head of a million dollar game development company I could just leave the source wide open without any obfuscation whatsoever but unfortunately I am not. Anyone could just reverse engineer the compiled code, modify it, alter resources and claim it as their own. I am aware that obfuscation does not completely stop that, but it does require someone to put a whole lot more effort into it.

I am currently still in an experimental design phase so I do not have any code examples of what I'd like to protect.


texts: How to create the "drunk camera" effect in GTA 4?

texts:
If you have played GTA 4, then you have probably been drunk at some stage. This is one of the best intoxicated simulators I have ever seen. It is actually hard or sometimes almost impossible to drive a vehicle while drunk in this game.

I know that a lot of the things that make up this drunk experience are changes to the controls or having random changes in direction, but how would the camera be done?

The camera seems to wave in and out and side to side. It also has changing blur, and other effects going on. Would this be some kind of shader? What are the effects that are used on top of each other to create the experience?


texts: glUniformMatrix4dv with a unidimensional array

texts:
I am trying to convert this C++ gml code to C and am getting the same array but I cannot see anything on the screen, is there something I am doing wrong maybe on the shader?

GML code in C++:

GLuint MatrixID = glGetUniformLocation(programID, "MVP");
...
glm::mat4 MVP = Projection * View * Model;
printf("MVP:\n");
for(int i=0;i<4;i++)
  for(int j=0;j<4;j++)
    printf("%.2f\n",MVP[i][j]);  //prints the same list as in C
...
//durante el loop
glUniformMatrix4fv(MatrixID, 1, GL_FALSE, &MVP[0][0]); //draw a cube

C code:

GLuint MatrixID = glGetUniformLocation(programID, "MVP");
...
t_mat4 MVP;  //t_mat4 defined as typedef double t_mat4[16];
mulMatrix(Projection,View,MVP);
mulMatrix(MVP,Model,MVP);
printf("proj*view*model\n");
inrange(i,16)
    printf("%.2f\n",MVP[i]); //unidimensional array
...
//durante el loop
glUniformMatrix4dv(MatrixID, 1, GL_FALSE, MVP); //Nothing shows up

vertex shader:

#version 330 core

// Input vertex data, different for all executions of this shader.
layout(location = 0) in vec3 vertexPosition_modelspace;
layout(location = 1) in vec3 vertexColor;

// Output data ; will be interpolated for each fragment.
out vec3 fragmentColor;
// Values that stay constant for the whole mesh.
uniform mat4 MVP;

void main(){

    // Output position of the vertex, in clip space : MVP * position
    gl_Position =  MVP * vec4(vertexPosition_modelspace,1);

    // The color of each vertex will be interpolated
    // to produce the color of each fragment
    fragmentColor = vertexColor;
}


texts: Can I use copyrighted sprites for a demo?

texts:
I just had a quick question and wanted everyone's opinions.

I'm making a 2D demo game for a resume which I want to post online. I'm applying as a programmer position so I don't really have my own art. I am planning on using sprite sheets and tile sets from other games in order to create just one or two levels on my demo. I will give credit at the bottom of the screen and state that these sprites are not my own.

Is this a good idea or could this be potentially "dangerous" in the illegal sense?


texts:
I have a quiz online game. For each game there is a prize (number of scores). Now I have three ratings: top for the last day, top for the last week, total top (based on the sum of scores). Sum is not bad, but there is an issue: the more you play (even with bad results), the higher you are because more games leads to more points. I want to build a new rating, that takes in account not only sum of scores, but performance in games to. Just an average prize is not a good idea for me, because it means that winner of a single game will be higher, than a person who won 9 games and got not-maximum score in the last one.

Do you have any ideas/experience, what formulas could be used?

Thanks.


texts:
I've generated some 2nd order SH light-probes from cube-maps in my scene and I was surprised how strong artifacts are around the back of the dominant lights. I switched to a Lambert source plus ambient and got a result just like in the image below. Stupid SH Tricks (http://www.ppsloan.org/publications/StupidSH36.pdf) suggests a technique called Han Windowing for reducing the artifacts, which I'm guessing is a convolution filter similar to a Gaussian blur, but I'm unable to tell much from the description or find an example.

I've also read some sources that say Gaussian might be best when using a HDR source.


texts:
My game uses a system similar to Metroid Prime's logbook, in that it logs things the player encounters and discovers on their journey, categorizing it, etc.

I want to write out all of the possible entries they can find, with the categories and all, but I need a system similar to what'll be in the final product to toy with, and use as an example for when it gets implemented into the game itself.

A click through menu sort of thing. Writing out all of these long descriptions would be too much of a hassle in a regular text document (and would make it FAR too long), and doing it through HTML or something sounds far too messy.

Basically, I want something, like an app, that I can edit, and that'll let me click through the categories till I get to the entry I want, which should display on the side. Here's a really terrible example of what I'm looking for.

I'm probably stupid for asking this, and there's likely an extremely obvious solution to this, but I have a thousand other things related to the game to think about, and Googling didn't result in anything.


texts: Is this converting from or to premultiplied alpha?

texts:
I found this code buried under some rocks:

var divAlpha = 0xff00/color.A;
var r = (byte) (color.R*divAlpha >> 8);
var g = (byte) (color.G*divAlpha >> 8);
var b = (byte) (color.B*divAlpha >> 8);

The fields on color are bytes, of course. My guess would be it's avoiding using floating point operations to handle premultiplied alpha, but is it converting from or to? How does this work out?

Example output:

0x44112233 -> a: 0x44, r: 0x3f, g: 0x7f, b: 0xbf


texts: Rotate 3D cube so nearest side is facing user

texts:
How do I figure out the new angle and rotation vectors for the most visible side of the cube?

Why: The user can rotate cube, but when finished I'd like the cube to snap to a side facing the user.

What: I'm currently using CoreAnimation in iOS to do the rotation with CATransform3D. I have the current angle and the rotation vectors so I can do this:

CATransform3DMakeRotation(angle, rotationVector[0], rotationVector[1], rotationVector[2]);

Additional Info: I'm currently using Bill Dudney's Trackball code to generate movement and calculate angle and rotation vector.


texts: Enconding/Decoding bit value in Texture Alpha Channel

texts:
I am Rendering to a SurfaceFormat.Color. (R8G8B8A8)
The alpha of this format has 8 bits and I want to be able to use those 8 bits as a bit field.

For example, in one pass of my render, I want to save a bit value like 1 or 4  passing => 00000001 = 1 or 00000010 = 4 ....

The problem is that the output data of my pixel shader need to be in the range of [0 - 1].

How can I encode, for example, the value 00100001 = 33 in my surface.

I am doing this:

PixelShaderOutput PShader( PS_INPUT pin ) : COLOR0
{
    PixelShaderOutput output;
    ///bla bla bla
    output.color.a = 33 / 255;
    return output;
}

Is this the right way?

Will I be able to read it in the other side? I mean, in another shader, when I need to read this value, can I use float value = ReadTexture(...) * 255; where value will have 33? (or 00100001)

The GPU will make the right "convertion", cause 33 / 255 = 0,1294117647058824. Will it be encoded as 00100001 in the texture?

In this new shader I want to this value as a bitfield like:

bool xTextureRepeat = fmod(value , 64) >= 32;


texts: How can I improve the performance of texture switching without resorting to atlasing?

texts:
I'd like to use texture images that are not a sprite sheet or other form of texture atlas, mainly because I'll be consistently adding and swapping textures while I figure out the direction my game takes.

In Java, I'm using slick2d's TextureLoader to load a texture, and then I bind it with an unique id. However, when not using a spritesheet I have many more images to bind, which causes a potential performance problem. I've noticed that calling glBindTexture for every block I'm drawing is bad, it drops my FPS to 1.

I'm already rendering blocks with glCallList so I've found a middle-ground. I bind a single block texture and then render all blocks of that type in the chunk, and repeat for each unique block type. However, that's still less than preferable.

Is there a better way to efficiently use multiple textures without an atlas or sprite sheet?


texts:
I have installed Android Studio and set the path in unity. And I am able to build apks with no problem. But when I try to test in unity remote unity gives an warning as

  Set-up Android SDK path to make Android remote work

I don't know what is happening. If Android SDK path is not set then how am I able build the apks.

I tried to solutions like enabling usb debugging mode , running unity editor first then opening Unity Remote , installing Google USB driver component of Android SDK but none of them worked for me.


texts: Is my collision-free location script working?

texts:
I've recently been learning C# and I wanted to take one of my 2D tutorials to Unity.

I reached a step where I need to spawn my new sprite into a collision free location. I've followed direction - generated random location, calculating Vector2s using the location and collider, and then used a while loop to check Physics2D.OverlapArea using my 2 vectors.

But, because I'm still only just learning C#, I'm finding it difficult to know if I have actually written my code correctly. Is there any simple way of being able to figure this out? Using Debug or something?

Vector3 spawnLocation = new Vector3 (Random.Range (minSpawnX, maxSpawnX),
                                     Random.Range (minSpawnY, maxSpawnY),
                                     -Camera.main.transform.position.z);
Vector3 spawnPoint = Camera.main.ScreenToWorldPoint (spawnLocation);
Vector2 lowerLeftCorner = new Vector2 (spawnPoint.x - teddyBearColliderHalfWidth,
                                       spawnPoint.y - teddyBearColliderHalfHeight);
Vector2 upperRightCorner = new Vector2 (spawnPoint.x + teddyBearColliderHalfWidth,
                                        spawnPoint.y + teddyBearColliderHalfHeight);
while (Physics2D.OverlapArea (lowerLeftCorner, upperRightCorner) != null)
{
    spawnPoint.x = Random.Range(minSpawnX, maxSpawnX);
    spawnPoint.y = Random.Range(minSpawnY, maxSpawnY);

    lowerLeftCorner = new Vector2 (spawnPoint.x - teddyBearColliderHalfWidth,
                                   spawnPoint.y - teddyBearColliderHalfHeight);
    upperRightCorner = new Vector2 (spawnPoint.x + teddyBearColliderHalfWidth,
                                    spawnPoint.y + teddyBearColliderHalfHeight);
}
Debug.Log (Physics2D.OverlapArea(lowerLeftCorner, upperRightCorner));

I was trying to use a debug at the end there, but it doesn't seem to continue running every single time that there's a spawn, so I am still unsure if it is working.
I'm terribly sorry for my nooby code. Feel free to direct to me some place else if you feel I need to do so.


texts:
I am new to shaders, and I am trying to tint a texture to mark status of a enemy.

I am implementing shaders on OpenGL ES 2.0 (Mobile)

The problem is that with this shaders, I see the enemy without change (even if I assign de fragcolor to (1.0, 0 , 0 ,1.0), the real code is commented).

Vertex shader

uniform mat4 u_MVPMatrix;       // A constant representing the combined model/view/projection matrix.
uniform mat4 u_MVMatrix;        // A constant representing the combined model/view matrix.

attribute vec4 a_Position;      // Per-vertex position information we will pass in.
attribute vec3 a_Normal;        // Per-vertex normal information we will pass in.
attribute vec2 a_TexCoordinate; // Per-vertex texture coordinate information we will pass in.

varying vec3 v_Position;        // This will be passed into the fragment shader.
varying vec3 v_Normal;          // This will be passed into the fragment shader.
varying vec2 v_TexCoordinate;   // This will be passed into the fragment shader.

// The entry point for our vertex shader.
void main()
{
    // Transform the vertex into eye space.
    v_Position = vec3(u_MVMatrix * a_Position);

    // Pass through the texture coordinate.
    v_TexCoordinate = a_TexCoordinate;

    // Transform the normal's orientation into eye space.
    v_Normal = vec3(u_MVMatrix * vec4(a_Normal, 0.0));

    // gl_Position is a special variable used to store the final position.
    // Multiply the vertex by the matrix to get the final point in normalized screen coordinates.
    gl_Position = u_MVPMatrix * a_Position;
}

Fragment shader

precision mediump float;        // Set the default precision to medium. We don't need as high of a
                                // precision in the fragment shader.
uniform sampler2D u_Texture;    // The input texture.

varying vec3 v_Position;        // Interpolated position for this fragment.
varying vec3 v_Normal;          // Interpolated normal for this fragment.
varying vec2 v_TexCoordinate;   // Interpolated texture coordinate per fragment.

// The entry point for our fragment shader.
void main()
{

    vec4 texVal = texture2D(u_Texture, v_TexCoordinate);
    gl_FragColor = (1.0, 0 , 0 ,1.0);//vec4(texVal.rgb, texVal.a)*(1.0, 0 , 0 ,1.0);

}


texts: Handling input in ECS for multiple characters

texts:
I've been reading into Entity-Component-Systems, and they seem rather handy. However, I don't quite understand how input should be handled and after googling and looking thru GDSE posts, I've become even more confused. I see plenty of explanations, but no examples of how to incorporate things like an intent system.

Originally, I planned on polling for keyboard events and passing those events onto a controller. This controller would have a vector of callback functions, which could be rebound to different keys on the fly.
But then I realized it doesn't translate well into a game with multiple characters, each with their own set of actions - like a fighting game, or the Megaman X games that allow you to switch between characters.

I thought that if I were to make these callback functions rather generic, so that they just change the state of the character, then have a System that consumes states for different characters to apply different results to the action (IE, the "jump" button would set the currently controlled character's state to JUMPING. But maybe Character 1 jumps faster than Character 2, but Character 2 jumps higher). But that doesn't seem like a wise idea, because now I have a system for every state that each character could possibly have. It smells really bad, basically. And to have a character unsubscribe from one "State System" and resubscribe to another just gives me the feeling that I am not doing something right, but I am at a loss.

How should I handle input that can differ slightly from character to character? I feel like I am on the right track with having the states handle input, but I don't think that each state should have it's own system. A state should be generic and operate on many entities, not just a single instance of one!


texts: Lerp vs Vector math: one better than the other?

texts:
In Unity3D (all versions, I believe), there is a static function for the Vector3D class called "lerp".  It interpolates a point between two points a point, based off a provided percentage related to the desired distance between the two.

Alternatively, I could just get the direction I want to go as a point, subtract it from my current position, Normalize() the resulting vector, then multiply that times a speed value.

So:

Is one way faster than another?

and

Is there a third better/faster/easier/more efficient way I don't know about?

Thanks.


texts: How does Unity Static batch handle submeshes

texts:
I have the following 2 meshes:

Mesh 1
    Submesh 1 - Mat 1
    Submesh 2 - Mat 2

Mesh 2
    Submesh 3 - Mat 1 (same as mat1 from submesh 1)

Since submesh 1 and 3 have the same material and they are all static, I'd like to render submesh 1 and 3 in a single drawcall. However, Unity is failing to batch those submeshes together.

Is there a way to achieve this?


texts:
I need to use a variable from the main script of a game which is the score variable public int scoreCount; I need it in the main script because it will be needed to update the score when they get past a certain point.

I need to be able to access this variable.. so add or subtract from it i.e. scoreCount++; however I am not sure how to do this, I have looked at tutorials and they make no sense for me.. could someone please explain it in more detail.

I also need to be able to use the public void UpdateScore() function from the mainscript too, do I just do it the same way as the variable or is there a different method. Thank you.


texts: What is the clearest way to present several numbers in a very limited space?

texts:
I'm building a mobile incremental game and as, is typical for the genre, I've got a ton of changing values to show to the user. They serve both as a way to show them their progress, but also to help them make better decisions as the game goes on.

I have five values I want to show, the amount of "Harvesters" and "Salesmen" the user has, and then how many resources they're adding or removing from the resource pool, along with the net result. Say if you're harvesting 10 resources a second, and you're selling 2, you're netting +8/s.

In the following images, blurred to focus on the area in question, you can see the different styles I've tried out. This is the first style, where everything is shown to the player, but is exceptionally busy:

The second style is just the net change, but is missing the quantities of the two types of workers (ie 10 harvesters and 5 salesmen)

Finally the third style is a mix of verbosity and information, but does not show the net difference (ie +123/s).

I'm a fan of the first style because it shows the player everything, and as the programmer I'm happy to look at piles of numbers that represent the fruits of my labour, but the player might not want to see all of that. I've considered adding a toggle setting that goes between the styles if you press it, but I'm hoping there's some sort of happy medium here.

The highlighted parts of the image is all the space I have, but I can incorporate icons if it would help.

My question is between the three of these (or some totally different style), how can I convey the same amount of information clearly and cleanly?


texts: C++&SFML Moving Sprites Smoothly in Tiles

texts:
As a student, I've always wanted to become a game developer. So far I've managed to learn the basics of C++ and SFML 2.1

For my first project, upon deciding to make a 2D RPG-ish game, I encountered a problem that the game loop refreshes so quickly that if I move them by 1 pixel per frame, the sprite will move more quick than I intended to.

I implemented a frame-determined movement system(not sure what it's called) that whatever the fps is, the character moves at same speed.

However, I couldn't solve the problem(which is what I'm asking) that the sprite won't move smoothly. What's happening in my build is that the player will move about 1px per frame, and can be interrupted by other inputs. What I want the sprite to do is move horizontally 32px per second. How can I do this?

Edit: wasn't being clear enough. What I want the program to do is when I press 'Right' key once, sprite moves towards the positive side of x-axis, for 32px. What's currently functioning in my program is the sprite will move only once, 1px

TL;DR : I want to move my sprite like old-school RPG games, moving predetermined pixels(or tiles) smoothly.


texts: How do I keep a triangle strip between geometry shader invocations?

texts:
I'm using a small geometry shader to build a "ribbon" from a set of points. For each point, I create 4 vertices that represent a section of the ribbon:

[maxvertexcount(4)]
void    GS( point GS_Input v[1],
            inout TriangleStream<PS_Input> ptStream )
{
    float4  vertices[4];
    vertices[0] = float4(v[0].pos.x - 2, 0, v[0].pos.z + 2, 1);
    vertices[1] = float4(v[0].pos.x + 2, 0, v[0].pos.z + 2, 1);
    vertices[2] = float4(v[0].pos.x - 2, 0, v[0].pos.z - 2, 1);
    vertices[3] = float4(v[0].pos.x + 2, 0, v[0].pos.z - 2, 1);

    PS_Input ov = (PS_Input)0;
    for (int i = 0; i < MVC; i++)
    {
        ov.posW = mul(vertices[i], g_world);
        ov.posH = mul(vertices[i], g_wvp);
        ov.normalW = mul(float4(v[0].normal, 0), g_world);
        ov.color = v[0].color;
        ptStream.Append(ov);
    }
}

As mentioned on the MSDN: "A geometry shader generating triangle strips will start a new strip on every invocation", and because of this, I don't get a ribbon, all I get is a set of quads, just like as if I was doing some particle billboarding.
Is there any way to circumvent that in order to keep the same strip from on invocation to the next ?


texts: Point system that is not competitive or has a clear goal

texts:
I'm making a game in which the goal is to reach as much entries as possible and I want the player to see that he is making progress somehow. However the game shouldn't be of competitive nature (it co-operative), so I feel that points might not be the right measure. I thought instead of a progress bar, so you work towards a goal of entries. However the problem with this is that there isn't a specific number of entries the user should aim for; The more, the better.

Is there a way of showing progress without assuming there is an end and without it getting competitive?


texts: Understanding arguments to a signed distance field function

texts:
I'm looking into drawing a box using Inigo Quilez's code:

float sdBox( in vec2 p, in vec2 b )
{
    vec2 d = abs(p)-b;
    return length(max(d,vec2(0))) + min(max(d.x,d.y),0.0);
}

Do I understand correctly that for p is a point anywhere in 2d space?

If so, what is b?

I tried to draw a 2x2 rectangle at origin (assuming b is then vec2(2,2)) and do those calculations but nothing good came out. It should calculate the distance between the point and nearest edge, right?


texts: Upload Games to Steam without Greenlight?

texts:
I've been working on a little game, (which is nowhere near completion) and wanted to know, that when I'm finished, if I would be able to release it onto Steam without having to get it Greenlit.

The reason why this is, is that I already payed for tools and editors for making my game, and don't want to have to pay another $100 in order to release my game.

Is this possible?


texts:
Player cam has a raycast. I need it to work as pointer for player's bullet direction. If the ray hits any kind of object this spot will be the aim of player's bullets.

Here is my script

public class camraycast : MonoBehaviour {

Camera mycamera;
GameObject prefab;

public int bulletSpeed = 10;
public GameObject angle; //  camera
public GameObject players;

void Start () {
    prefab = Resources.Load("bullets") as GameObject;
    mycamera = GetComponent<Camera>();
}

void Update() {

    if (Input.GetMouseButtonDown(0))
    {
        Vector3 camScreen = new Vector3(0.5f, 0.5f, 0f); // center of the screen
        float rayLength = 100f;
        Ray ray = mycamera.ViewportPointToRay(camScreen);
        RaycastHit hit;
        Debug.DrawRay(ray.origin, ray.direction * rayLength, Color.red);

        if (Physics.Raycast(ray, out hit, rayLength))
        {
            print ("Looking at : " + hit.transform.name);
            GameObject bullets = Instantiate(prefab) as GameObject;
            bullets.transform.position = players.transform.position + angle.transform.forward * 0.1f;
            Rigidbody rb = bullets.GetComponent<Rigidbody>();
            rb.AddForce((hit.point - angle.transform.position) * bulletSpeed);
            Destroy(bullets, 9f);
        }
    }
    Vector3 camScreens = new Vector3(0.5f, 0.5f, 0f); // center of the screen
    float rayLengths = 100f;
    Ray rays = mycamera.ViewportPointToRay(camScreens);
    Debug.DrawRay(rays.origin, rays.direction * rayLengths, Color.red);
}
}


texts: My SFML sprite Move() function: FeedBack?

texts:
Hey so I'm making a pong game with SFML and in the process made a function that takes a Time, Speed, Angle of movement, buffer for the movement on the X axis, and buffer for the movement on the Y axis.

I then implemented this function into my custom mySprite class, more specifically into it's update() function which updates its Position using the above function to calculate its new position.

However I'm worried that giving the function the FrameTime() of the Window (the time since the frame was last updated) is not the best choice as the sprites might start jumping around if there's lag between frame updates or other problems.....

Finally I would like to know how my organization, planning, etc is..  Thanks!

my UPDATED, WORKING Code:

   #include<SFML/Graphics.hpp>
#include<SFML/System.hpp>
#include<cmath>
#include<vector>
#    define M_PI 3.14159265358979323846

sf::RenderWindow Window;

template<typename T>
void CalculateMove(T Time, T Speed, T Angle, T& buffX, T& buffY)
{   //Make the degrees positive
    if(Angle<0) Angle= 360+Angle;
    //determine what quadrant of circle we're in
    unsigned int  Quadrant= 1;
    if(Angle>90)  Quadrant= 2;
    if(Angle>180) Quadrant= 3;
    if(Angle>270) Quadrant= 4;

    //anything above 90 would be impossible triangle
    Angle= (float)(Angle-(int)Angle)+(float)((int)Angle%90);

    // calculates x and y based on angle and Hypotenuse
    if((int)Angle!=0){
        if(Quadrant==2 || Quadrant==4) Angle=90-Angle; //The unit circle triangle is flipped otherwise, causing x and y to be switched
        buffY= sin(Angle / 180 * M_PI)/ (1.f/(Speed*Time));
        buffX= sin((180-Angle-90)/ 180 * M_PI)/ (1.f/(Speed*Time));}

    else{// Movement is a straight line on X or Y axis
        if(Quadrant==0 || Quadrant==2) buffX= Speed*Time;
        if(Quadrant==1 || Quadrant==4) buffY= Speed*Time;}

    //Quadrant Factor (positive or negative movement on the axis)
    switch(Quadrant){
    case 1: break;
    case 2: buffX=-buffX; break;
    case 3: buffX=-buffX; buffY=-buffY; break;
    case 4: buffY=-buffY; break;}
};

/////////////////////////////////////////   Mysprite    ////////////////////////////////
class mySprite : public sf::Sprite
{
private:
    float velocity;
    float angle;

public:
    // all the values needed by the base class sprite();
    mySprite(
        const sf::Image& Img,
        const sf::Vector2f& Position = sf::Vector2f(0, 0),
        const sf::Vector2f& Scale = sf::Vector2f(1, 1),
        float Rotation = 0.f,
        const float Angle= 0.f,
        const float Velocity= 0.f,
        const sf::Color& Col = sf::Color(255, 255, 255, 255)):
      Sprite(Img, Position, Scale, Rotation, Col){
        angle= Angle;
        velocity= Velocity;};

    float Velocity(){return velocity;};
    void SetVelocity(float newVelocity){velocity=newVelocity;};
    float Angle(){return angle;};
    void SetAngle(float newAngle){angle=(float)(newAngle-(int)newAngle)+(float)((int)newAngle%360);};

    void Update(){
        float frameTime= Window.GetFrameTime();
        float X=0,Y=0;
        SetRotation(angle);
        CalculateMove(frameTime,velocity,angle,X,Y);
        Move(X,-Y);
    };

    void Accelerate(float PPS){velocity+=PPS;};
    void Turn(float degrees){
        angle=(float)((angle+degrees)-(int)(angle+degrees))+(float)((int)(angle+degrees)%360);};

    void Reflect(float CollAngle){
        SetRotation(-GetRotation());
        angle=360-angle;
        //TODO: factor in the collision angle
    };
};


texts:
Hi I'm trying to change from Cairo (2D Vector image library) to NanoVG.
I'm using C#, openTK and Nano.VG.NET to make my game.

I'm having issues with alpha? Transparency/Blending is an issue…

Here is an output

Without NanoVG Overlay :

With NanoVG Overlay :

I think it has to do with blending or the nano shader….Not sure. Does anyone knows how to solve this?

My OpenGL Initialization :

GL.DrawBuffer (DrawBufferMode.Back);
GL.Disable (EnableCap.Lighting);
GL.Enable (EnableCap.Texture2D);
GL.Disable (EnableCap.Multisample);
GL.Disable (EnableCap.SampleAlphaToCoverage);
GL.Disable (EnableCap.AlphaTest);
GL.DepthFunc (DepthFunction.Lequal);
GL.Enable (EnableCap.DepthTest);
GL.Disable (EnableCap.ScissorTest);
GL.Enable ( EnableCap.TextureRectangle);

GL.Enable (EnableCap.Blend);
GL.BlendFunc (BlendingFactor.SrcAlpha, BlendingFactor.OneMinusSrcAlpha);


texts: c++ How to use angular velocity that derived from inertia and force(torque) in 3d

texts:
I am relatively new to game development. May my terminology and description are not appropriate. Please excuse my poor phrasing and help me by giving advice on how to question better if this question seems less fitting. I really appreciate your efforts.

Hi. I am having hard time interpreting the set of values I have.
I have inertia and force(torque) in terms of x y z.
FYI I used x and y coordinates as my ground, flat coordinates and z as my up/down.

I am assuming that since f = ma, that angular acceleration must be a = f / m.
So I divide my torque by inertia.
Then I add those x y z values to my angular velocity variable's x y z.

However these x y z values confuse me. Don't I need angle/sec or radian/sec sort of values in order to apply rotation?
The x y z values I have seemed to not say anything about radians or angular movement.

Question : If I have ( 1, 2, 3 ) or any ( x, y, z ) as my angular velocity, how do I actually apply it as angular movement?

FYI Here I am pasting my code :

float mass = 100;
float devidedMass = 1.0/12 * mass;
Vec3 innertia(
    devidedMass* (_box._size.z*_box._size.z + _box._size.x*_box._size.x),
    devidedMass* (_box._size.y*_box._size.y + _box._size.x*_box._size.x),
    devidedMass* (_box._size.y*_box._size.y + _box._size.z*_box._size.z ));
box._angAccel += forceAng/innertia;
box._angVelo += box._angAccel;
box._angAccel.allZero();

source of my inertia calculation
http://www.health.uottawa.ca/biomech/courses/apa4311/solids.pdf


texts:
I'm trying to get rid of repetition on terrain, when viewed from up high. To achieve that, I've chosen Wang tiles. One thing I'm missing, and can't really find is any kind of generator that can take a source image and generate a set of Wang tiles from it.

So is there any kind of generator that implements Wang tiles generation from source image? I've tried to read the research papers, but algorithms descriptions there are quite sketchy and vague to be actually put to code.


texts: How to draw a rotatable and zoomable sphere?

texts: My game is a sort of business simulation game of Earth, and I want the main interface to be just like a google earth view. Is there a way to do this with built in OpenGL features or do I have to implement the engine myself.


texts:
In Unity I converted my single player game to a multiplayer game.
Now, the single player game does not work anymore because the objects are disappearing on start, due to the network identity.

What is the best practice for still using the same objects in a single player game?

My question is about a general implementation, and not about something in my game specific.

Example:

We create a simple single player game:

Make a sphere
Make a script to move it with arrows

We have a single player game!!

Change the script to be a networkbehaviour
Check for islocalplayer in the script
Make the sphere a network identity
Make a network controller

Now we have a multiplayer "game"!

HOWEVER

If we now want to play this game singleplayer, it will not work. Just try adding the sphere to a scene. It will disappear on start.

What can I do to make the object usable in both single and multiplayer scenes?


texts: Is there any game-oriented virtual machine out there?

texts:
I'm investigating about virtual machines and their use in Games.

I'm looking for something cross-platform (at least win/mac/linux, mobile and consoles are a nice to have but not mandatory) and it would be nice if it could be binded to the usual things that you need for a game, like a graphics and sound lib. If it had any sort of automatic garbage collection, it would be nice, too. And since I want to use it for games, it should be fast and not very memory-consuming.

So far I've found:

Parrot VM
The Lua Virtual Machine (pdf)
V8

I'm leaving the Java Virtual Machine and .net VM out of this list since I feel they are a bit too big for my purposes - but I'm far from an expert on these things. If you think I should include them, please put your reasons below.

Am I missing any important one?

PS: I think this should be a community wiki, but I don't seem to be able to mark it as one.

EDIT: My final objective is creating a scripting language for game development. I've no problem with interpreters (have implemented a couple in the past) but this time I'd like to translate the Abstract Syntax Tree of my language to a VM, for efficiency mostly.


texts:
I'm trying to set up a UI system. Say I have a text object 'text' which is visible onscreen. I want to change it with a button press using a script such that the text box's previous string is replaced with a new string held in a string variable 'chat'.

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

public class textchange : MonoBehaviour
{

public Text text; //the text box gameobject is dragged into this

public string chat; //the chat string is filled elsewhere

void Awake()
{

}

void Update()
{
(if button press logic here)
{
text.text = chat;
}
}

}

What I expect is for the text to dynamically change, but what happens is absolutely nothing, the gameobject does not have its text component rewritten. What gives?


texts:
I'm currently getting into the Unity networking system called unet. I have a child of the local player authority, the weapon. The weapon (PlasmaCannon_left and right) have a script handling firing, because weapons can be replaced, and have different firing intervals, this seemed to me to be the easier way. However, they won't fire.

Hierarchy:

(simplified) Weapon Code:

public void Start() {
    Debug.Log("Weapon Spawned.");
    if (isLocalPlayer) {
        Debug.Log("Weapon set as local player");
    }
}

public void Update() {
    if (isLocalPlayer) {
        if (firingTimer <= firingInterval){
            firingTimer += Time.deltaTime;
        }
        if (firingTimer >= firingInterval) {
            if (Input.GetButton("Fire1") && firingMode == FiringMode.Primary) {
                CmdFire();
            }
            if (Input.GetButton("Fire2") && firingMode == FiringMode.Secondary) {
                CmdFire();
            }
        }
    }
}

[Command]
public void CmdFire() {
    Debug.Log("Firing Bullet.");
}

I am getting the "Weapon Spawned." log message, but nothing inside isLocalPlayer conditions is happening even though I have added a networkidentity component and set Local Player Authority to true.

Like I said, I'm still learning so I have no clue what's going wrong here.


texts: Pausing animation and resuming on same frame

texts:
How do you stop an animation and then resume on the same frame where you paused? I tried:

if (paused) {
    anim.speed = 0;
} else {
    anim.speed = 1;
}

Sure, it pauses and plays but it doesn't resume on the frame it paused. It starts over the animation. I also tried playing around the Speed field in Animator (instead of via code) while the animation is playing and its the same way. When the animation is playing and I change the value of Speed, the animation doesn't slow down, it gets reset.


texts: Draw a 3D object at specific coordinates on the screen

texts:
I'm creating an application which allows the user to manipulate 3D models.

I would like to draw 3 axis representing the world coordinate system in 3D in order to give the user an idea where he is. These axis are represented by a 3D model. Now I want these axis to be always shown at the bottom left of the screen. I know how to draw them but not how to project them at specific coordinates on the screen.

How can i achieve this?

EDIT:

I use XNA. The axes have been created with 3DSMax, each axes is a cylinder surmounted by a cone. When I load the 3DSMax file, I get an instance of the Model class.

I've just tried to draw it normally and it appears at the center of the scene. After that, i don't know what to do to make it appears at the bottom left of the screen regardless of where the camera looks, as if that was part of the UI. 3DSMax has the same thing at the bottom left of each frame.


texts: Should I generate 2 array map or use tilemap?

texts:
So, I'm trying to build a 2d multiplayer bobmerman game. Right now I have whole map as 2d integer array. I'm thinking if I should change it to tilemap. In the future, I will want to be able to generate map from code, so keep that in mind.
Is it worth changing array to tilemap? What are the pros and cons of it? My server side is responsible for all the actions (movement, collision, placement), is it possible to connect with tilemap?


texts: How do you rotate all the objects around the camera?

texts:
If I'm correct, the way that you can "look around" in an environment is that you rotate all the objects around the camera. This is the code that I've created using JavaFX 3D. So what's the algorithm?

package com.rtek.main;

import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.PerspectiveCamera;
import javafx.scene.Scene;
import javafx.scene.paint.Color;
import javafx.scene.paint.PhongMaterial;
import javafx.scene.shape.Box;
import javafx.scene.transform.Rotate;
import javafx.stage.Stage;

public class Walk extends Application {
    private Group root = new Group();
    private PerspectiveCamera camera = new PerspectiveCamera();
    private CameraGroup cameraX = new CameraGroup();
    private CameraGroup cameraY = new CameraGroup();
    private CameraGroup cameraZ = new CameraGroup();
    private static final double CAMERA_INITIAL_DISTANCE = -450;
    private static final double CAMERA_NEAR_CLIP = 0.1;
    private static final double CAMERA_FAR_CLIP = 10000.0;

    public void start(Stage primaryStage) throws Exception {

        Scene scene = new Scene(root, 800, 600, true);

        buildScene();
        buildMouse();

        loadMouse(scene);

        primaryStage.setTitle("Walk Around");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    private void loadMouse(Scene scene) {
        scene.setOnMouseMoved(event -> {
           ???
        });
    }

    private void buildMouse() {
        root.getChildren().add(cameraX);
        cameraX.getChildren().add(cameraY);
        cameraY.getChildren().add(cameraZ);
        cameraZ.getChildren().add(camera);

        camera.setNearClip(CAMERA_NEAR_CLIP);
        camera.setFarClip(CAMERA_FAR_CLIP);
        camera.setTranslateZ(CAMERA_INITIAL_DISTANCE);
    }

    private void buildScene() {
        PhongMaterial material = new PhongMaterial();
        material.setDiffuseColor(Color.RED);
        material.setDiffuseColor(Color.GREEN);

        Box cube = new Box(100, 100, 100);
        cube.setMaterial(material);

        root.getChildren().add(cube);
    }

    private class CameraGroup extends Group {
        private Rotate x = new Rotate();
        private Rotate y = new Rotate();
        private Rotate z = new Rotate();

        public CameraGroup(){
            x.setAxis(Rotate.X_AXIS);
            y.setAxis(Rotate.Y_AXIS);
            z.setAxis(Rotate.Z_AXIS);

            getTransforms().addAll(x, y, z);
        }
    }
}


texts:
I'm rewriting my game now using software designing patterns and want to do the code, most correct I can. While implementing MVC(Model View Controller) I got a question which I would like to discuss or to hear some opinions of experts.
The question is about management of unused frames... For example next sequence of windows:
ResourceLoadingWindow -> LoginWindow -> GameWindow
Definetly that I don't want to reuse ResourceLoadingWindow , since I'm using Java Applet and I don't see any situation when I will need to reuse it. The different story is about LoginWindow, which can be reused a lot of times, because some player would want to Logout and come back again in few minutes for example. I would like to know, following the MVC structure, should I destroy window, removing it from ContentPane or just hide? Maybe I need to unregister it from controller or I shouldn't do so?

Thanks in adavance.


texts: A game community equivalent to IMDb Pro?

texts: Is there one resource that tracks and lists games in development, similar to what IMDb Pro does for films in development? MobyGames is good for post-mortem, who did what, but what about a resource that gives you intel on what games are in production?


texts: How to Detect a Right Mouse Click on a UI Button in Unity

texts:
I've been recently working on a videogame, and I'm trying to make a script that will destroy the game object it is applied to whenever the right mouse button is clicked on it. It doesn't function at all and I don't receive any error messages in the Console. Here is all my code:
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;

public class RightClick: MonoBehaviour, IPointerClickHandler
{
    // Initiates whenever the pointer is clicked
    public void OnPointerClick(PointerEventData eventData)
    {
        // Destroys item from players inventory when pressed
        if (eventData.pointerId == -2)
        {
            // Removes object from inventory
            Object.Destroy(this.gameObject);
        }
    }
}

I have searched for hours on this topic and have only found extremely outdated sources, please help me!


texts:
so just to be more specific this question isn't in regards to how to target enemies or anything like that rather its purposed towards a specific targeting issue i have with me enemies in its current state.

So the issue im having is that if i fire a bullet towards an enemy and then before that bullet hits the desired enemy it was initially set too, if my tower changes its target then suddenly my bullet does a u-turn and then targets this new enemy. Which isn't what i want.

I'm using C++. I know this is a pointer issue, that my pointer's memory address changes to point at the new enemy which the tower would be facing, the problem is i just don't know how to solve this, personally for me i don't use pointers that much and unfortunately im just not very good at using them it seems :/.
Any help on this issue is greatly appreciated, its been annoying me now for the better part of a few hours, and if anyone could explain what I'm doing wrong here as-well that would be great!
So here's my targeting code

for (int numOfEnemies = 0; numOfEnemies < lib.numberOfEnemies; numOfEnemies++)
{
    float y =  pow(enemies[numOfEnemies].position.y - position.y, 2);
    float x = pow(enemies[numOfEnemies].position.x - position.x, 2);

    if (sqrt(y + x) < range && enemies[numOfEnemies].alive)
    {
        cEnemy =  &enemies[numOfEnemies];
        acquiredTarget = true;
        break;
    }
}

Simple enough, then this is how i'm passing it in my Projectile class;

bullets.push_back(Projectile(bulletPosX, bulletPosY, 8, 8, damage, 1, speed, *cEnemy, currentUpgradeLevel));

Which specifically then uses this constructor;

Projectile::Projectile(float x, float y, int w, int h, int dmg, int type, float mxSpeed, Enemies& bulletTarget, int towerLevel)
{
     position.x = x;
     position.y = y;
     width = w;
     height = h;
     bulletAngle = 0;
     renderingAngle = 0;
     damage = dmg;
     active = true;
     ySpeed = 0;
     xSpeed = 0;
     maxSpeed = mxSpeed;
     typeOfProjectile = type;
     target = &bulletTarget;
}

There you see target is then a pointer to an enemy address, the cEnemy (currentEnemy). What my desired effect would be to have my Projectile store the enemy that I pass into it which then until it hits that enemy, the targeted enemy will forever stay focused on the enemy passed in when the projectile was first created.

Again any help greatly appreciated!

For reference

Enemies = Class Name.
enemies = vector array of active Enemies.

cEnemy = (Pointer to Enemies Object)/Enemies* cEnemy.


texts:
I am curious on how to handle collision detection involving a moving target and user input. Basing myself in the mobile space, I get events from a set framework, but I do wonder about the amount of lag involved.

Say the object moves faster and faster, then position of the input and the object is very important. What I want to know is what is the best design for handling user input and then also the best way to make sure to accurately work out when the input point collides with the object, keeping threads in mind?


texts: Spawning prefab when other prefab appears

texts:
Im trying to make a bottle spawn when it is broken.

This is the code that makes that:

public class romperobjetos : MonoBehaviour {

public GameObject BrokenBottle;
public float breakVelocity = 5f;
public GameObject NoBrokenBottle;
public bool rompible = false;
public Vector3 oldPosition;
public Quaternion oldRotation;
public bool botellarota = false;

public void Start()
{

}

// Use this for initialization
public  void Update()
{
    Debug.Log(NoBrokenBottle.GetComponent<Rigidbody>().velocity.magnitude);
    if (NoBrokenBottle.GetComponent<Rigidbody>().velocity.magnitude > breakVelocity)
    {
        rompible = true;
    }
    else
    {
        rompible = false;
    }

}
public void OnTriggerEnter(Collider other)
{
    if ((other.gameObject.name == "Plane") && (rompible))
    {
        oldPosition = NoBrokenBottle.transform.position;
        oldRotation = NoBrokenBottle.transform.rotation;
        Debug.Log("vamos bien");
        BreakBox();
    }
}
public void BreakBox()
{
    Instantiate(BrokenBottle, oldPosition, oldRotation);
    Debug.Log("se rompe");

        NoBrokenBottle.SetActive(false);
        botellarota = !botellarota;
}

}

The broken bottle prefab has a boolean variable that is true when it appears, but the unbroken bottle doesn't instantiate. This is the script for the spawn:

public class SpawnBotellas : MonoBehaviour {

public Transform[] spawnPoints;
public GameObject[] whatToSpawnPrefab;
public GameObject[] whatToSpawnClone;
public bool botella1rota = false;
// Use this for initialization
void SpawnAlgo()
{
    whatToSpawnClone[0] = Instantiate(whatToSpawnPrefab[0], spawnPoints[0].transform.position, Quaternion.Euler(0, 0, 0));
}
 void Update()
{
    //botella1
    if (GameObject.Find("alidobas blanco roto").GetComponent<alidobasrota>().alidobasblanco)
    {
        Debug.Log("asdkj");
      //  whatToSpawnClone[0] = Instantiate(whatToSpawnPrefab[0], spawnPoints[0].transform.position, Quaternion.Euler(90, 0, 0)) as GameObject;
    }

Sorry for my bad English and thanks.


texts:
I have a problem with JBullet mesh collsion. Everything works fine when I create a mesh from my object without scaling, but the problem starts when I want to scale the object. I also tried scaling in Blender, but it has the same problem. Here is my code for creating a mesh from an object:

    int numtriangles = mesh.vertices.length / 3;
    int numverts = mesh.vertices.length;

    ByteBuffer indexBuffer = BufferUtils.createByteBuffer(numverts * 3 * 4).order(ByteOrder.nativeOrder());
    indexBuffer.clear();
    for(int i=0;i<numtriangles;i++) {
       indexBuffer.putInt(i);
       indexBuffer.putInt(i);
       indexBuffer.putInt(i);
    }

    ByteBuffer geometry = BufferUtils.createByteBuffer(numtriangles * 3 * 4).order(ByteOrder.nativeOrder());
    geometry.clear();
    for(int i=0;i<numtriangles;i++) {
       geometry.putFloat(mesh.vertices[i].getPos().x);
       geometry.putFloat(mesh.vertices[i].getPos().y);
       geometry.putFloat(mesh.vertices[i].getPos().z);
    }

    geometry.rewind();
    indexBuffer.rewind();

    TriangleIndexVertexArray trimesh = new TriangleIndexVertexArray(numtriangles, indexBuffer, 3 * 4, numtriangles, geometry, 3 * 4);
    BvhTriangleMeshShape shape = new BvhTriangleMeshShape(trimesh,true);
    return shape;

My scaling was something like this:

    for(int i = 0; i < vertices.length; i++) {
        Vertex acc = vertices[i];

        Vector3 pos = acc.getPos();
        pos.x *= scale.x;
        pos.y *= scale.y;
        pos.z *= scale.z;
        acc.setPos(pos);

        Vector2 tex_coord = acc.getTexCords();
        tex_coord.x *= scale.x;
        tex_coord.y *= scale.z;
        acc.setTexCords(tex_coord);

        vertices[i] = acc;
    }

The problem is when I scale the object, it no longer collides with other objects.


texts: How to avoid minecraft-like map to blend

texts:
I am making a minecraft-like world, with some differences. For instance, the camera will be facing always in the same direction.

I am having trouble with the visuals. Here is an example:

As you can see, when looking at a "step", as long as you can see the wall between the 2 levels, kinda like looking from it upwards, it is easy to identify. But when the wall disappear, kinda like when you are looking at it downwards, the step seems to blend, to a point where it is hard to tell where the step begins.

I thought of adding outlines, but due to the heavy palette of tiles that I am going to have, it would require to re-think a lot the logic to choose the correct tile, and I was hoping to find an easier solution.

What could I do to solve this problem?


texts: Grab reference to static members or functions that has custom attribute attached

texts:
I am trying to create a custom attribute that I can attach to either variables or functions, such that I could grab all references somewhere else in code.

Example

[Attribute1]                        //custom attribute
public static int speed = 1;        //dummy variable
[Attribute1]                        //custom attribute
public static int acceleration = 1; //dummy variable
[Attribute2]                        //custom attribute
public static int count = 1;        //dummy variable

[Attribute3]
public static void DummyFunction() {...}

and from somewhere else, be able to do something along the lines of

var allAttributeReferences = GetAllAttributes("Attribute1");
allAttributeReferences[0] = 10;

var allAttributeReferences2 = GetAllAttributes("Attribute2");
foreach (var reference in allAttributeReferences2)
{
    reference = 0;
}

var allAttributeReferences3 = GetAllAttributes("Attribute3")[0];
allAttributeReferences3(); //Assume it is a function, and invoke function.

Is this even remotely possible? Could someone point me in the right direction?


texts: On 3d ripper DX and other 3d asset tools that can help boost 3d artists learning

texts: Aside from 3d ripper DX does anyone know any other 3d asset tools to help 3d artist in learning modelling and/or animations.


texts:
I have a camera that works as long as its stationary. Now I'm trying to create a child class of that camera class that will look at its target.

The new addition to the class is a method called SetTarget(). The method takes in a Vector3 target. The camera wont move but I need it to rotate to look at the target. If I just set the target, and then call CreateLookAt() (which takes in position, target, and up), when the object gets far enough away and underneath the camera, it suddenly flips right side up. So I need to transform the up vector, which currently always stays at Vector3.Up. I feel like this has something to do with taking the angle between the old direction vector and the new one (which I know can be expressed by target - position).

I feel like this is all really vague, so here's the code for my base camera class:

public class BasicCamera : Microsoft.Xna.Framework.GameComponent
    {
        public Matrix view { get; protected set; }
        public Matrix projection { get; protected set; }

        public Vector3 position { get; protected set; }
        public Vector3 direction { get; protected set; }
        public Vector3 up { get; protected set; }
        public Vector3 side
        {
            get { return Vector3.Cross(up, direction); }
            protected set { }
        }

        public BasicCamera(Game game, Vector3 position, Vector3 target, Vector3 up)
            : base(game)
        {
            this.position = position;
            this.direction = target - position;
            this.up = up;

            CreateLookAt();

            projection = Matrix.CreatePerspectiveFieldOfView(
                MathHelper.PiOver4,
                (float)Game.Window.ClientBounds.Width /
                (float)Game.Window.ClientBounds.Height,
                1, 500);
        }

        public override void Update(GameTime gameTime)
        {
            // TODO: Add your update code here
            CreateLookAt();

            base.Update(gameTime);
        }
}

And this is the code for the class that extends the above class to look at its target.

class TargetedCamera : BasicCamera
    {
        public Vector3 target { get; protected set; }

        public TargetedCamera(Game game,
            Vector3 position,
            Vector3 target,
            Vector3 up)
            : base(game, position, target, up)
        {
            this.target = target;
        }

        public void SetTarget(Vector3 target)
        {
            direction = target - position;

        }

        protected override void CreateLookAt()
        {
            view = Matrix.CreateLookAt(position, target, up);
        }
    }


texts:
I am trying to create a effect similar to what is described here How can I let players "scrape away" one texture to reveal another?
I have tried working through this but am confused and hoping someone could provide more info or if there is another way of doing it. Essentially I need to use a laser effect to "burn" or scrape paint from a door to reveal a layer below. Or any object.
I have a object which I have applied the shader to, I can then apply my "rust" and "clean" texture. When I add the splatmap the "rust" texture shows, when I run the scene.. a mouse click then does nothing.


texts: how to design transparent screen in libgdx

texts:
this question is for LibGdx geeks. I want to make transparent screen in my game. For example, when level completes I want a new transparent screen pop up and show player's high score, buttons to navigate on next level etc like in angry birds kind of screen.

This type of screen can also use, when user click on pause button, to show pause screen.
Please guide me to design this kind of screen.

Or if I am going wrong to make transparent screens for this kind of situation. Please guide me for better one.


texts:
I tried to create a climb script and found some similar code. I would like to climb with my player on a ladder. I came up with the following:

bool canClimb = false;
    float speed = 1;

GameObject player;                          // Reference to the player GameObject.

void Awake () {
    // Setting up the references.
    player = GameObject.FindGameObjectWithTag ("Player");
}

void OnTriggerEnter2D(Collider2D other) { // send in the other collider (should always work)

    if (other.gameObject.tag == "Player") { // used a tag to ID collider as player
        canClimb = true;
        player.rigidbody.useGravity = false;

    }
}

void OnTriggerExit2D(Collider2D other) { // send in the other collider (should always work)

    if(other.gameObject == "Player"){
        canClimb = false;
        other.attachedRigidbody.useGravity = true;

    }
}

void Update () {

    if(canClimb == true){

        if(Input.GetKey(KeyCode.Z)){

            player.transform.Translate (Vector3(0,1,0) * Time.deltaTime*speed);

        }
        if(Input.GetKey(KeyCode.S)){
            player.transform.Translate (Vector3(0,-1,0) * Time.deltaTime*speed);

        }
    }
}

The above code will give a red mark on the useGravity in the line of player.rigidbody.useGravity. I doesn't know how to fix this.


texts: How to adapt UV code to use a tilesheet that is "uneven"?

texts:
The tutorial has code that takes a tilesheet and builds a UV mapping:

 const float tileSize = 0.25f;

 public virtual Vector2[] FaceUVs(Direction direction)
 {
     Vector2[] UVs = new Vector2[4];
     Tile tilePos = TexturePosition(direction);

     UVs[0] = new Vector2(tileSize * tilePos.x + tileSize,
         tileSize * tilePos.y);
     UVs[1] = new Vector2(tileSize * tilePos.x + tileSize,
         tileSize * tilePos.y + tileSize);
     UVs[2] = new Vector2(tileSize * tilePos.x,
         tileSize * tilePos.y + tileSize);
     UVs[3] = new Vector2(tileSize * tilePos.x,
         tileSize * tilePos.y);

     return UVs;
 }

He explains why he uses tileSize = 0.25f:

  The variable tileSize is equal to 1 divided by the number of tiles per
  side, in the case of our example texture 1/4 (0.25). The function
  creates an array of vector2 and gets the tile position with the
  direction and populates the array based on the tile position. Every UV
  coordinate corresponds to a vertex and the triangle made of those
  vertices uses the corresponding texture coordinates.

This is the tilesheet he is using, which is a 4x4:

I have a tilesheet which is not a 4x4:

I have tried tileSize = 0.0667f (1/15 if I assume the tilesheet is 15x15), but this is not correct. For example, a grass block is (5, 14) for the side, and (5, 8) for the top. But the game renders really weird textures.

What should the tileSize be since this tilesheet is not a perfect square (it looks like 6x15 tiles, but it also has a lot of empty space which might cause problems)?

Reference:

Tutorial:
http://alexstv.com/index.php/posts/unity-voxel-block-tutorial-pt-2

Source tilesheet (CC0 license):
http://kenney.nl/assets/voxel-pack


texts:
Tibia is a 2d game, but it's sprites are drawn using certain kind of orthographic projection that is not the same I'm used to:

test http://dl.dropbox.com/u/62862049/Screenshots/97.png

I'm trying to figure out what projection is used here. I've guessed the following:

project(x,y,z) = (x-z/sqrt(2), y-z/sqrt(2))

It produces a circle very similar to that wheel, and alright cubes, but the spheres are not projected as perfect circles like the globe and the crystal ball on the picture above.

test http://o7.no/TfNmfZ
test http://o7.no/TfMZSA
test http://o7.no/TNCuCt

So which is the actual projection that game is using?


texts: How do I query a server with visible map tiles?

texts:
In my game, I need to retrieve data of items in the visible tiles based on what tiles are visible in the viewport. I am planning to make a batch AJAX request with the visible tiles, containing image tags like Google Maps. The item information will be in JSON format.

What is the best approach for this? I currently have a class that determines the visible columns/rows and offsets relative to the visible area shown.


texts: Java getResourceAsStream as local resource

texts:
Before using LWJGL, I used the Graphic method, and there I displayed imageicons, and I had the picture file located in the resources.
I used:

ImageIcon tcard = new ImageIcon(this.getClass().getResource("RCA.png"));

to load the image.

Now when I load textures in LWJGL, I have to use absolute paths to locate the file:

tcard = TextureLoader.getTexture("PNG",  ResourceLoader.getResourceAsStream("C:/RCA.png"));

I tried Googling, but I didn't find anything helpful. How can I load the image from the local resources like in the first example?


texts: Minimizing amount of comparisons for collisions?

texts:
In my 'Terraria' based game I am having lag issues. The cause of the lag is as follows:

Every update loop through all the tiles in the world:
If the rectangle that was passed as an arg intersects with the current tiles rectangle return true. If not go to the next tile.
If the rectangle that was passed as an arg doesn't intersect with any of the tiles rectangles then return false.

My solution is to only check collisions for the tiles that are on the screen.
At the moment my code renders all of the tiles regardless of the position. I know that this is a very lag-filled approach and I have no idea at all what the maths is to only get the tiles the player can see. If it helps the world is stored in a hash map that is initialised like this:

public Map<Integer, Tile> world = new HashMap<Integer, Tile>();
// numeric id = key , tile = value

I have tried looping through the tiles in 2 ways:

public boolean checkCollision(Rectangle argRect)
{
    for(int i = 0; i < world.size(); i++){
        Tile tile = world.get(i);
        Rectangle tileRect = new Rectangle(tile.rect);

        if(tileRect.intersects(argRect)){
            return true;}
    }
    return false;
}

And:

public boolean checkCollision(Rectangle argRect)
{
    for (Entry<Integer, Tile> entry : world.entrySet()) {
          Object key = entry.getKey();
          Tile tile =  world.get(key);
          Rectangle tileRect = new Rectangle(tile.rect);
          if(tileRect.intersects(argRect)){return true;}
    }
    return false;
}

Could I pass the players position to this method and have it only loop through tiles in the area? Would this approach have to loop through the tiles to see which ones are in the area?


texts: How can I calculate a vertex normal for a hard edge?

texts:
Here is a picture of a lovely polygon:

Circled is a vertex, and numbered are its adjacent faces.  I have calculated the normals of those faces as such (not yet normalized, 0-indexed):

Vertex 1 normal 0:   0.000000   0.000000    -0.250000
Vertex 1 normal 1:   0.000000   0.000000    -0.250000
Vertex 1 normal 2:  -0.250000   0.000000     0.000000
Vertex 1 normal 3:  -0.250000   0.000000     0.000000
Vertex 1 normal 4:   0.250000   0.000000     0.000000

What I'm wondering is, how can I determine, taken as given that I want this vertex to represent a hard edge, whether its normal should be the normal of 1/2 or 3/4?  My plan after I glanced at the sketch I used to put this together was "Ha!  I'll just use whichever two faces have the same normal!" and now I see that there are two sets of two faces for which this is true.

Is there a rule I can apply based on the face winding, angle of the adjacent edges, moon phase, coin flip, to consistently choose a normal direction for this box?

For the record, all of the other polygons I plan to use will have their normals dictated in Maya, but after encountering this problem, it made me really curious.


texts: How to make enemies randomly choose a path and then come back if wrong one?

texts: So I'm making a 2D Tower Defense-game in Unity with C# where the enemy has to go to the base, but can go to the wrong path randomly and then turns around when the road ends. How can I achieve this?


texts: What technique should I use to create models and animation sequences in OpenGL code?

texts:
I'm getting into game development using OpenGL (and the LWJGL library) and I want to create models for characters, NPC's etc. in the code, as well as animation sequences (for example the way the models are done in Minecraft).

What is the process to go about doing something like this? Is there a particular feature set that is used or common methods of doing this? I'm basically looking for pointers as to what to search for when trying to find examples of how this is done.


texts: glVertexAttribPointer stride GL_INVALID_VALUE opengl 3.3

texts:
I'm experiencing issues similar to described in this question, which was never answered. Basicly when I'm calling

glVertexAttribPointer

with stride greater than this exact value: 640. OpenGL GL_INVALID_VALUE error is raised. According to documentation such an arror can be raised in one case:

  GL_INVALID_VALUE is generated if stride is negative.

Which is obviously not my case.

In OpenGL 4.4 the maximum value is specified and set to GL_MAX_VERTEX_ATTRIB_STRIDE according to this site

Is there a certain magic number in older versions of OpenGL (3.3 in my case) for a maximum vertex stride? Is there any other reason that this function can raise GL_INVALID_VALUE?


texts: Need to make animation whereby the character shatters into a bunch of pieces

texts:
I would like to take a 3d character model, cut out a bunch of shapes (or a bunch of triangles in the shape of the pieces I want) and then have the pieces separate from each other at the beginning of the animation and fall apart with gravity so it looks like the model is falling apart in shattered pieces.

Is there a way to run a script on a mesh, cut out these pieces, instantiate all of them as separate models and then run gravity on them during the simulation?


texts: Make Windows game appear in Games Explorer (Start Menu - Games)

texts:
How can I make my game (right now just a C# Console Application) appear in the Start Menu under Games??

I mean is it possible for any program to register as a Game in Windows Vista / 7?


texts: Nonsense error in the overlap between 2 warriors and a tower

texts:
I have a project where 1 warrior is generated every 5 seconds. This warrior as it is generated tries to follow a path that contains 4 target points. Between the target point 1 and the target point 2 there is a tower.

Then the warrior is going to meet the target point 2, but as soon as he hits the tower, he fails to reach the target point 2 and goes to meet it until it is destroyed.

The part of the code circled in pink was to be executed only after the destruction of the tower (when the life of the tower reaches 0), which does not happen, but the worst thing is that when it executes, it does not execute completely, the tower is not destroyed, but the warrior moves toward target point 2.

Result in game:

Look that the impression occurs for the two warriors.

Maybe the message log will help:

I decrease the delay time of the loop to 0.1 and as there is no time for the second warrior to overlap the tower along with the first warrior, everything works correctly.

The problem occurs when more than one warrior reaches the tower simultaneously.


texts:
Is there any way to control what surface type is used in shader graph insted of changing it in PBR Master?
I'm creating dissolve effect for albedo/emission/transparent surfaces (https://www.youtube.com/watch?v=taMp1g1pBeE). Then I'm making 3 materials based on that one shader that I can control with variables. It works fine for Opaque but when I want to use it for glass I need to change Surface to Transparent in PBR Master and Opaque surfaces are getting bugged due to Two Sided setting.
Can I control what type of surface is used based on some variable or maybe take it out to inspector as in standard materials?


texts: How can I add intermittent voice chat to a Unity multiplayer game?

texts:
I'm looking to make a multiplayer horror game with one of the main mechanics being the game's internal voice chat.

Currently I plan on making it cut in and out so that the players (being on opposite ends of the map from each other) will lose verbal contact with each other.

I planned on using Unity. Do you know how I could go about making this work?


texts:
I'm having some issues with my optimization of my game.

I have a simple tile map looped like this in my case the images are 64 by 64 pixels:

 for (i=0; i < 50; i++){ //horizontal
    for (j=0; j < 50; j++){ // vertical

    var x = (i-j)*(img[0].height/2) + (canvas.width/2)-(img[0].width/2);
    var y = (i+j)*(img[0].height/4);

    abposx = x + offset_x;
    abposy = y + offset_y;

    total_load++;

    ctx.drawImage(img[0],abposx,abposy);
        }
    }

This as you can see is a 50 by 50 map. But i firstly want to do the following optimizations:
Work out the max that fits in canvas window (including partial) so it fills the screen.

The problem i have though by imposing the limit the loops will only load that many tiles ( lets say 10 by 10 ) so the map is always 10 by 10 and as i scroll the rest of tiles remain unloaded for obvious reasons.

So i also need to work out how to change the starting position... any ideas =/ ?


texts: How to go about an intermediate collision resolution system?

texts:
I would like to know a better way of collision resolution than I am currently doing. My current collision system stores the current positions and previous positions of each object. When an object collides with another it sets the current positions to the previous positions.

This would work fine if objects could only move in four directions, but when they can move in more than four directions the system doesn't work. For example if you are moving an object_A up and right and it collides with and object_B above it, the object_A stops moving even if still going up and right. In most 2d games however if this scenario happened the object_A would stop moving up but continue to move right. This is the kind of collision resolution that I would like to implement. I don't need anymore complicated physics right now this will do.

I'm just using rectangles so that would be the only shape I need to worry about.


texts: How do mobile games create simple UI components?

texts:
How are simple UI inputs typically handled in 2D mobile games? For example, text input boxes and keyboards.

It seems that many game engines do always have simple UI components.  There are obvious challenges in trying to show native components when your game engine has "control" of the application.

I would be interested if anyone can share their design approach.  I am most comfortable with cocos2dx and cocossharp.  However I am interested in other 2d game engines and possible work arounds for showing text input boxes and keyboards.


texts: Calculating shadowmap coordinates for cubemap in shading pass?

texts: I'm trying to implement shadow mapping with cube maps. I believe I've done the first stage by filling the cube map, but for the final shading pass I am unsure how to exactly calculate the cubemap coordinates. Any pointers?


texts: Is a warning about IAP in freemium games on iOS required?

texts:
When I launch the successful iOS game "Clash of Clans", right in the beginning I get the following message in an iOS info pop-up:

"Clash of Clans is free to play, but you can speed up your progress with in-app purchases. If desired, purchases can be disabled in the general settings of your device."

What's the reason the developer shows this message right in the beginning? Is there any legal obligation to do so?


texts: How should I store dynamic game entities for efficient area-based selection?

texts:
In my 2d block-based game I'm trying to implement a data structure that would store entities entities in a way that's capable of:

Direct selection based on coordinate.
Iteration
Iteration limited to an area

I thought of these solutions:

For 1,3 I thought that a 2 dimensional array of entities' coordinates would be suitable but I already have a 2 dimensional array of blocks' coordinates and don't want to have another one too. And this solution is not suitable with 2, there will be too many gaps when iterating the array and this is a performance loss.

The next solution I thought was simply using an array and adding new entitys simply by arr[length], this is performance wise for 2 but it is hard to perform 1 and 3 (use a for loop everytime to check if I'm colliding with an entity (duh)).

The last solution is simply adding entity data to my (already exists) blockList 2 dimensional array, this one has nearly the same pros and cons with first solution.

And there is always the alternative of using first and second solutions together by making them refer to the same object.

Which one of these solutions should I use, cause all of them have their pros and cons and I have to something uses less space, cause the game map is not fixed.


texts: Sprites: Are there any tools to scale sprites individually without using Photoshop/GIMP?

texts:
I am using TexturePacker as tool to pack my 2D sprites, it is good but it doesn't provide the possibility to scale individual sprites to a specific scale.

I am wondering whether there is any good tool or command line to scale the files in the original folder without having to use TexturePacker.

What I am trying to do is to fix some scaling errors that the illustrator that produced the files did without having to re-scale/fix things using Photoshop that is more time expensive.


texts: Strange artifacts when using gl_FragCoord to access texels

texts:
I ran into a problem with using gl_FragCoord variable to access texels. The problem can be illustrated by following example:

First I render a textured quad into texture of size (W, H) where W and H are viewport width and height correspondingly. Then I draw another quad with lower left corner in (0, 0) and upper right corner in (W, H) (so that it effectively takes whole viewport) which is textured with this texture. Let's call it quad A. Then I draw another quad (let's call it quad B) on top of it, with lower left corner in (0, H1) and upper right in (W, H) and also use the same texture for it. The whole scene can be illustrated by this picture:

As you can see, the bottom part of the first quad lays in quad A and a top part in quad B. Thus when I experiment with fragment shader for quad B I can see whether the top part of the quad matches the bottom part.

Now to the problem:

When in fragment shader for quad B I use

gl_FragColor = texture2D(u_backgroundTexture, v_texCoord);

(v_texCoord is (0, 0) for lower left corner and (1, 1) for upper right)

to determine fragment color, everything is fine. Top and bottom parts of the first quad perfectly match each other:

However, when I change this line to:

gl_FragColor = texture2D(u_backgroundTexture, gl_FragCoord.xy / u_resolution);

(where u_resolution is a vec2(W, H))

the top and bottom parts of the quad doesn't match anymore. If I render that quad close to right edge of the screen I get following artifacts:

and if I draw it close to the left side artifacts looks like this:

Could anyone please explain what are the possible causes for such artifacts? Apparently I am missing some fundamental understanding of how texturing works, since in my mind texture2D(u_backgroundTexture, v_texCoord) should be completely equivalent to texture2D(u_backgroundTexture, gl_FragCoord.xy / u_resolution); in my case.

P.S. Obviously, for quad A I always use gl_FragColor = texture2D(u_backgroundTexture, v_texCoord) in fragment shader.


texts: Move object forward according to rotation

texts: How do I make an object (like a bullet) go forward according to its rotation in vanilla nodejs (my game server language)?  For example, if an object's rotation is 0 degrees, then it goes straight up.


texts: Blue color instead of alpha using Alpha Blending

texts:
I am testing rendering with alpha blending state according to this guide.
The aim is to add snow on terrain grass texture.
Finally, I got the wrong result -- the blue color fillings up all alpha = 0 pixels.
I checked the instruction step triple time, can't find any mistakes.
Could someone explain to me what's is wrong with my code?
PS and VS:
SnowPSIn SnowVSMain(SnowVSIn Input)
{
    SnowPSIn Output;
    float fY = g_txHeightMap.SampleLevel(g_samLinear, Input.vTexCoord, 0).a * g_fHeightScale;
    float4 vWorldPos = float4(Input.vPos + float3(0.0, fY, 0.0), 1.0);
    Output.vPos = mul(vWorldPos, g_mViewProj);
    Output.vTexCoord.xy = Input.vTexCoord;
    Output.vTexCoord.z = FogValue(length(vWorldPos - g_mInvCamView[3].xyz));
    Output.vTexCoord.w = length(vWorldPos - g_mInvCamView[3].xyz);
    //Output.vShadowPos = mul(vWorldPos, g_mLightViewProj);

    return Output;
}

float4 SnowPSMain(SnowPSIn Input) : SV_Target
{
    float4 vSnowColor = g_txTerrSnow.Sample(g_samLinear, Input.vTexCoord.xy * 64);
    return vSnowColor;
}

BlendState:
BlendState SrcAlphaBlendingAdd
{
    BlendEnable[0] = TRUE;
    SrcBlend = SRC_ALPHA;
    DestBlend = INV_SRC_ALPHA;
    BlendOp = ADD;
    SrcBlendAlpha = ZERO;
    DestBlendAlpha = ZERO;
    BlendOpAlpha = ADD;
    RenderTargetWriteMask[0] = 0x0F;
};

Pass:
pass RenderShowPass
{
    SetVertexShader(CompileShader(vs_5_0, SnowVSMain()));
    SetGeometryShader(NULL);
    SetPixelShader(CompileShader(ps_4_0, SnowPSMain()));
    SetBlendState(SrcAlphaBlendingAdd, float4(0.0f, 0.0f, 0.0f, 0.0f), 0xFFFFFFFF);
}

all sources
Before:
After:


texts: How can I change a materials properties in my Unity c# code?

texts:
Hello everyone I want to change my materials tiling offset in code, but the only way I found to access it other than drag-dropping to a public field in inspector is to check by name. But I then noticed the name is suffixed with ' (Instance)' .

So it seems a little odd to me having to access it this way, is there another way that I don't know about?

foreach(Material m in GetComponent<MeshRenderer>().materials)
{
    if (m.name == "card_front (Instance)")
    {
        m.mainTextureOffset = new Vector2(value * 1/13f, (int)suit * 1/5f);
    }
}


texts:
I'm working on a website for asynchronous two-player games (mostly board games); as part of the site's development I'm hoping to use it to playtest new games I design. The good news is that this offers a much larger pool of playtesters; the bad news is that they'll be remote, so I have no easy way of gauging reactions or of directly watching them play. Obviously I can get a lot of useful information just by extracting metric data (e.g. How many moves games take, who wins more often, average margins of victory, etc.), but I'm wondering how much I can go beyond this too:

What data particularly should I be looking to extract from completed (or even in-progress) games?
What are effective means of collecting information from the participants themselves rather than just the games?  In particular, will surveying players (e.g. with email or web forms) do me any good?
What sort of essential information should I only expect to be able to garner from ‘local’ playtests?


texts: Why does my 2D top-down joystick code occasionally stop working?

texts:
I'm working on a 2D top-down game, and am working on the player controls.

I have the following code currently controlling a player sprite:

void Update () {
        float moveHorizontal = Input.GetAxis("Horizontal");
        float moveVertical = Input.GetAxis("Vertical");
        float headingAngle = Mathf.Atan2(moveHorizontal, moveVertical);
        Debug.Log("Heading angle: " + (headingAngle * Mathf.Rad2Deg).ToString() + " degrees.");
        Quaternion newHeading = Quaternion.Euler(0f, 0f, headingAngle * Mathf.Rad2Deg);

        if (transform.rotation != newHeading && (moveHorizontal != 0f || moveVertical != 0f))
        {
            Debug.Log("Turning. Rotation: " + transform.rotation + " | New Heading: " + newHeading);
            transform.rotation = Quaternion.Slerp(transform.rotation, newHeading, turnSpeed * Time.deltaTime);
        }
        else
        {
            Debug.Log("Heading in the right direction, moving...");
            transform.position += new Vector3(moveHorizontal * moveSpeed * Time.deltaTime, moveVertical * moveSpeed * Time.deltaTime, 0);
        }
    }

This code sort of works, but occasionally the player will stop moving, even though it's rotated in the direction that the joystick is pointing. When that happens, the transform.rotation quaternion will be something like '(0, 0, -7, -7)', but the newHeading quaternion will be '(0, 0, 7, 7)', like they've flipped around. When that happens, the transform.rotation != newHeading in the if condition is always true, so the else condition is never reached.

If I keep moving the joystick to different locations, eventually the player will start moving again.

By the way, I have a sprite attached as a child to a game object, and the sprite is rotated 90 degrees in the z-axis, if that makes any difference.

Any help would be appreciated!


texts: I see some articles through Google that I can use libgdx in C#. Is it true? I found no official and unonfficial about this. If there is a way, please tell me how. Thank you


texts:
I'm pretty new here (as though to a game development).
So here's my question.
I'm trying to organize a really simple game cycle in my public static main() as follows:

Scanner sc = new Scanner(System.in);
        //Running the game cycle
        boolean flag=true;
        while (flag) {
            int action;
            System.out.println("Type your action please:");
            System.out.println("0: Exit app");
            try
            {
                action = sc.nextInt();

                switch (action) {
                    case 0:
                        flag=false;
                        break;
                    case 1:

                        break;
                }
            }   catch (InputMismatchException ex) {
                    System.out.println(ex.getClass() + "\n" + "Please type a correct input\n");
                    //action = sc.nextInt();
                    continue;
             }

What's wrong with this cycle:
I want to catch an exception when user types text instead of number, show a message, warn the user, and then continue game cycle.

But instead of that, when users types wrong data, it goes into a eternal cycle without even prompting user.
What I did wrong?


texts: Programatically replace color gradient on sprite

texts:
Say I have the following image:

I want to tint the yellow parts on this sprites shoulder/arms by a random color. In other questions on this site, they suggest using a chroma key and replacing the constant color with whatever color I wanted, but that solution wouldn't keep the gradient.

The other solution I've seen is that I should cut out the part I want to change the color of and make it an overlay. That would work, but would require a lot of effort since I have many poses for this character + animations.

Any ideas?


texts: How do I implement tilt controls that work even when the device is not vertical?

texts:
I'm using libGDX to develop an Android game. The main character can be moved freely in the 2d plane by tilting the phone. The relevant part of my current implementation looks somewhat like this:

Vector2 mainCharacter;
float speedX, speedY;

public void render(float delta) {
    speedX = 0.6f * speedX + 0.4f * -Gdx.input.getAccelerometerX();
    speedY = 0.6f * speedY + 0.4f * -Gdx.input.getAccelerometerY();
    mainCharacter.move(speedX, speedY);
}

This simple implementation works quite well as long as the player sits or stands upright. But there are two situations where this approach fails:

If the player holds his phone almost horizontally (e.g. if he lies in bed, see fig. 1). Neither the computation of speedY nor the computation of speedX works properly in that situation.
Inside a moving vehicle. When the vehicle speeds up or slows down, this has a strong impact on the values returned by Gdx.input.getAccelerometerX/Y.

So my question is: Is there anything that can be done to solve these two problems? How can I get satisfying results independent of whether the player is lying, standing or sitting? And is there a reasonable way to reduce the influence that the movement of a vehicle has on the output of the accelerometer?

fig. 1


texts: Unity3D behaves differently in scene and game view

texts:
We are having AI being able to shoot. Everything works fine when having them play in Scene view, but when going into Game view the position they are shooting from is different.

Does anyone know what could cause this? That the Unity "Scene view" behaves other than "Game view"?

Hope there's anyone there to help us out, thanks in advance.


texts: Has google increased apk limit from 50mb to 149?

texts:
I recently seen Angry Birds GO has apk size of 149 on google play, https://play.google.com/store/apps/details?id=com.rovio.angrybirdsgo&hl=en

Yet google says apk size limit is 50 mb.So my question is,has google increased apk size limit from 50 mb?


texts:
I am duplicating this thread from stackoverflow, please remove it if that is not allowed.

I'm completely new in OpenGL. I have this problem: I have quite a complicated scene, and I am looking at it from the front (default camera position). The way I have seen to move the camera is using the gluLookAt() function to set the point you want to look at, and glTranslate3f() to move the camera position. I need to move the camera with different data - my data is not the point I want to look at - rather, I have the data of the projection plane - determined with a viewing vector and a point in the plane. Is there a way to set the camera using this data rather than a "look at" point?

I am using an ortographic projection (glOrtho()), so everything is projected onto the projection plane.

UPDATE: To be more precise: the point I have is a point in the plane, to which I want to project to. I have in fact not only the plane, but the square to which I need to project, defined. So I have a scene somewhere a space, and a square somewhere away from that scene. I want to project the scene to that square and show that projection on screen. I hope that made it a bit clearer what I need to achieve ... While gluLookAt defines a point in the scene at which to look at, and the position of the eye. While eye is one point in space and projection offers perspective, with ortographic projection, you do not have one point, you have a whole square on which to project to, so how can I define that?

For easier understanding what I am trying to achieve. Here is the image of what glOrtho normally does:

Here is an image of what I am trying to achieve:


texts: How to change an animated sprite's images per second from script?

texts: Consider an AnimatedSprite with an animation of 9 .png files and a setting of 5 images per second. How can I change the number of images per second from script?


texts: How can I stop the next screen from briefly displaying at the start of a CCTransitionFadeTR?

texts:
I am testing transitions in cocos2d, and am running into a problem.

I have a MainMenu screen which contains a button.  The idea is that clicking on the button will trigger a CCTransitionFadeTR transition to a WhackMain screen where there is a CCLabelTTF which displays "Hello World".

But when I press the button and start the transition, the WhackMain screen appears at full opacity for a moment before the transition from MainMenu to WhackMain begins.  The transition appears to be working correctly, apart from WhackMain being visible for a moment before the transition begins.

How can I keep this from happening?

Here is my code, if it will help identify the problem:

MainMenu.m:

#import "MainMenu.h"
#import "WhackMain.h"

@implementation MainMenu

+(CCScene *) scene1 {
// 'scene' is an autorelease object.
CCScene *scene1 = [CCScene node];

// 'layer' is an autorelease object.
MainMenu *layer1 = [MainMenu node];

// add layer as a child to scene
[scene1 addChild: layer1];

// return the scene
return scene1;
}

-(id) init {
// always call "super" init
// Apple recommends to re-assign "self" with the "super" return value
if( (self=[super init])) {

    CGSize winSize = [[CCDirector sharedDirector] winSize];

    // Create a label for display purposes
    _label = [[CCLabelTTF labelWithString:@"Last button: None"
                               dimensions:CGSizeMake(320, 50) alignment:UITextAlignmentCenter
                                 fontName:@"Arial" fontSize:32.0] retain];
    _label.position = ccp(winSize.width/2,
                          winSize.height-(_label.contentSize.height/2));
    [self addChild:_label];

    // Standard method to create a button
    CCMenuItem *starMenuItem = [CCMenuItemImage
                                itemFromNormalImage:@"ButtonStar.png" selectedImage:@"ButtonStarSel.png"
                                target:self selector:@selector(starButtonTapped:)];

    // position the label on the center of the screen
    starMenuItem.position =  ccp( winSize.width /2 , winSize.height/2 );

    CCMenu *starMenu = [CCMenu menuWithItems:starMenuItem, nil];
    starMenu.position = CGPointZero;
    [self addChild:starMenu];
}
return self;
}

- (void)starButtonTapped:(id)sender {
  [_label setString:@"Last button: *"];
  [[CCDirector sharedDirector] replaceScene:[CCTransitionFadeTR
                                           transitionWithDuration:2 scene:[WhackMain scene2]]];
}

// on "dealloc" you need to release all your retained objects
- (void) dealloc {
[super dealloc];
}

@end

WhackMenu.m:

#import "WhackMain.h"
#import "MainMenu.h"

@implementation WhackMain

+(CCScene *) scene2 {
// 'scene' is an autorelease object.
CCScene *scene2 = [CCScene node];

// 'layer' is an autorelease object.
WhackMain *layer2 = [WhackMain node];

// add layer as a child to scene
[scene2 addChild: layer2];

// return the scene
return scene2;
}

-(id) init {
// always call "super" init
// Apple recommends to re-assign "self" with the "super" return value
if( (self=[super init])) {

    // create and initialize a Label
    CCLabelTTF *label = [CCLabelTTF labelWithString:@"Hello World" fontName:@"Marker Felt" fontSize:64];

    // ask director the the window size
    CGSize size = [[CCDirector sharedDirector] winSize];

    // position the label on the center of the screen
    label.position =  ccp( size.width /2 , size.height/2 );

    // add the label as a child to this Layer
    [self addChild: label];
}
return self;
}

// on "dealloc" you need to release all your retained objects
- (void) dealloc {
[super dealloc];
 }

@end


texts: Do I really need a render() method in the game loop if the view subscribes to the models?

texts:
For a game that I'm working on, we've followed the MVC paradigm. However, in classic MVC, the view subscribes to the model and when the model updates it informs the view. We've implemented this as an Observer pattern so the model doesn't really have a direct link to the view, to reduce coupling.

Now, given such a configuration, is the call to render in the game loop really necessary?

That is,

while(true){
 update(); //mostly called via user interaction
 render(); //necessary if called by model?
}

The game loop is more like:

while (game_is_running){
 getUserInput();//This updates models which in turn asks views to render the changes.
}

Is there really an advantage to having render in the game loop? Is it acceptable to have the models inform the view to render themselves? What's the preferred way to go about this?


texts: Unity - Align 2 gameObjects by their center point

texts:
I'm trying to align 2 game objects using their respective center points at runtime in Unity. The goal is to center my new generated object (SKY) to my map (terrain) which represents the center of my scene. What I already achieved is:

create my game object (terrain)
create 2 float values xCubes and zCubes based on the terrain bounds
create a new Game Object (SKY)
spawning a prefab on each xCubes and zCubes to create the ceiling

Now I need to center SKY on my terrain gameobject with bounds.min.x but the new object results aligned by its origin point, not by its center. SKY has to be aligned by x and z values but not on the Y, for which i need to specify my own value (that's why i cannot use simply bounds.center.
    private void GenerateCeiling(int xMax, int zMax)
{
    GameObject landscape = new GameObject("SKY");

    for (int z = 0; z < zMax; z++)
    {
        for (int x = 0; x < xMax; x++)
        {
            var newCeiling = Instantiate(skyTile, new Vector3(x * 10, 0, z * 10), Quaternion.Euler(0, 0, 0));
            newCeiling.transform.parent = landscape.transform;
        }
    }

    landscape.AddComponent<Renderer>();
    Renderer SkyRenderer = landscape.AddComponent<Renderer>();
    var skyCenter = SkyRenderer.bounds.center;
    //landscape.transform.position = new Vector3(terrain.bounds.min.x, 50, terrain.bounds.min.z);
    skyCenter = new Vector3(terrain.bounds.min.x, 50, terrain.bounds.min.z);

    Debug.Log(terrain.bounds.size.x.ToString());
    Debug.Log(terrain.bounds.size.z.ToString());

}

i tried to deal with different renderer.bounds min, max, center, extents etc. and to create new Rendere component on the SKY game Object but it doesn't work.
Anyone can help please?


texts:
I would like to build a body with Farseer out of two rectangles so it looks like this:

I am a real beginner, so please describe it carefully.

Thanks in advance!


texts:
I have a script that randomly chooses a position to move a game object every 5 seconds, however instead of moving my object smoothly, my script make my object jumps, which is not desirable! How would I make my object move to position smoothly! Thank you!

public float timer;
public float speed;

public int newtarget;

public float xPos;
public Vector3 desiredPos;

void Start() {
}

void Update () {
    timer += Time.deltaTime;
    if (timer >= newtarget) {
        newTarget ();
        timer = 0;
    }
}

void newTarget() {
    xPos = Random.Range(-4.5f, 4.5f);
    desiredPos = new Vector3(xPos, transform.position.y, transform.position.z);

    transform.position = Vector3.Lerp (transform.position, desiredPos, Time.deltaTime * speed);
        if (Vector3.Distance(transform.position, desiredPos) <= 0.01f)
        {
            xPos = Random.Range(-4.5f, 4.5f);
            desiredPos = new Vector3(xPos, transform.position.y, transform.position.z);
        }
}