texts: My Raycast will not detect collisions in my Unity 2D project. What am I doing wrong?

texts:
I appreciate any help you can offer me. I created a script for a character controller that casts two rays below the player's gameobject. The rays extend infinitely and should collide with another gameobject called terrain. The player is directly above the terrain, so the Raycast must return information about that collider (terrain has a BoxCollider2D). The code I'm using is below. Thank you so much for your time and your help.

Why won't my Raycast hit the BoxCollider2D that is directly in front of it?

 public int distanceFromCenter; // set to 1 in inspector
 private float rayDistance = Mathf.Infinity;

 void Update () {
     Vector3 transformUp = transform.up;
     Vector3 transformRight = transform.right;
     RaycastHit leftRayHitInfo;
     RaycastHit rightRayHitInfo;

     Vector3 leftRayOrigin = transform.position + distanceFromCenter * transformRight;
     Vector3 rightRayOrigin = transform.position - distanceFromCenter * transformRight;
     Ray leftRay = new Ray(leftRayOrigin,-transformUp);
     Ray rightRay = new Ray(rightRayOrigin,-transformUp);
     Debug.DrawRay (leftRayOrigin,-transformUp*5000,Color.white); // for visualization
     Debug.DrawRay (rightRayOrigin,-transformUp*5000,Color.white); // for visualization

     bool castLeftRay = Physics.Raycast (leftRay, out leftRayHitInfo, rayDistance);
     bool castRightRay = Physics.Raycast (rightRay, out rightRayHitInfo, rayDistance);
     if (castLeftRay) {
         Debug.Log ("leftray true");
     } else {
         Debug.Log ("leftray false"); // the console always prints this
     }
 }


texts: Unity3D - GameObject as a static function

texts:
Newbie Unity3D/C# developer here.
I've tried learning Unity3D during my May/June college vacation and came across a problem:Code 1:

CameraObj returnVoid;

void Start ()
{
    returnVoid = GameObject.Find ("Main Camera").GetComponent<CameraObj> ();
    returnVoid.ComponentType ();
}

Code 2:

GameObject returnDirectLight;

void Start ()
{
    returnDirectLight = GameObject.Find ("Directional Light");
    Debug.Log (returnDirectLight.GetComponent<DRLight>().directionString);
}

CameraObj is my custom component.
As far as I know, GetComponent is actually a public method. I understand the logic behind Code 2. What I fail to understand is Code 1. How does GetComponent become a static function here? Does it become abstract in my CameraObj class?


texts: Not able to connect to Photon(PUN).photon unity networking error

texts:
I'm new to photon Networking. My game was working great suddenly this is appearing

Cannot send messages when not connected. Either connect to Photon OR use offline mode! UnityEngine.Debug:LogError(Object)


texts: Outline shader in SFML/GLSL does not work

texts:
I have a problem with SFML. This code does not work:

uniform sampler2D texture;

varying vec2 v_texCoords;

float offset = 1.0/32;

void main()
{
v_texCoords = gl_TexCoord[0].xy
  vec4 col = texture2D(texture, v_texCoords);

  if (col.a == 1)
    gl_FragColor = col;
  else {
    float au = texture2D(texture, vec2(v_texCoords.x , v_texCoords.y -offset )).a;
    float ad = texture2D(texture, vec2(v_texCoords.x , v_texCoords.y + offset)).a;
    float al = texture2D(texture, vec2(v_texCoords.x -offset, v_texCoords.y)).a;
    float ar = texture2D(texture, vec2(v_texCoords.x + offset, v_texCoords.y)).a;

    if (au.a != 1 || ad.a != 1 || al.a != 1 || ar.a != 1)
      gl_FragColor = vec4(0.0, 0.0, 0.0, 1);
    else
      gl_FragColor = col;
  }
}

How can I make my outline shader work in SFML?


texts: How can I move an object towards another along a straight line

texts:
How can I move an object (like a cube) towards another object?

Let's say that we have a red cube in the center of a floor, and a blue cube in another location, there aren't objects between this two, so the movement is along a line.

How can I move the blue cube towards the red one?


texts: Determining value to add / subtract scaling

texts:
I have a menu panel.
It appears if the user presses the Enter key, and it disappears if he presses the Enter key again.

When the menu is still hidden, its X scale is set to 0.
In its normal / expanded state is 0.00175f.
When the menu is shown or hidden, I want to smoothly scale from 0 to 0.00175f or from 0.00175f to 0.

To do that, I have written a coroutine:

private IEnumerator pShrinkExpandMenu(bool uShrink)
{
    if (!uShrink)
    {
        Menu.SetActive(true);//the menu should be expanded / enlarged, so we need to make sure it's visible
    }

    float fWidthIfExpanded = 0.00175f;
    float TimeInSecondsToSwitch = 0.3f;

    _TimeElapsedOnShrinkingExpanding += Time.deltaTime;

    while (_TimeElapsedOnShrinkingExpanding < TimeInSecondsToSwitch)
    {
        float fValue;

        if (uShrink)
        {
            fValue = ...
        }
        else
        {
            fValue = ...
        }

        Menu.localScale.X = fValue;

        yield return 0;
    }
    if (uShrink)//if we shrink, and it's completely shrunken, hide it
    {
        Menu.SetActive(false);
    }
}

I hope that my coroutine is fine.
One thing that I just don't know is how to determine the value that the X scaling should be changed during one loop.

I have no idea how to calculate fValue.

Could anybody explain that to me, please?


texts: Calculate point of circle–circle collision between frames

texts:
I need to find the exact XY coordinate where a circle collides with another circle calculated between frames. This means that I take the coordinate of the moving circle on the previous frame and take its coordinate on the current frame. Then I need to find the position where the circle collides some time along this line segment.

In the diagram below, the blue circle moves from the previous frame (upper) to the current frame (intersecting, lower). During this time it would have hit where the dashed circle is. I need to find the coordinate of the green point.

Also note that it may be possible for the blue circle to entirely pass through the red circle. There would then be two points, so the first must be used.


texts:
I have an array in my vertex shader like this:

uniform mat4 MeshTransforms[20];

At the moment I'm just updating the entire array of matrices like so:

int meshTransforms = ARBShaderObjects.glGetUniformLocationARB(shader, "MeshTransforms");
ARBShaderObjects.glUniformMatrix4ARB(meshTransforms, false, UnitTransformMatrices);

Where UnitTransformMatrices is a float buffer containing the transform matrices of some units.

I'd like to just update a single matrix in the array (just update one unit transform matrix). So how can I overwrite a single matrix in the middle of the matrix array?

This is using the LWJGL, so I'm limited to the functionality it provides.


texts:
I have to make a simple "avalanche" game to show I know how to use the physics and creating terrain. But I actually wanted to go a little above and beyond and actually give the player health so there is a actual purpose to dodging the sphere objects. I found a very useful guide on how to set up player health, the only thing is I don't know how to set up the player taking damage when he collides with a sphere. Here is the code I have for the players health

#pragma strict

public var health : float = 100f;                           // How much health the player has left.
public var resetAfterDeathTime : float = 5f;                // How much time from the player dying to the level reseting.
public var deathClip : AudioClip;                           // The sound effect of the player dying.

private var anim : Animator;                                // Reference to the animator component.
private var playerMovement : PlayerMovement;            // Reference to the player movement script.
private var hash : HashIDs;                             // Reference to the HashIDs.
private var sceneFadeInOut : SceneFadeInOut;            // Reference to the SceneFadeInOut script.
private var lastPlayerSighting : LastPlayerSighting;    // Reference to the LastPlayerSighting script.
private var timer : float;                                  // A timer for counting to the reset of the level once the player is dead.
private var playerDead : boolean;                           // A bool to show if the player is dead or not.

function Awake ()
{
    // Setting up the references.
    anim = GetComponent(Animator);
    playerMovement = GetComponent(PlayerMovement);
    hash = GameObject.FindGameObjectWithTag(Tags.gameController).GetComponent(HashIDs);
    sceneFadeInOut = GameObject.FindGameObjectWithTag(Tags.fader).GetComponent(SceneFadeInOut);
    lastPlayerSighting = GameObject.FindGameObjectWithTag(Tags.gameController).GetComponent(LastPlayerSighting);
}

function Update ()
{
    // If health is less than or equal to 0...
    if(health <= 0f)
    {
        // ... and if the player is not yet dead...
        if(!playerDead)
            // ... call the PlayerDying function.
            PlayerDying();
        else
        {
            // Otherwise, if the player is dead, call the PlayerDead and LevelReset functions.
            PlayerDead();
            LevelReset();
        }
    }
}

function PlayerDying ()
{
    // The player is now dead.
    playerDead = true;

    // Set the animator's dead parameter to true also.
    anim.SetBool(hash.deadBool, playerDead);

    // Play the dying sound effect at the player's location.
    AudioSource.PlayClipAtPoint(deathClip, transform.position);
}

function PlayerDead ()
{
    // If the player is in the dying state then reset the dead parameter.
    if(anim.GetCurrentAnimatorStateInfo(0).nameHash == hash.dyingState)
        anim.SetBool(hash.deadBool, false);

    // Disable the movement.
    anim.SetFloat(hash.speedFloat, 0f);
    playerMovement.enabled = false;

    // Reset the player sighting to turn off the alarms.
    lastPlayerSighting.position = lastPlayerSighting.resetPosition;

    // Stop the footsteps playing.
    audio.Stop();
}

function LevelReset ()
{
    // Increment the timer.
    timer += Time.deltaTime;

    //If the timer is greater than or equal to the time before the level resets...
    if(timer >= resetAfterDeathTime)
        // ... reset the level.
        sceneFadeInOut.EndScene();
}

public function TakeDamage (amount : float)
{
    // Decrement the player's health by amount.
    health -= amount;
}

Thanks for the help guys, and helping me to learn unity.


texts: When the scene is loaded again start function is not getting called from the script in which I have applied singleton pattern

texts:
In Game scene I have an empty GameObject Circles to which a script named Circles is attached.
The script is:
public class Circles : MonoBehaviour
{
    public Text text;
    LevelManager levelManager;
   public int score=0;
    int enemyNo;
  private void Awake()
    {
        int scorer = FindObjectsOfType<Circles>().Length;
        if (scorer > 1)
        {
            gameObject.SetActive(false);
            Destroy(gameObject);
        }
        else
        {
            DontDestroyOnLoad(gameObject);
        }

    }
 void Start()
    {

        print("start");
        enemyNo = Random.Range(0, 4);
        Invoke("instantiator", 1.5f);

        text.text = score.ToString();
        levelManager = FindObjectOfType<LevelManager>();

    }
}

When the player loses he goes to GameOver scene where his score is displayed.
When the player presses play again button then he comes to Game scene again and the start function is not getting called.
When the player presses the play again button I want to destroy previously existing Circles GameObject and not the GameObject Circles which is present in the scene so that score is set to zero and the start function get called.
How to fix this issue?


texts:
I'm writing a rendering engine in OpenGL.

I Want to do order independent transparency.

I had heard somewhere that some GPUs have support for actually sorting the fragments of all the objects in the scene based on depth and then drawing them.

I then realized that this feature is likely very important to many people.

Does OpenGL have a built-in fragment sorting algorithm, or access to this hardware?


texts: How is a splash screen that is disposed upon user input meant to be implemented?

texts:
I'm going through Gustavo Steigert's tutorials on libgdx, but I have a feeling that this is more of a design question, rather than specifically regarding libgdx. My question is regarding the splash screen. I can implement what he has in that tutorial without any errors, but I want to add a little extra. In every game I've ever played, the splash screen goes away when the user left-clicks or presses esc, so I'm trying to add that (strangely, I can't find any tutorials with splashes like that). So, I have this method in my SplashScreen class:

public boolean handleInput() {
    if (Gdx.input.justTouched()) {
        game.setScreen(new MenuScreen(game));
        return true;
    } else {
        return false;
    }
}

At first, I tried to make that method return void and simply call splash.handleInput() in the render() method of the main Game class, Tyrian. However, that doesn't work, because once the splash screen has been moved on from, handleInput() will still be called on every render(), and the game crashes if the user clicks a menu button. So, I made handleInput() return a boolean and used this code in render():

if (onSplash) {
    if (splash.handleInput()) {
        onSplash = false;
    }
}

onSplash is a boolean inside the Tyrian class that is true by default.

Something else odd: when using the void version of handleInput(), the game will only crash if a button on the menu (the menu screen is the next screen) is pressed., and not if the screen is pressed. I am worried that the splash screen is never being disposed of (though my current solution does not seem to show that), because I can see from logging messages being printed to the console that the menu screen is being created upon every screen click, which is what handleInput() does. Also, if I put an else to that code above, with splash.dispose(); as a result, the game will crash.

This is such a common action in games, I would be surprised if there was not a common and cleaner accepted way of implementing it that I have missed.

EDIT: I have changed the handleInput() back to void and have used the instanceof keyword in my main game file. It's a cleaner solution, but I'm not sure if it's the best (it's an extra check on every render!).

SplashScreen.java

public void handleInput() {
    if (Gdx.input.justTouched()  ||  Gdx.input.isKeyPressed(Input.Keys.ESCAPE)) {
        game.setScreen(new MenuScreen(game));
    }
}

Tyrian.java

if (this.getScreen() instanceof SplashScreen) {
    splash.handleInput();
}


texts: Best way to detect if vec3 is between vec3(x) and vec3(y) in glsl

texts:
As titled

I am sampling from a texture and if the color is somehow gray [vec3(.8), vec3(.9)] and an uniform is 1 I need to substitute that color with another one

I am not a glsl veteran but I am pretty sure there is a more elegant and compact (without mentioning faster) way than this:

vec3 textureColor = texture(texture0, oUV);

if(settings.w == 1 && textureColor.r > .8 && textureColor.r < .9
                    && textureColor.g > .8 && textureColor.g < .9
                    && textureColor.b > .8 && textureColor.b < .9)


texts: How do I fix this weird lighting problem?

texts:
I'm making a small game in Unity, and some models are displaying very ugly shading.  The shading usually looks funky along the edges between triangles.  I'm pretty new to working in 3D; I bet this is an artifact of vertex lighting, but I'm not sure, and I'm not sure how to fix it.

Here you can see the worst example of this problem:

Low-quality lightmapping is visible in that shot, but I'm asking about the visible bands and weird shapes visible on the surface of the orange mesh in the foreground.  The mesh was built and UV-mapped in Blender, and is using a standard bumped diffuse shader.  There is a light behind and above the camera; all other lights in the scene are pretty far away.  What am I doing wrong, and how can I do better?

EDIT: Below is the wireframe for this model in Blender.


texts:
I created some MenuItemfunctions for navigating, which are currently displayed on the menu toolbar. The C# code:

using UnityEditor;
using UnityEngine;

public class Menu : MonoBehaviour {

static void rotateView(Quaternion rotation) {
    SceneView.lastActiveSceneView.LookAt(SceneView.lastActiveSceneView.pivot, rotation);

    SceneView.lastActiveSceneView.Repaint();
}

[MenuItem("View/Front _1")] // FRONT
static void FrontView() {
    rotateView(Quaternion.Euler(0, 180, 0));
}

[MenuItem("View/Back &1")] // BACK
static void BackView() {
    rotateView(Quaternion.Euler(0, 0, 0));
}

// Few more similar functions

}

I came from Blender, where there are shortcuts opening a context menu on the cursor position like this one, opened after pressing U:

What I want to do is displaying a context menu after pressing P which would display a list of implemented MenuItems.
Is something like this possible in Unity?


texts: Query regarding a quad tree implementation for spherical terrain

texts:
I am having some difficulty conceptualising how a quadtree would be used to implement a spherical terrain system.

I currently have a spherical terrain system working, without any form of optimisation, I just have a vertex buffer full of every vertex in the terrain. Obviously, this can only be rendered at very low resolutions without lagging.

I intend to use a Chunked Level of Detail system to speed things up, however, despite my research, I am still somewhat unsure as to how to proceed.

From what I understand:
I need to generate several levels of detail (by essentially creating several distinct terrain files, each with a lower resolution than the last).

I then load the quad tree with the data by setting each level of the quad tree to be a "level of detail", so level 1 would be the root node, encompassing everything, level 2 would contain very low resolution terrain data (in the form of a low-resolution list of terrain vertices), and so on until level n, where the highest resolution data would be stored (in the form of a high resolution list of terrain vertices).

This is the part I have the most trouble with, is this correct? Generating several terrain files at different resolutions, and loading each one to a separate level of the quad tree?
Or should the tree be populated with vertices in a different way?

I then populate the main vertex buffer by searching the quadtree's nodes, and I use the players position to decide which nodes to return. So, the nodes far away from the player will be all high level (level 1) nodes with low detail, and as the distance to the player gets closer, the search will drill deeper and deeper into the quad tree, so eventually the nodes returned will be the highest detail level possible.

Is this in any way correct? My thinking on this is still quite hazy, even though I have done extensive research.

Thanks for any help or advice!


texts: Smart terrain generation to avoid unconnected tiles

texts:
To make this clear from the get go;

I'm not looking for HOW To randomly generate a terrain (I know I can use Perlins noise for that).

I'm looking for an algorithm that can help with the terrain generation.

Example;

Me and my friend are working on a flash game to be use as advertisement for an upcoming game (And to see if theres actually interest for the base game).

And I've been working on randomly making terrains, however!
When i generate the map, i have no idea how to make it so it connects properly.

The map is isometric and tilebased and after its been generated we're going to litter chest/traps and other gameplay elements on the map. However, theres no reason to put an item on a piece of that map thats not connected to the rest of the map.. Or worse yet, spawn a player on a tile thats unconnected to anything.

Does anyone know of a algorithm that helps with stuff like this?

Thanks in advance people.

~Etarnalazure

EDIT

What I'm looking for is an algorithm that makes sure theres no unconnected tiles,
thus no items or players may by accident get seperated from the rest of the walk-able tiles.

Hopefully this clears up what i mean.


texts:
I am drawing a rectangle using a emptytexture (1x1) and I use the following:
spriteBatch.Draw(EmptyTexture, new Rectangle((int)MyPosition.X + MyTexture.Width / 2, (int)MyPosition.Y + MyTexture.Height / 2, 100, 2000), null, Color.Red, MyDirection + MathHelper.ToRadians(180), new Vector2(0, 0), SpriteEffects.None, 0.0f);

which does this:

But now I am trying to make another rectangle next to that one which looks like this:

But when you rotate the ship it rotates like this:

I've done this by the following:
spriteBatch.Draw(EmptyTexture, new Rectangle((int)(MyPosition.X + MyTexture.Width / 2) + 100, (int)MyPosition.Y + MyTexture.Height / 2, 100, 2000), null, Color.DarkRed, MyDirection + MathHelper.ToRadians(180), new Vector2(0, 0), SpriteEffects.None, 0.0f);

But what I am trying to do is to make the point of rotation of the 2nd one at the middle of the ship like the other one but it's drawn the same.


texts: How to rotate an object around world aligned axes?

texts:
I have a Vector3 which has an euler angle for each axis.

Usually, when I want to create a rotation matrix I will use functions such as D3DXMatrixRotationX passing the respective angle from my rotation vector above and multiply the matrices (ZXY) to create the overall rotation matrix which is used to form the complete object transformation matrix.

However, this method will produce a set of rotations in object space. That is, passing a vector of (90, 0, 90) into my method will create a rotation in world space effectively of (90, 90, 0).

Is there a way to always ensure each component of my rotation vector results in a rotation around the respective world space aligned axes?

EDIT:

This is an animation of what is currently happening - I want a way to rotate around the blue axes, not the red.

EDIT 2:

Just to note I am not looking for a solution involving Euler angles, but simply a way in which I can represent a transformation of multiple rotations around the world axes.


texts: An odd performance problem rendering a simple scene (less than 14k vertices) in OpenGL using two vbos with LWJGL

texts:
Problem

I have been having a strange degrading performance issue rendering a simple scene containing two "chunks" of 4x4x4 cubes each.

Video of problem

This is a screen capture showing my console output, look specifically at the FPS dropping (which is the issue).

http://assets.cognitive.io/bugconsole.swf

Details about problem

My machine (a mid-2009 mbp 15") is on average using something like 10% cpu, but the machine is getting very hot to touch so I believe the graphics card is working very hard.

Someone else tested this code on another machine and experienced 100% cpu usage on a quad-core AMD cpu (on one core) and the same kind of performance problem.

I can't quite figure out what's going on, multiple people have looked at this and we are not getting any smarter.

Currently there is no frustum culling or any other sort of culling. I do not think that is the problem, I should be able to render a much much higher number of vertices without experiencing problems.

I have a list of chunks (ArrayList) that is created on start, not within the render loop, that generates a vbo and all that.

In my renderer I loop through the list of chunks and for each one I bind the vbo, setup some uniform variables and such before calling glDrawArrays().

I have a version of this where I only have one vbo (but then also only one cube per vbo/glDrawArrays call, very inefficient) where everything is working fine.

Thoughts and ideas

I believe the problem is something related to either VRAM filling up or me doing something incredibly wrong.

I've tried looking at my project with OSX's OpenGL profiler application, which has given me two different results:

First I was just using glBufferData each frame to pass the data, which resulted in 90% of the gl time spent being spent on CGLFlushDrawable().

After some advice from someone on #opengl on Freenode, it was suggested I should setup the vbo once with glBufferData, and then call glMapBuffer to pass the data after that.

This results in the same performance problem but 99% of the gl time being spent on glMapBuffer().

I was hoping someone had some advice for me, I would really like to just be able to continue learning opengl instead of being stuck debugging this performance issue for weeks.

Code on GitHub

The code is available at https://github.com/flexd/Game/tree/chunkrenderer (specifically the chunkrenderer branch!, you can see that the lighting2 branch works without the same performance issue).

The main game class is Game.java which contains the main method and it's also where I setup OpenGL.

Chunk.java, Cube.java, Renderable.java and ChunkRenderer.java are also of interest. Shader.java is where the shader class lives, but I doubt that has anything to do with the issues, it's basically the same shader as before.

Thanks in advance, I hope to be able to find the issue soon :)

Looking forward to being able to learn more of this.

PS: Let me know if I am posting this in the wrong place, I don't know if there's a opengl category that's better suited for this.


texts:
In my game I have to integrate Facebook login. I searched about custom modules and all.

I found one but it not working in ios and its for older version.

Any help would be appreciated


texts: Manipulating vertices after multiplication with MVP matrix (OpenGL)

texts:
I'm making a collage of lots 16x16 renders on a 512x512 texture, of the same scene, from various viewing positions and angles, preferably lots of times per second. I've profiled my program (which contained a glDrawElements call per mesh), and the multiple glDrawElements calls seemed to slow it down a lot. In order to optimize, I've resorted to instanced rendering. However, the main problem I'm having is changing the viewport between, say, every 3 instance renderings, or so. I was thinking of adding a fourth matrix, which would scale the perspectively-projected vertices of a would-be 16x16 picture, translate them so that the little images don't overlap, and based on the little picture's position and size (16x16 pixels) on screen, use the `discard' command in the pixel shader.

How do I scale the projected vertices from the current large viewport into a 16x16 smaller version of it and translate them inside the former at a certain position?

Or, more clearly, how do I change the viewport during a glDrawElementsInstanced call, every N instances?

EDIT
Here's a visualization of what I'm trying to achieve:

Keep in mind, I can't change the viewport as I want to do this during a call to glDrawEleemntsInstanced, every 3 instances, or so.

How do I compute a matrix or what do I have to do to get the post-projection vertices scaled and translated so that I'll have the full image scaled in a 16x16 portion of the screen?


texts:
When I set a position3D for a Sprite in cocos2dx, it render two times the same sprite, i took a screenshot:

I set the position3D because i want to use the Z position the give an effect of distance, but its rendering these two sprites in the lower left corner, how can I fix that?

Here is my code in .h:

cocos2d::Sprite* mySprite;
cocos2d::Sprite* mySprite2;
cocos2d::Camera* camera;

Here i my code in cpp:

bool HelloWorld::init()
{

if ( !Layer::init() )
{
    return false;
}

auto s = Director::getInstance()->getWinSize();
camera = Camera::createPerspective(60, (GLfloat)s.width / s.height, 1, 100);

camera->setRotation3D(Vec3(0, 0, 0));

this->addChild(camera);
mySprite2 = Sprite::create("idle1.png");
mySprite2->setPosition3D(Vec3(5, 0, -41));
mySprite2->getTexture()->setAliasTexParameters();

this->addChild(mySprite2, 2);

mySprite = Sprite::create("idle1.png");
mySprite->setPosition3D(Vec3(-5, 0, -81));
mySprite->getTexture()->setAliasTexParameters();

this->addChild(mySprite, 0);
}


texts: Unity Profiler - How do I correct Audio (WASAPI) Feeder issues?

texts:
I've got the following data after running the Unity Profiler:

If I'm reading this correctly, the thing that's driving me down to ~1 FPS is the CPU Audio. I can't understand what's going on here, though, because there isn't any audio in my game right now.


texts: What are some common ways to generate revenue from a free game?

texts:
When creating a free game what revenue options are there and how successful are they? What are the pros and cons of different revenue models such as ad-supported, freemium, partnerships, merchandising, virtual goods, etc.?

If possible, give specific examples of games using different revenue models and provide data as evidence (otherwise it could get quite subjective).


texts: Can you help with collision detection and response in a 3D car racing game?

texts:
I am trying to implement the collision detection and response in 3D car racing game.

I have a car model, for collision I am assuming my car as a cuboid. my collision detection with walls is quite good and the response is also good. My model has a velocity, position, acceleration and orientation. I am using matrix to save the orientation and position.

My problem is collision and its response with the ground (in my case it's road). When the ground is a simple plane with a constant y-axis, then there is no need for collision detection as there is no force or movement in the y direction. But if my road is not linear, if it has some elevation, then I am having a collision detection problem when it comes to calculating its orientation.

Any help and suggestions will be of great help.


texts:
I recently saw a game which looked a bit like minecraft, but it was a RPG.
The enemies in this game consist completely of voxels and if they die, they collaps and every single voxels falls down, splattering on the floor.

That looked great and I think it could also look good in a 2D Shooter.
But I cannot think about an approach to handle such an amount of pixels.
What I want to achieve is: The enemies (and also the player) should consist of pixels, but not in a way that let them look like a pixel mess. They should have certain shapes etc.
But everything should be loose. So for example, if there is an endboss with some tentacles or big weapons, it should be possible to destroy these bit by bit. And everytime a bit is destroyed, the single, now loose pixels fly away in all directions.

How is this usually done for voxels?
Will this even be possible with pixels (I cannot see why not)?
How could be an approach to implement such an idea?


texts: How do I make a 2D race car turn smoothly?

texts:
I'm making a competitive 2-player 2D racing game for a school project. I'm struggling with the movements of my car: I made it a square for testing purposes and it can move left, right, up or down, but it can't make smooth turns around corners.

How can I make my car (currently a square) make smooth movements? I've heard vectors might help, but I don't know how to use them.

I'm writing this in C# with Visual Studio.

My car control code looks like this right now:

private void Form1_KeyDown(object sender, KeyEventArgs key) {
    // player1 controls
    if (key.KeyCode == Keys.Up)     { Player1.Top -= 5; }
    if (key.KeyCode == Keys.Down)   { Player1.Top += 5; }

    if (key.KeyCode == Keys.Left)   { Player1.Left -= 5; }
    if (key.KeyCode == Keys.Right)  { Player1.Left += 5; }

    // player2 controls
    if (key.KeyCode == Keys.W) { Player2.Top -= 5; }
    if (key.KeyCode == Keys.S) { Player2.Top += 5; }

    if (key.KeyCode == Keys.A) { Player2.Left -= 5; }
    if (key.KeyCode == Keys.D) { Player2.Left += 5; }
}


texts: Android: Loading bitmaps without premultiplied alpha (OpenGL ES 2.0)

texts:
Is this possible? To load textures in non-premultiplied format (Straight alpha?)?

My game has 1 or 2 images which have semi-transparent pixels and I need to be able to fade them in and out but this doesn't seem possible easily.

As far as I understand Android always loads graphics in premultiplied alpha format, but if this is the case, how to blend them correctly?

Any help would be appreciated.

EDIT  I have included some code:

String strFShader =
"precision mediump float;" +
"varying vec2 v_texCoords;" +
"uniform sampler2D u_baseMap;" +
"void main()" +
"{" +
"gl_FragColor = texture2D(u_baseMap, v_texCoords);" +
"gl_FragColor.a *= "+opVal+";"+    //where opVal is a value from 0.0f to 1.0f
"}";

And then......

//Enable Alpha blending and set blending function

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

//Draw it
GLES20.glDrawArrays(GLES20.GL_TRIANGLE_STRIP, 0, 4);

//Disable Alpha blending
GLES20.glDisable(GLES20.GL_BLEND);

Using this, the semi-transparent parts of the image will display too dark (including a dark border where anti-aliased edges should be) but will fade in and out (It's just no good though as the image isn't correct).

If I change the blending mode to:

//Enable Alpha blending and set blending function

GLES20.glBlendFunc(GLES20.GL_ONE, GLES20.GL_ONE_MINUS_SRC_ALPHA);

Then it will display perfectly at full opacity (1.0f) but becomes 'oversaturated' (This is the best way I can describe it) the more transparency you introduce (ie 0.9f down to 0.0f).

Thank you for the suggestions, as highlighted in the accepted answer in the end I didn't need to load without with "straight alpha" as I was able to correctly work with the pre-multiplied version that Android loads by default by changing the 2nd line of my Fragment shader to:

"gl_FragColor *= "+opVal+";"+


texts: How to make sprite move in any direction?

texts:
I have an arrow sprite that rotates based on where my cursor is pointed, I can only make it move up,down,left and right.How about in a diagonal way?

//this is the rotation
nt x=Gdx.input.getX();
        int y=Gdx.graphics.getHeight()-Gdx.input.getY();

        double radians= Math.atan2(y - arrowSpr.getY(), x - arrowSpr.getX());
        float angle=(float)Math.toDegrees(radians)-85;
        arrowSpr.setRotation(angle);

//then the movement
arrowSpr.translateX(speed.x);
arrowSpr.translateY(speed.y);


texts: Why does the keyboard continue to control disabled buttons?

texts: Having the whole panel with all its children including buttons disabled by simple gameObject.SetActive(false) doesn't prevent the buttons from interacting (navigation and clicks) with the keyboard. What could be the reason?


texts: Are there any open source Source engine VTX/VVD viewers?

texts:
I've been playing with loading and displaying Source Engine models (TF2, specifically) and have had mild success, but there are some aspects of it that are eluding me still. I've been primarily looking at http://developer.valvesoftware.com/wiki/MDL and online forks of the SDK headers like http://hlssmod.net/he_code/public/studio.h to understand the formats, but I've found the headers to be helpful, but lacking some crucial implementation details. The Developer Community pages do talk implementation, but much of it is speculation and I've already identified several points where it is wrong, so I'm struggling to locate some better resources.

I've got the whole .VVD file parsing now (as in: I can get the correct verts for a given LOD, verified by rendering a pointcloud.) The specific issue I'm looking at now is in the .dx90.VTX file. Drilling down into the Mesh Strip Groups, it seems like I can render the first strip group just fine (I have the Heavy's chest, arms, and legs rendering) but subsequent meshes are a mess of random triangles. It feels to me as if there should be a per-mesh offset into the .VVDs vertexes somewhere within the .VTXs structure, but I can't locate one. Maybe there's something in the .MDL, which I haven't started looking into yet, but it feels very odd to me to have such closely related data in separate files.

I know that's probably all gibberish to anyone that's not intimately familiar with the Source model formats. Really what I could use more than anything else is some reference code from another app that is loading these files. Are there any open-source exporters/viewers out there?


texts:
Off the back of this post in which I asked two questions and received one answer, which I accepted as a valid answer. I have decided to re-ask the outstanding question.

I have implemented light points with shadow casting as shown here but I would like an overall map light with no point/light source.

The map setup is a top-down 2-d 50X50 pixel grid.

How would I go about implementing a day/night cycle lighting across a map?


texts:
When trying to install Unity I am getting the following error:

  The download of version ... was cancelled.

I checked that there are no spaces in the path.

Also I can not Sign in.
When I provide the correct email and password the Sign in window just closes with no result.

Also I tried to report a bug using the Report Bug feature, but it seems not to work.

Also I tried to post a question on Unity Forum. But the Sign In over there does not work as well.

What else may I try? Thank you.


texts: AI system recommendations for a Hive mind system

texts:
Im currently starting to work on a game project where a player will be faced against an enemy which has a hive mind. I was wondering if anyone could recommend an A.I system which I could use as at the moment I am thinking about using Finite State Machines(FSM) and I think that if I use FSM's that it will get messy.

Just to clear up what will be part of the "Hive Mind" if anyone was wondering will be:

Hive Leader
Soldiers
Workers

Under each of these categories there will be roughly 2-3 different sub-categories which will have to have slightly modified FSM's dependent on their abilities.

Thanks for any response


texts: XNA - Error while rendering a texture to a 2D render target via SpriteBatch

texts:
I've got this simple code that uses SpriteBatch to draw a texture onto a RenderTarget2D:

private void drawScene(GameTime g)
{
    GraphicsDevice.Clear(skyColor);
    GraphicsDevice.SetRenderTarget(targetScene);
    drawSunAndMoon();
    effect.Fog = true;
    GraphicsDevice.SetVertexBuffer(line);
    effect.MainEffect.CurrentTechnique.Passes[0].Apply();
    GraphicsDevice.DrawPrimitives(PrimitiveType.TriangleStrip, 0, 2);
    GraphicsDevice.SetRenderTarget(null);
    SceneTexture = targetScene;
}

private void drawPostProcessing(GameTime g)
{
    effect.SceneTexture = SceneTexture;
    GraphicsDevice.SetRenderTarget(targetBloom);
    spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.Opaque, null, null, null);
    {
        if (Bloom) effect.BlurEffect.CurrentTechnique.Passes[0].Apply();
        spriteBatch.Draw(
            targetScene,
            new Rectangle(0, 0, Window.ClientBounds.Width, Window.ClientBounds.Height),
            Color.White);
    }
    spriteBatch.End();
    BloomTexture = targetBloom;
    GraphicsDevice.SetRenderTarget(null);
}

Both methods are called from my Draw(GameTime gameTime) function. First drawScene is called, then drawPostProcessing is called.

The thing is, when I run this code I get an error on the spriteBatch.Draw call:

  The render target must not be set on the device when it is used as a texture.

I already found the solution, which is to draw the actual render target (targetScene) to the texture so it doesn't create a reference to the loaded render target.

However, to my knowledge, the only way of doing this is to write:

GraphicsDevice.SetRenderTarget(outputTarget)
SpriteBatch.Draw(inputTarget, ...)
GraphicsDevice.SetRenderTarget(null)

Which encounters the same exact problem I'm having right now.

So, the question I'm asking is: how would I render inputTarget to outputTarget without reference issues?


texts: How to instantiate a sprite from a sprite sheet using script in unity?

texts:
We are creating a 2D top down rpg, and we have multiple textures, and we need to be able to change which sprite sheet its reading from in order to change the look of the walls and floor in each room. It has the same basic tiles just they need to look different. Like the corner of a cabin, to the corner of an office building.

At the moment we are taking the sprite sheet, splitting it up, and making prefabs out of it for placement by script in the game. Is there a way to do this automatically because we have a lot of textures, and its too many to make into prefabs.


texts:
I have a Unity Project and somehow the edges of objects in my Scene (Scene view and game view) look like this:

I think I already had that problem once, but in my recent projects, this didnt happen anymore.

Is there any solution to that?


texts: Is there a main UI renderer in Unity? I changed the transparency and now everything is translucent

texts:
I was trying to change the transparency of a Button object. I tried a few things like:

button.GetComponent<Renderer>().material.color = translucentColor
button.GetComponent<CanvasGroup)().alpha = 0.5f

And a few other things, I'm not sure. But the weirdest thing happened. I changed some value of something to like half alpha, and suddenly, every UI element in my game is permanently translucent! Even though I reverted that code, I can't figure out what has turned permanently translucent.

Is there some sort of god object attached to the canvas whos properties can be changed at run time and then set forever? I'm a bit new to Unity so seeing this behavior is very unnerving and weird.

I'm poking around in Unity's editor UI and I see something called the Default UI Material at white at half transparency. Could that be it?

If so, is that changeable? It's all grayed out.


texts: How to set a struct as a Direct3D9 vertex shader constant?

texts:
I have a vs_2_0 shader like this:

struct ConstantBuffer
{
    float4 diffuse;
    float4 specular
};

shared uniform ConstantBuffer g_cb : app_constantBuffer;

void PS(out float4 Color: COLOR0)
{
    Color = g_cb.diffuse;
}

The above example is simple, the constant buffer only stores two 4 component colors. I want to set the constant buffer before binding the pixel shader. I do not want to use the ID3DXEffect interface.

The IDirect3D9Device interface only provides methods for setting primitive types...I want to set the entire struct at one time. Is this possible?


texts:
In my game there is a bird flying up and a stream of containers (baskets) is moving from right to left of the screen in the bottom. Baskets are being Instantiated on right and get destroyed when they reach the left side of the screen.
 On The left there is an EmptyObject called Destroyer and anything that collides with it get destroyed. I'm not using out of bounds for the objects to get destroyed instead I'm using an EmptyObject with collide.
 And on tap the bird throws an artifact projectile downwards and if it collides with the Basket it changes into another sprite. This is the code for that transform.GetComponent<SpriteRenderer> ().sprite = changedBasket;
 The problem is that user is only allowed to miss 3 baskets losing more than 3 baskets will result in Game Over. So inside my Basket.cs I'm checking that if(target.gameObject.tag == "Deadly") then count it as a chance loose. BUT the changeBasket also act as it's the same basket.The logic that I think will work is to change the tag after the artifact collides with the basket and on that type of tagged object deadly won't work. If I'm write kindly tell me how to implement this in c# of-course. Please note that the object is an Instantiated Clone


texts:
I'm having an issue with removing objects from a sprite Group.  What is happening is I have a bullet class and every time the user presses  the player shoots a bullet.  I have 'alive = bool' code and all works great so long as only one instance of bullet is in the list.  If multiple are in the list however only the last one gets removed.  Does anyone know how I can fix this?

elif event.key == pygame.K_SPACE:
                # Fire a bullet if the user clicks the mouse button
                bullet = Bullet()
                bullet.bullet = bullet
                # Set the bullet so it is where the player is
                bullet.rect.x = player.rect.x + 9
                bullet.rect.y = player.rect.y
                # Add the bullet to the lists
                bullet_list.add(bullet)
                all_sprites_list.add(bullet)
                print(len(bullet_list))

    if bullet.alive == False:
        bullet_list.remove(bullet)
        all_sprites_list.remove(bullet)

#In the class
# If the bullet goes off the screen remove it
    if self.rect.y < 200:
        self.alive = False

I have it set to 200 at the moment for testing purposes.

Any help or a better way of doing this would be very much appreciated.  Thank you in advance.


texts: LibGDX How to adjust mouse aim angle calculation when screen is resized

texts:
I'm starting with a screen resolution of 1280 x 960 and that is the default resolution where mouse aiming is calculated thus:
angleRad = (float) (Math.atan2(screenX - (screenWidth / 2), screenY - (screenHeight / 2)));
angle = (float) Math.toDegrees(angleRad - Math.PI / 2);
angle = Math.round(angle) <= 0 ? angle += 360 : angle;
if (Math.round(angle) == 360)
    angle = 0;

Which all works fine. But when the game is resized to some resolution with a vastly different ratio to the default, like for example 2560 x 1440 at full screen in my case, the aiming is off. The resize method is like this:
@Override
public void resize(int width, int height) {
    game.getViewport().update(width, height);
    control.screenWidth = width;
    control.screenHeight = height;
}

Where control.screenWidth and control.screenHeight are used in the above angle calculation and as the set resolution in other areas. The angle calculation when resized is roughly correct but tends to get further and further off course the further the aim is away from the player.
If the player aims straight up, down, left or right (N, S, W or E basically) then the aim is dead on, but veers off as aiming goes away from the player towards a screen edge - no doubt due to the resolution ratio difference.
We have these ratio differences which no doubt affect the angle calculation:
1280x960 1.33 ratio
2560x1440 1.77 ratio

But I'm not sure how to take into account these ratios to adjust the angle calculation accordingly in my code?
The crosshair and bullets are both off position. In the screenshot below the crosshair position in comparison with the mouse pointer can be seen. This is for resolution 2560x1440. The code for the crosshair is this:
point = angleToVector((float) (angleRad + Math.PI)).scl(10000);
gs.getWorld().rayCast(callBack, pos, point);

angleRad is the mouse angle in radians, pos is the vector position of the player and point is the vector target position. This is the raycast callback
private RayCastCallback callBack = new RayCastCallback() {
    @Override
    public float reportRayFixture(Fixture fixture, Vector2 point, Vector2 normal, float fraction) {
            collision.set(point);
        return fraction;
};


texts: Sound plays several times upon collision

texts:
Upon collision, my sound effect plays several times. How can I fix this?

public Sprite charAlive, charDead;
public AudioClip popAudio;

void  OnCollisionEnter2D (Collision2D col ){

    if (col.gameObject.name == "dirtWalls") {
        gameObject.GetComponent<SpriteRenderer>().sprite = charDead;
        AudioSource.PlayClipAtPoint(popAudio, transform.position);
        StartCoroutine (Dead ());
    }
    if (col.gameObject.name == "gooWalls") {
        gameObject.GetComponent<SpriteRenderer>().sprite = charDead;
        StartCoroutine (Dead ());
    }
    if (col.gameObject.name == "grassWalls") {
        gameObject.GetComponent<SpriteRenderer>().sprite = charDead;
        StartCoroutine (Dead ());
    }
}

IEnumerator Dead() {
//      AudioSource.PlayClipAtPoint(popAudio, transform.position); // PLAYS SEVERAL TIMES
//      AudioSource.mute(popAudio);
    yield return new WaitForSeconds(3/2);
            Application.LoadLevel ("untitled");
    // LOAD LEVEL RESETS EVERYTHING, MAKE LOAD CHAR INSTEAD?
}


texts:
I've been trying to setup a development environment for Flixel on Ubuntu using this guide http://forums.flixel.org/index.php?topic=4545.0 but thus far have been unsuccessful mainly due to the guide being dated and using an outdated and inactive plugin for Eclipse (axdt).

I was wondering if anyone currently develops Flixel based games using Ubuntu/Linux, and if so how you got yourself setup. Ideally I would want to use an IDE like Eclipse but I would be open to other options.


texts: Swept 3d capsule intersection with AABB, what am I actually supposed to use to accomplish this?

texts:
I'm trying to figure out how to do continuous collision with a capsule (which would represent a collision volume for a player for example).
Given how common the capsule is in many game engines, and the fact it is merely a circle swept along a line, I would assume that even just normal collision between it any boxes, triangles/arbitrary facets would be abundant, however I'm having a hard time finding anything on capsule collision.
Some how I guess I could figure out the swept volume/object intersection (box + 4 capsule collision detection), and binary search my way down to an approximate collision, but this seems far from ideal, especially given the simple shapes involved.  I feel given the shapes I should be able to intersect directly and receive the results.  I'm not sure how to figure out "where" something intersected along a swept series with other methods (like GJK).
For my case, I'm currently focused on just AABB collisions and vertically oriented swept 3D capsules, which I hope to resolve (move capsule appropriately back with AABB collision).


texts: Android: how do I switch between game scenes in a game? Any tutorials?

texts:
I am trying to create a simple game using the Android SDK without using AndEngine (or any other game engine). I have plenty of experience designing games from the past, but I'm having lots of trouble trying to use the Android SDK to make my game. By far my biggest hurdle right now is switching between views. That is, for example, going from the menu to the first level, etc.

I am using a traditional model I learned (I think it's called a scene stack or something?) in which you push the current scene onto a stack and the game's main loop runs the top item of the stack. This model seems non-trivial to implement in the Android SDK, mostly because Android seems to be picky about which thread instantiates which view. My issue is that I want the first level to show up when you press a button on the main menu, but when I instantiate the first level (the level class extends SurfaceView and implements SurfaceHolder.Callback) I get a runtime error complaining that the thread that runs the main menu can't instantiate this class. Something about calling Looper.prepare(). I figured at this point I was probably doing things wrong.

I'm not sure how to specifically phrase my issue into a question, so maybe I should leave it as either

1) Does anybody know a good way (or the 'proper' way) to switch between scenes in an Android game?

or

2) Are there any tutorials out there which show how to create a game that doesn't take place entirely in one scene? (I have googled for a while to no avail... maybe someone else knows of one?)

Thanks!


texts: Handling actions in component based multiplayer game

texts:
Please stay with me as I explain my question.

I'm creating a multiplayer game. My design pattern follows broadly thoughts described in the post here.

The idea is that each actor whether be it a (local) player or a npc does what a GameAction attached to this actor tells it to do. These GameActions are obtained by reacting to a received GameEvent. This enables only sending GameEvents through network and each client logic will obtain own GameActions for e.g. moving local copies of remote players themselves and also getting sanity checks from time to time.

How should these actions be composed then? Who takes responsibility stopping actions?

My problem right now is that if a LocalInputHandler produces on keyDown() a CHARACTER_INPUT event it will be delivered to and consumed by a parent node the local player is living in. The parent node obtains a CHARACTER_MOVE GameAction and attaches it to the specific local player. On update() the player/character excecutes the GameAction. It moves, by itself. Like a small script interpreter. Isn't that awesome? No it isn't because if I didn't release the button (aka holding it) no new CHARACTER_INPUT will be emitted and the player excecuted it's action and nothing happens.

To solve this problem I came up with 6 classifications or types of GameActions:

Unstoppable - loops forever, can only be stopped by itself
OneTimeLooper - loops until getting stopped, always finishes task before getting interrupted
Looper - loops until getting stopped, can be interrupted any time
OneTimer - performs action only once and can't be interrupted while doing it
WeakWorker - Performs action once but can always be interrupted
Stopper - AntiAction: interrupts all types except unstoppables. Is a OneTimer

This would lead having a CHARACTER_MOVE action be a OneTimeLooper. It moves the attached actor until a CHARACTER_MOVE_STOP action tells it to do, being created because of an event originating from a keyUp() call.

But this solution smells bad to me, because then each Character/Actor/Player has to have more than one GameAction it can hold to. A Stopper must have access to it's counterpart to know if it is allowed to stop. Also shouldn't higher order classes like parent nodes have the power to stop an GameAction since they also created them?
Why not give LocalInputHandler power? How to change input style if you have a menu opened on top of the screen representing everything that happens in your world?

Clarifications and optional text:

LocalInputHandler and localPlayer are coupled by handing over LocalInputHandler the ID (represented by UUIDs, which I'm still not sure using because they are so big for networking applications) of localPlayer in construction. Each InputHandler whether be it a remote or ai InputHandler will only now by ID which actor they are handling and will refer to this ID when creating a CHARACTER_INPUT event by writing recepient = actorID into the event. The message of this event is a int[] keymap which holds information about which key is held down. keymap is a member variable of a InputHandler It could be a boolean[] but for now it's an int[] array. Parentnode of an actor takes these informations (recepientID and keymap) and packs a CHARACTER_MOVE GameAction into the event passing it down to the actor for consumption. In this process the keymap is being copied by calling .copy()on keymap because this will prevent opening a channel of direct communication from the InputHandler to the GameAction by not letting it just copy a reference but the array as a whole.


texts:
I'm currently building a Mars colonization game and I'm wondering if anyone can point me to resources on how to procedurally create resources and biomes within a 2d game. Much like in a game like Factorio were different resources and such are spread around the map.

Thanks in advance!


texts: Warp GameObject Size When Entering/Leaving Area

texts:
Below I have an image describing the desired functionality I am going for. Let's say you control a square and when you move this square into a given area, any part of your rigidbody/model inside of the area will be magnified upon entering and shrunk upon leaving. So now you more or less are made up of two rectangles, one small and one large.

What would be an elegant approach towards achieving this effect?


texts: Error in projecting coordinates from FitViewport to screen in LibGDX

texts:
i'm using a FitViewport to render my "game world". Viewport virtual dimensions are fixed 400x240.
I use viewport.unproject method to scale input touches from screen coordinates to world coordinates, and the values are good.

The problem begins when i use the opposite (viewport.project method).
I have to use it for drawing a sprite that is scaled for screen dimensions but i have X and Y positions in "game" coordinates.

Vector2 screenCoords = new Vector2();
screenCoords = (viewport.project(new Vector2(gameX, gameY)));

When i use viewport.project i only have the result i expect if the screen aspect ratio matches my game aspect ratio (so the viewport fits the whole screen).

I noticed that if screen height is higher (so my viewport is fitted horizontally and black bars appear below and above it) the X coordinate is fine, but Y coordinate varies slightly depending if the "game" Y coordinate is near upper or lower side.

Based on my knowledge and on javadoc comments i've red, the method must automatically recognize if the viewport is not full-screen or if it is not, and add an offset based on how tall the black bars are.

Am i doing something wrong???


texts:
I tried to implement indexed draw, but when I call I got nothing on screen. Even more strange that I wasn't get any error when call it and buffer variables packed right.

There my constructor:

Mesh::Mesh(Shader &shader, std::vector<GLuint>* indices, std::vector<VertexData>* vertices) {
shaderProgram = &shader;
_meshLenght = (GLsizei) indices->size();
_indices = indices;

glGenBuffers(1, &_ebo);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, _ebo);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices->size(), indices, GL_STATIC_DRAW);

//create one here
glGenVertexArrays(1, &_vao);
glBindVertexArray(_vao);

std::vector<glm::vec3> positions {};
std::vector<glm::vec3> normals {};
std::vector<glm::vec2> texture {};

for (size_t i = 0; i < vertices->size(); ++i) {
    positions.push_back(vertices->at(i).positions);
    normals.push_back(vertices->at(i).normals);
    texture.push_back(vertices->at(i).texCoords);
}

glGenBuffers(1, &_vbo);
glBindBuffer(GL_ARRAY_BUFFER, _vbo);
glBufferData(GL_ARRAY_BUFFER, sizeof(glm::vec3)*(positions.size()+normals.size()), nullptr, GL_DYNAMIC_DRAW);

glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(glm::vec3)*positions.size(), positions.data());
glBufferSubData(GL_ARRAY_BUFFER, sizeof(glm::vec3)*positions.size(), sizeof(glm::vec3)*normals.size(), normals.data());

glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, nullptr);
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 0, reinterpret_cast<const void*>((sizeof(glm::vec3) * positions.size())));

glEnableVertexAttribArray(0);
glEnableVertexAttribArray(1);
glBindBuffer(GL_ARRAY_BUFFER,0);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
glBindVertexArray(0);
}

And there my draw code:

void Mesh::Draw() {
glBindVertexArray(_vao);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, _ebo);
if (_ebo==0)
    glDrawArrays(GL_TRIANGLES, 0, _meshLenght);
else {
    glDrawElements(GL_TRIANGLES, _meshLenght, GL_UNSIGNED_INT, nullptr);
}
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
glBindVertexArray(0);
}

Also show my vertices info screenshot:

And if you need have apitrace trace file:
https://drive.google.com/file/d/0B-dWIpzqq91mQXVIeHhTOHFhRkU/view?usp=sharing


texts: How would a game-state snapshot system be implemented for networked real-time games?

texts:
I want to create a simple client-server real-time multiplayer game as a project for my networking class.

I've read a lot about real-time multiplayer network models and I understand the relationships between the client and the server and lag-compensation techniques.

What I want to do is something similar to the Quake 3 network model: basically, the server stores a snapshot of the whole game state; upon receiving input from the clients, the server creates a new snapshot reflecting the changes. Then, it calculates the differences between the new snapshot and the last one and sends them to the clients, so that they can be in sync.

This approach seems really solid to me - if the client and server have a stable connection, only the minimal necessary amount of data will be sent to keep them in sync. If the client gets out of sync, a full snapshot can be requested as well.

I cannot, however, find a good way to implement the snapshot system. I find it really hard to move away from single-player programming architecture and think about how I could store the game state in such a way that:

All the data is separated from the logic
Differences can be calculated between snapshot of game states
Game entities can be still easily manipulated via code

How is a snapshot class implemented? How are the entities and their data stored? Does every client entity have an ID that matches an ID on the server?

How are snapshot differences calculated?

In general: how would a game-state snapshot system be implemented?


texts:
I'm trying to load levels in XNA from XML files.
I have currently got a system to do this working, but it looks like it might get horribly complex as I add more objects later on.
My world currently consists of Planet entities along with physics props, scenery, static props, etc. It will later include NPCs, interactive machines, and a lot more content (but I want to sort this out before going any further).

Based on a tutorial I read, my level loader loads a LevelData entity from XML. This contains arrays of PlanetLevelData, PropData, and StaticData. My test file is as shown:

<?xml version="1.0" encoding="utf-8" ?>

<XnaContent>

<!-- TODO: replace this Asset with your own XML asset data. -->

    <Asset Type="DataTypes.LevelData">`

        <PlanetData>
            <Item>
                <Position>5.2 5.2</Position>
                <BodyRadius>300</BodyRadius>
                <FieldRadius>450</FieldRadius>
                <Name>Jupiter</Name>
                <Rotation>0</Rotation>
                <ImageName>-</ImageName>
            </Item>
            <Item>
                <Position>-2 -2</Position>
                <BodyRadius>300</BodyRadius>
                <FieldRadius>450</FieldRadius>
                <Name>Jupiter2</Name>
                <Rotation>0</Rotation>
                <ImageName>-</ImageName>
            </Item>
        </PlanetData>

        <PropData>
            <Item>
            <Type>Crate</Type>
            <Position>2 3</Position>
            </Item>
        </PropData>

        <StaticData>
            <Item>
                <Type>FromImage</Type>
                <Position>-4.5 -4.5</Position>
                <ImagePath>Lamp</ImagePath>
                <Rotation>2</Rotation>
                <Radius>0</Radius>
                <Vertices></Vertices>
                <PlanetOwner>Jupiter2</PlanetOwner>
            </Item>
        </StaticData>

    </Asset>

</XnaContent>

In other words, I have to put all my content files into arrays. However, for me to have different types of StaticData from the XML file, I have to specify the type with a String (called Type).

I then load the XML using Content.Load<LevelData>("name here.xml"). I go through every PlanetData in the array and create a new Planet based on it's properties. I also use switch statements based on the Type field to specify which type to create...

Is this the only way to load level data into objects using XML (I hope not, it's hideous to use). I couldn't really find much on this topic...


texts: Blender arm rig not working the way it should

texts:
I just bought a pair of arms from the unity asset store and imported them into blender, the IK seems to work just fine untill i use a Child of constraint on another bone(which is supposed to be a weapon) on the arm's wrist bone

the bone rotates but it wont move.

I'll leave a video of it right here,
https://www.youtube.com/watch?v=jfLmG2sQ_10

EDIT: the wrist bone seems to follow the child WHEN i disconnect the wrists parent, but if i do that the IK doesnt work in general.
Appreciate all help, thanks in advance :)


texts: Trying to figure out SDL pixel manipulation?

texts:
Hello so I've found code that plots a pixel in an SDL Screen Surface :

void putpixels(int x, int y, int color)
{
  unsigned int *ptr = (unsigned int*)Screen->pixels;

  int lineoffset = y * (Screen->pitch / 4 );
  ptr[lineoffset + x ] = color;

}

But I have no idea what its actually doing here this is my thoughts.

You make an unsigned integer to hold the unsigned int version of pixels
then you make another integer to hold the line offset and it equals to multiply by pitch which is then divided by 4 ...

Now why am I dividing it by 4 and what is the pitch and why do I multiply it??

Why must I change the lineoffset and add it to the x value then equal it to colors?

I'm soo confused.. ;/

I found this function here -> http://sol.gfxile.net/gp/ch02.html


texts: Originally I was doing all terrain calculations in a vertex shader and simple modifying the positions of the vertices from there. I would now like to use normal maps and I cannot think of any way of using these with this current method. So my question is: how can one create a heightmap (as a texture) on the gpu in a pixel shader? Thanks for any replies/suggestions.


texts:
I'll let the gif speak first.

As you can see, the small cube just kinda floats there like it has a forcefield. This weird glitch only happens with small cubes, smaller than 60 pixels for some reason. It's 32x32. And I have no clue why this happens, at all. I've debugged and debugged, but I am at my end.

Box class

//Header
class Box
{
public:
    Box(const std::string& _textureName, int _x, int _y, int _width, int _height, SDL_Renderer* _renderer, b2World* _world);

    void draw(SDL_Renderer* _render) const;
    void update();
private:
    SDL_Texture* m_image;
    SDL_Rect m_bounds{};

    b2PolygonShape m_polygon;
    b2FixtureDef m_fixture;
    b2BodyDef m_bodyDef;
    b2Body* m_body;
};

//CPP
Box::Box(const std::string& _textureName, int _x, int _y, int _width, int _height, SDL_Renderer* _renderer, b2World* _world) : m_image(IMG_LoadTexture(_renderer, _textureName.c_str()))
{
    SDL_QueryTexture(m_image, nullptr, nullptr, nullptr, nullptr);

    m_bounds.x = _x;
    m_bounds.y = _y;
    m_bounds.w = _width;
    m_bounds.h = _height;

    m_bodyDef.type = b2_dynamicBody;
    m_bodyDef.position.Set(_x / World::PPM, _y / World::PPM);
    m_body = _world->CreateBody(&m_bodyDef);

    m_polygon.SetAsBox((_width / World::PPM) / 2.0f, (_height / World::PPM) / 2.0f);

    m_fixture.shape = &m_polygon;
    m_fixture.density = 1.0f;
    m_fixture.friction = 0.3f;

    m_body->CreateFixture(&m_fixture);
}

void Box::draw(SDL_Renderer* _render) const
{
    SDL_Point center;
    center.x = m_bounds.w - (m_bounds.w / 2);
    center.y = m_bounds.h - (m_bounds.h / 2);

    const auto angle = (180 * m_body->GetAngle()) / M_PI;

    SDL_RenderCopyEx(_render, m_image, nullptr, &m_bounds, angle, &center, SDL_FLIP_NONE);
}

void Box::update()
{
    m_bounds.x = m_body->GetPosition().x * World::PPM;
    m_bounds.y = m_body->GetPosition().y * World::PPM;
}

World class

//Header
class World
{
public:
    static constexpr float PPM = 32.0f;
    static constexpr int VELOCITY_ITERATIONS = 5;
    static constexpr int POSITION_ITERATIONS = 8;

    World();

    void update();
    void render(SDL_Renderer* m_renderer);

    void createBox(const std::string& _textureName, int _x, int _y, int _width, int _height, SDL_Renderer* _renderer);
private:
    float m_timeStep;

    b2World m_world;
    b2BodyDef m_groundBodyDef;
    b2Body* m_groundBody;

    std::vector<Box*> m_boxes{};
};

//CPP
World::World() : m_world(b2Vec2(0.0f, 9.8)), m_timeStep(1.0f / 60.0f)
{
    m_groundBodyDef.position.Set(400.0f / PPM, 590.0f / PPM);
    m_groundBody = m_world.CreateBody(&m_groundBodyDef);

    b2PolygonShape groundBox;
    groundBox.SetAsBox(400.0f / PPM, 20.0f / PPM);
    m_groundBody->CreateFixture(&groundBox, 2.0f);
}

void World::update()
{
    m_world.Step(m_timeStep, VELOCITY_ITERATIONS, POSITION_ITERATIONS);
    for (auto box : m_boxes)
    {
        box->update();
    }
}

void World::render(SDL_Renderer* m_renderer)
{
    for(auto box : m_boxes)
    {
        box->draw(m_renderer);
    }
}

void World::createBox(const std::string& _textureName, int _x, int _y, int _width, int _height, SDL_Renderer* _renderer)
{
    m_boxes.push_back(new Box(_textureName, _x, _y, _width, _height, _renderer, &m_world));
}

If anybody has any idea why this might happen, please let me know. Thank you.


texts: How do I implement Breakout's "multiball" powerup?

texts:
I'm just starting out and making a breakout clone as my first game. I'm implementing all kinds of powerups, but I'm stuck on multiball. The powerup adds additional bouncing balls to the game.

So far, I've implemented powerups by just adding them to the Ball class as states. This is easy for increasing speed, making the ball sticky, changing sprites and such. When the ball is in one state it behaves in only one way.

Now, how do multiple balls fit into this? I suppose having more balls is more of a function of the game itself than the Ball, so it seems logical to make it a game state instead of a ball state. How would I do this?


texts: How to make the automatic movement of an actor and control that it does not go off the screen?

texts:
I have an actor in a class who then I put him in the main scene, but I want the actor to move randomly, that is, now he moves to the right, then down ... but controlling that he does not leave the screen either. I have tried some ways, but in some he would not move, others would go all the way to the left and loop. I have tried this that more or less does what I had in mind, but it is not correct because the character is shaking and sooner or later ends up leaving the screen. I'm just using this library and there are many things that escape me, any help or advice would be appreciated.
@Override
public void act(float delta) {
    super.act(delta);
    int number= (int)(Math.random()*4+1);

    switch (numero){
        case 1: this.setX(this.getX()-delta*80);break;
        case 2: this.setY(this.getY()-delta*80);break;
        case 3: this.setX(this.getX()+delta*80);break;
        case 4: this.setY(this.getY()+delta*80);break;
    }
    Rectangle.set(this.getX(),this.getY(),this.getWidth(),this.getHeight());
}


texts: Graphics programming replicating the transition from Chrono Trigger inside the gate

texts:
I started playing this game for the first time lately and this really peaked my interest

You can see the transition in motion starting at ~12:08

There seems to be some interesting maths taking place in there. It would appear that there are two different views combined together. The blue ripples are rendered first in the background and then the purple oscillating waves appear to be rendered on some sort of pseudo 3D projection.

How exactly they came to this result however is beyond me and curiosity has got the better of me.

I don't expect a lot of people would know how this is especially done but if anyone has done some extensive graphics programming, perhaps they could enlighten me.


texts: Why aren't resources such as Pixmap disposed on finalization in LibGDX?

texts:
I've been looking at the LibGDX framework, and certain classes such as Pixmap require to be disposed manually when you are no longer using them (call the dispose method).

I'm wondering, since this is Java, why did they not choose to dispose the resources on Pixmap finalization? That is, override the finalize method to automatically call dispose. If an object is finalized, then that means that the Garbage Collector determined no hard references to it, so clearly no one is using the Pixmap and it is fine to dispose it.

What particular advantages are there to calling it manually rather than use the finalization method?


texts: Drawing a partial sprite with batch-LibGdx

texts:
I have a sprite like this.

I want to draw this sprite in such a way that sprite is growing from bottom to top, using sprite batch on tap.for that,I have written the following code:

  if (MyInputProcessor.isTap)
{
Sprite stickSprite = new Sprite(stickTexture);
stickSprite.setPosition(stick.getX(),stick.getY());
for(float n=0;n<100;n++)
{
     float i = 0.01f * n;
    batch.draw(
    stickSprite.getTexture(),
     stick.getX(),
     stick.getY(),
         stickSprite.getWidth() / 2,
         stickSprite.getHeight() / 2,

         stickSprite.getWidth(),
         stickSprite.getHeight()*i,  //multiplying with height
         stickSprite.getScaleX(),
         stickSprite.getScaleY(),
        0 ,
        stickSprite.getRegionX(),
        stickSprite.getRegionY(),

        stickSprite.getRegionWidth(),
        stickSprite.getRegionHeight(),
        false,
        false);

 }
MyInputProcessor.isTap = false;

}

Here the i value increments but not taking effect in the code to scale.
Whats wrong with the code?

I tried this also:

   private void drawStick() {

    Sprite stickSprite = new Sprite(stickTexture);

    if (MyInputProcessor.isTap)
    {
       stickSprite.setPosition(stick.getX(),stick.getY());
       for(float n=0;n<=100;n++)
       {
        float i = 0.01f * n;
        stickSprite.setSize(stickSprite.getWidth(),stickSprite.getHeight()+i);
        }
    }
  stickSprite.draw(batch);

But rendering full sprite only.


texts: How do I change windows commands to android commands?

texts:
I created a game and would like to test it on android, but it does not respond to any touch on the screen, I think it's because I have to adapt the game code for android. Click => Touch

I developed it and tested it with the selected target (windows):

I was able to put it to run on an android virtual machine, but it does not respond to any commands:

How could he do that?

How to adapt the function => if (point_in_rectangle(window_mouse_get_x(),window_mouse_get_y(),60,250,104,313)) && config==false for example? For something that works for android.

I hope I have been clear. What I want exactly is to turn all game mouse clicks into screen touches.

Sorry for any translation error and thank you already


texts: How to make a 2D neon-like trail effect in Unity

texts:
Recently I've been toying around with neon-ish effects for a game I'm making and wanted to share my results with you.

If you guys have any other methods of achieving this result, please be sure to share.


texts: DirectX9 fullscreen, render immediately?

texts:
Is it possible, somehow to avoid the single frame of black that appears before a DirectX9 window is displayed in fullscreen? My code looks like this.

INT WINAPI wWinMain( HINSTANCE hInst, HINSTANCE, LPWSTR, INT )
{
WNDCLASSEX wc = { sizeof( WNDCLASSEX ), CS_CLASSDC, MsgProc, 0L, 0L, GetModuleHandle( NULL ), NULL, NULL, NULL, NULL, L"D3D", NULL };
RegisterClassEx( &wc );
LPDIRECT3D9         pD3D = NULL;
LPDIRECT3DDEVICE9   pd3dDevice = NULL;
int                 windowWidth = 1280;
int                 windowHeight = 1024;
int                 adapter = 3;
bool                fullscreen = true;

if( NULL == ( pD3D = Direct3DCreate9( D3D_SDK_VERSION ) ) )
    return E_FAIL;

HWND hWnd = CreateWindow( L"D3D", L"D3D Test", WS_VISIBLE | WS_POPUP, 0, 0, windowWidth, windowHeight, NULL, NULL, wc.hInstance, NULL );

D3DDISPLAYMODE d3ddm;
pD3D->GetAdapterDisplayMode( adapter, &d3ddm );

D3DPRESENT_PARAMETERS d3dpp;
ZeroMemory( &d3dpp, sizeof(d3dpp) );

d3dpp.Windowed               = !fullscreen;
d3dpp.SwapEffect             = D3DSWAPEFFECT_DISCARD;
d3dpp.BackBufferFormat       = d3ddm.Format;
d3dpp.EnableAutoDepthStencil = TRUE;
d3dpp.AutoDepthStencilFormat = D3DFMT_D16;
d3dpp.PresentationInterval   = D3DPRESENT_INTERVAL_ONE;
d3dpp.BackBufferCount        = 1;
d3dpp.BackBufferWidth        = windowWidth;
d3dpp.BackBufferHeight       = windowHeight;
d3dpp.hDeviceWindow          = hWnd;

if( FAILED( pD3D->CreateDevice( adapter, D3DDEVTYPE_HAL, hWnd, D3DCREATE_HARDWARE_VERTEXPROCESSING, &d3dpp, &pd3dDevice ) ) )
{
    return E_FAIL;
}

MSG msg;
ZeroMemory( &msg, sizeof( msg ) );
while( msg.message != WM_QUIT )
{
    pd3dDevice->Clear( 0, NULL, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, D3DCOLOR_XRGB( 255, 255, 255 ), 1.0f, 0 );
    pd3dDevice->Present( NULL, NULL, NULL, NULL );

    if( PeekMessage( &msg, NULL, 0U, 0U, PM_REMOVE ) )
    {
        TranslateMessage( &msg );
        DispatchMessage( &msg );
    }
}

if( pd3dDevice != NULL )
    pd3dDevice->Release();

if( pd3dDevice != NULL )
    pd3dDevice->Release();

UnregisterClass( L"D3D", wc.hInstance );
return 0;

}


texts: How do you organize your game files and classes?

texts:
Although it isn't necessary to exclude things like graphics and audio packages, I'm most interested in the organization of the folders for classes that deal with AI and game state. I'm thinking something like this in Java using packages as the example:

import com.rpg.characters;
import com.rpg.characters.antagonist;
import com.rpg.characters.neutral;
import com.rpg.characters.protagonist;
import com.rpg.characters.state;
import com.rpg.gameplay;
import com.rpg.gameplay.engine;
import com.rpg.gameplay.maps;
import com.rpg.weapons;

Also, does it make a huge difference between 2d and 3d games?


texts: What is an acceptable GC frequency for a SlimDX/Windows/.NET game?

texts:
I understand that the Windows GC is much better than the Xbox/WP7 GC, being that it's generational and multithreaded -- so I don't need to worry quite as much about avoiding memory allocation.

SlimDX even has some unavoidable functions that generate some amount of garbage (specifically, MapSubresource creates DataBoxes), yet people don't seem to be too upset about it.

I'd like to use some functional paradigms to write my code too, which also means creating objects like closures and monads.

I know premature optimization isn't a good thing, but are there rules of thumb or metrics that I can follow to know whether I need to cut down on allocations? Is, say, one gen 0 GC per frame too much?

One thing that has me stumped is object promotions. Gen 0 GCs will supposedly finish within a millisecond or two, but if I'm understanding correctly, it's the gen 1 and 2 promotions that start to hurt. I'm not too sure how I can predict/prevent these.


texts:
Despite being a long-time developer I've never played with JavaScript libraries or any sort of graphics development.  With my son we're trying to create something interesting and are using createjs/easeljs as our vehicle of choice.

That said, we are going through a number of tutorials and can't determine why this isn't working.  The ball image does display but the on-click method code does not cause the image to scale.  The onBallClick method is being called so we suspect the reference is simply wrong somehow.

        var preload = new createjs.LoadQueue();
        var stage = new createjs.Stage("demoCanvas");

        function loadImage() {
          preload.addEventListener("fileload", handleFileComplete);
          preload.loadFile({id:"ball", src:"assets/ball.png"});
        }
        function handleFileComplete(event) {
          document.body.appendChild(event.result);
          event.result.addEventListener("click", onBallClick)
        }
        function onBallClick(event)
        {
            var ballImage = preload.getResult("ball");
            var bitmap = new createjs.Bitmap(ballImage);
            bitmap.scaleX = 0.5;
            stage.update();
        }

There are no errors in the developer console so we're trying to determine what is the correct reference to the bitmap.

We tried to do createjs.Bitmap(event.result) in handleFileComplete but event.result has a type of [Node] so we're not sure what to do with that but it doesn't appear useful for purposes of the createjs.Bitmap() statement.


texts: Can I force a manually created texture to not be divided with low quality?

texts:
I have a texture that I have created that looks something like this:

.

This is a very low texture map, but it helps me in a shader that I'm making that distinguishes between land and ocean, the ocean tiles do different things than the land. To try and figure out what was going on, I used the shader to turn the ocean, as defined by the mask, black. Note that this image doesn't match the ocean texture example from above, but it's the best I had...

The ocean is a binary color, either it is ocean or isn't, and is set appropriately. But what I'm actually seeing is that if the 2x2 tile area has mixed land/ ocean, the value is averaged.

What I've noticed is that the pixels were combining together, a 2x2 pixel area was averaged. After tracing through this for some time, I discovered that the issue was a quality setting that reduced the resolution of certain images.

There are some images that I don't mind lowering the resolution of, but images such as this one I absolutely don't want to lower the resolution. Is there a setting that I can add to a runtime generated texture to tell it not to reduce it's resolution if requested to by the quality settings?

EDIT: Code fragments to produce the results above. It's kind of hard to pull just the fragments that produce this code and not produce an overwhelming bit, but hopefully this will do.

Code to generate textures:

Color32[] windMask=new Color32[world.width*world.height];
for (int x = 0; x < world.width; x++)
{
    for (int y = 0; y < world.height; y++)
    {
        windMask[x + world.width * y] = world.Tiles(x, y).baseType == Tile.BaseType.Ocean?new Color32(255,255,255,255):new Color32(0,0,0,255);
    }
}

sharedMaterial.SetTexture("_WindMask", TextureUtilities.TextureFromColors(world.width, world.height, windMask, FilterMode.Point));

public static Texture2D TextureFromColors(int width, int height, Color[] colors, FilterMode filterMode = FilterMode.Trilinear)
{
    Texture2D texture = new Texture2D(width, height);
    texture.SetPixels(colors);
    texture.filterMode = filterMode;
    texture.Apply();
    return texture;
}

The Shader code:

o.Albedo *= 1 - tex2D(_WindMask, IN.uv_MainTex).r;

The "Fastest" quality settings that show the issue:

The "Fantastic" quality, which correctly isolates the ocean.

Image of the correctly isolated ocean:

The issue is the "Texture Quality", which you will note for the fastest setting is half resolution. I would really like to keep the ability to use lower resolution in the game, but have a few textures that do not use the lower resolution if the quality settings change.


texts:
I want to know how the algorithm works in this game:
http://www.gametrailers.com/user-movie/cloud-the-game/45068

Especially how the game generates the real time cloud, and be able to merge with other clouds dynamically.

I tried to google some info, but was unable to find the useful information.
Probably because I used to wrong keywords


texts: Variable value in inspector is not updating automatically?

texts:
Something weird is happening when I change a variable value in script and hit play the var value doesn't update I have to reset the script in inspector. Is this normal? Aren't the values suppose to update when we hit play?

The Simple Code I used to test this:

var a:int=0;

function Start () {
print(a);
}


texts:
I am tasked with developing a game for kids with low dexterity (as a college project).
I am stuck trying to find examples of similar games to generate ideas about game play and overall function. The general idea is that these kids wont be using a fully featured controller, it will be more basic, for example just a joystick.

Can anyone point me in the direction where I might find some resources (specifically game play ideas) to aid the in the development of low dexterity games?


texts:
I have a Pygame game, and I was wondering if there was any way to embed it into a webpage to make it easily playable, or if there is a games website that accepts Pygame games.

EDIT: I am now using Unity and am not after the answer anymore, but please answer if you want as it could help others.


texts: Transparency problem / Expanding material fixes it magically?

texts:
i stumbled upon a problem, can't figure out what's the reason and how to solve it.

I have glass-windows which use just the standard (specular setup) shader.
in the first place when the model is added to the scene the glass looks like this (wrong !)

Then JUST by clicking on the little arrow to deploy the extra infos about the material the glass suddenly looks like it is supposed to look :

Is this a unity bug ?
i actually change absolutely nothing, just click the material.

Is there a way to force this to occur on itself ?
i tried by disabling an re-enabling mesh renderer but it does not do the trick.

edit: seems that putting rendering mode to anything else and setting it back to transparent helps to obtain the same result as clicking the little arrow.
nevertheless this is very strange

thanks for any help


texts:
Inside an entity class:

public boolean onScreen(Camera camera){
    if(position.x + getWidth() > camera.position.x
            && position.x < camera.position.x + camera.viewportWidth
            && position.y < camera.position.y + camera.viewportHeight
            && position.y + getHeight() > camera.position.y){
        return true;
    } else {
        return false;
    }
}

The function returns false even when the entity is on the screen. What am I doing wrong?


texts: Can I mod Among Us mobile so people don't get kicked because of network problems, and how?

texts: I want to make a mod for Among Us which will allow people to stay in game despite short-lived connection problems (as opposed to being kicked after 1 second of network issues).


texts: Panda3D documentation, manual, and tutorials for offline viewing?

texts:
Is there a way to get the Panda3D's manual and tutorials available for offline viewing? I'm going on a business trip and I will spend a good deal of time at the airports and on long flights. I'd love to get started on Panda3D while in flight. Is there a way to get all that information available for offline, or use some program to download the tutorials and manual webpages?

Thanks


texts:
So I wanted to switch to IDirect3DDevice9Ex, purely for the SetFrameLatency function, as fullscreen vsynced D3D seemed to produce noticable input lag.

But then it tells me 'ha ha ha! now you can't use D3DPOOL_MANAGED!':

Direct3D9: (ERROR) :D3DPOOL_MANAGED is not valid with IDirect3DDevice9Ex

Is this really as unpleasant as it looks (when you're relying quite heavily on managed resources) - or is there a simple solution?

If it really does mean manual management of everything (reloading all static textures, VBs, and IBs on a device reset), is it worth the hassle, will IDirect3DDevice9Ex bring enough benefit to make it worth writing a new resource manager?

Starting to think I must be doing something wrong, due to this:

Direct3D9: (ERROR) :Lock is not supported for textures allocated with POOL_DEFAULT unless they are marked D3DUSAGE_DYNAMIC.

So if I put my (static) textures in POOL_DEFAULT, they need flagging as D3DUSAGE_DYNAMIC, just because I lock them once to load the data in?


texts: Sync clocks on a real time multiplayer game - Is this ok?

texts:
I'm developing a multiplayer game through Gamecenter in unity with prime31 plugin. This is how I sync the clocks of the two players (right now there will only be 2 player in one match), and I wanted to now if it's ok:

This is done one time at the start of the match.

I have device A and device B.
Device A resets it's game clock to 0.0f.
A sends a reliable message to B saying that A has reset it's game clock.
B recieves the message and resets his game clock as well and sends a message to A saying he has also reseted the clock.
A recieves the message and does the following.

float delayAtoB = getCurrentTime() / 2;
setGameClock(delayAtoB);

delayAtoB is actually this the time it took to get to B, so right now the two devices have the same clock. It works ok, but I wanted some opinions because I'm not sure if it's the best way and some exceptions might ocur..


texts: how do I instantiate something with only the y axis rotation matching the instanciators y rotation

texts: i'm making a swimming mechanic for my game and i need to instantiate the swim camera under neath the fps player when it hist the water. no mater what I try the swim cam wont have the same y rotation as the fps when its instantiated, and vice versa. what am i doing wrong? here is the scriptInstantiate(swim, new Vector3(transform.position.x, transform.position.y -2, transform.position.z), rotation: transform.rotation=Quaternion.AngleAxis(0,0,0));


texts:
I'm trying to get the blend of two images to work without luck.

I have a render target on which I have an object, then I want to render again the same object in same position but with different light condition. My goal is to add the result of this two render so I tried to do something like:

glEnable(GL_BLEND);
glBlendFunc (GL_ONE , GL_ONE);

....
glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
render on render target A
change light condition
do not clear now
render on render target A again with new light condition
glDisable(GL_BLEND);
display render target A

I am surely missing something because not only just the first image shows, but the object is transparent.

I am extremely sorry if the question is stupid but I'm very new to such things.  Thank you.

edit
Following the answer of @Sam Johnston I've edited my code but, although I solved the transparency, the results are not added (to make sure of this I render one with a completely red light and one with a green light) together, but I get just the first render as result:

glEnable(GL_BLEND);
glBlendFunc (GL_ONE , GL_ZERO);
glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
render on render target A
change light condition
glBlendFunc (GL_ONE , GL_ONE);
do not clear now
render on render target A again with new light condition
glDisable(GL_BLEND);
display render target A

Have I misunderstood the answer?

Juan


texts: Non axis aligned bounding box collision and physics

texts:
Exactly how much more expensive, and while we're at it, difficult, is it to have non-axis aligned bounding boxes in your framework?

I realise that it very much depends on what you're trying to do, so here's a little bit of detail; My small demo framework has a number of bots running around shooting each other. when they die, they explode into cubes. When they're hit, or the bullets miss and hit a wall; more cubes.

At the moment I'm taking advantage of the fact that my framework has no floor, just walls, so you can't really tell if the cubes are resting exactly on the floor or not - as a result I'm using bounding spheres as a cheats collision detection. The main visual problem is when a bot dies from a point blank shot; the middle of the agent blows out backwards but the bottom and top parts sort of collapse into a little pile of cubes.

I'd love to be able to have much more realistic physics on all the cubes so they collide and tumble realistically over one-another.

How would I go about achieving this? and how feasible is it? to have a little physics engine which is just cube on cube.


texts:
This is related to MMO Performance except that question is about bandwidth. This is about cpu load.

I put together a simple FPS using node.js and webGL. It's extremely simple, a lot like the BuddyMaze clone of MIDI Maze. There's very little going on, everyone moves in two dimensions (no height), shoots simple projectiles, and runs into walls.

Right now, if I make multiple connections to the server where every player shoots rapidly while spinning in circles, I can get about 15 - 20 players in the game before the server maxes out a core and slows way down. And this is when running at 30 fps on the server. At 10 fps, I get about 25 - 30 connections. This is pretty bad, since the game is going to have a lot more to do soon and I'll need to fit more players for this to be a feasible endeavor.

My brother just pointed out some stats about his coworker's TF2 server. His server is lower specs than ours, yet it runs TF2, obviously a much more complex game, at a whopping 500 ticks per second, with 36 users per core. Also, we currently consume much more bandwidth than they do, but we haven't been trying to lower that much yet.

How is this possible? What sort of tricks are there to increase server performance to this magnitude? Some things that I know of include:

Lowering framerate on the server, and interpolate positions on the client. I got some benefit, but clearly the TF2 server doesn't even bother with this.
Doing expensive things like collision detection on the client, and verify it infrequently on the server. I haven't moved this over just yet, I will tonight. Even so I don't expect such an enormous gain.
Break the playing field into regions (quad trees) to minimize calculations. Haven't had an opportunity for this yet.
I've considered the unfortunate possibility that node.js is just way slower than whatever TF2 is using, and may not be suited for this kind of high intensity task.
Is it all in the server configuration magic?

So what are the other tricks of the industry to do only the minimum required on the server but still have a flawless game experience? There's a big conflict between "defer to client to save cpu time" and "don't trust the client", so maybe it helps to know where the line is drawn in various situations?

Update

Profiling really is the only mantra I've ever found that's absolutely infallible. I quickly wrapped some timing functions around my code (thanks, FP!) and discovered what I never expected: the act of broadcasting the data to clients accounts for nearly all of the execution time. Specifically, around 90% of it. Further testing showed that this time is dependent on both the number of clients and the size of the data, but more so the latter. On a 20 user load, I cut my broadcast time 90%, from 24ms down to just over 2ms by sending only "{}" instead of the full data. But with only 5 users, broadcasting takes around 0.5 ms. So I clearly need to do some optimization here.

The first most obvious improvement is line of sight checking. This would decrease both the number of people who care about data, and also the amount of data sent to interested parties. Are there other tricks in this realm I can try, which focus on minimizing the cost of my broadcast operation?


texts: How to animate material alpha property via script?

texts:
I am creating Animator OverrideController via script based on current controller assigned to animator component. I have created animation curve for position and it works. When i try to animate transparency (material color alpha) it does not work (it does not make any effect, however in Animation Dopesheet there is yellow line: "Object name : Material.Color.a (Missing!)"). Did I fail to properly access this property or is it the consequence that creating animation via script works only for legacy animations with Animation component?

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

public class AnimationScript : MonoBehaviour {

    void Start()
    {
        AnimationClip clip = new AnimationClip();

        AnimationCurve curve = AnimationCurve.EaseInOut(0.0f, transform.position.x, 1.0f, transform.position.x);
        clip.SetCurve("", typeof(Transform), "localPosition.x", curve);

        curve = AnimationCurve.Linear(0.0f, 1.0f, 1.0f, 0.0f);
        clip.SetCurve("", typeof(Material), "_Color.a", curve);

        Animator anim = GetComponent<Animator>();
        AnimatorOverrideController animatorOverrideController = new AnimatorOverrideController(anim.runtimeAnimatorController);
        // "loop" is the name of clip not name of state
        animatorOverrideController["loop"] = clip;
        anim.runtimeAnimatorController = animatorOverrideController;
    }

}

However analogous code for legacy Animation component works:

void Start()
{
    Animation anim = GetComponent<Animation>();
    AnimationCurve curve;

    // create a new AnimationClip
    AnimationClip clip = new AnimationClip();
    clip.legacy = true;

    // update the clip to a change color
    curve = AnimationCurve.Linear(0.0f, 1.0f, 2.0f, 0.0f);
    clip.SetCurve("", typeof(Material), "_Color.a", curve);

    // now animate the GameObject
    anim.AddClip(clip, clip.name);
    anim.Play(clip.name);
}

What am I missing and why is first script not working?


texts:
What's a solid way to have a character stuck to another one?

I have a moving character (say followed) and I want a second one (say follower) to follow the first without chance of getting stuck into obstacles.

I thought that I could save every delta velocity vector of the followed and having the follower consuming one each frame after it reached its target's starting position.

More to say, dynamic obstacles could be an issue.

Since this sounds to me like a common topic (despite the fact that I'm having difficulties in finding answers), is there anyone who could enlighten me on a proper way of facing the issue?

Edit:

Since I'd like to describe something more like to an edge case of a pathfinding algorithm, consider the following:

follower should always be at a fixed position related to followed
follower must not necessarily interact with the environment the way followed does


texts: xna: Methods for having sprite characters in 3d game?

texts:
Methods for having sprite characters in 3d game?
I am making a game much like Doom. The world is 3d but objects and characters are 2d sprites. I am not asking about billboarding objects. I am asking about methods for having sprite characters that aren't always facing the player and have different frames depending on which way the character is facing. For example when an enemy is walking towards the player it is a 2d texture of a front and when walking away it is a 2d texture of a back.

One way I thought I read about was to draw a cube primitive that is "invisible". This 3d cube allows you to track the orientation of the character. Then you apply a sprite frame to each side of the cube but the 2d texture is only drawn on the side the player is looking at.

The other way I suspected I could do this is to make a 3d plane in a modeling program and import it to XNA. Then use the billboarding method to make sure the plane is always facing the player (you don't see the edge). Apply a the appropriate 2d texture (sprite frame) to the plane based on the direction the character is facing.

I know this is not how Doom did it but please tell me what you think of my ideas or a method on how this can be done.

Thank you.